#discord-bots
1 messages Β· Page 1051 of 1
like what?
in order to get data from different discord objects , like members, guilds channel etc
you need to access them by having intents
basically like the perm in order to access those data
oh so thats why!
client = discord.Client(intents= discord.Intents.default()) voila
yep
no type errors anymore thankuu
yw
capital I what i needed i guess XD
lol
:DDD
thks even tho ur helping another person lol
yes im learning the basic
cool
im kinda late learner
i start to learning rn and i learn after a few months of not doing code at all
lol
lol
i rarely dm people. i only dm them when its important
how to get user by id
When already playing a song in disnake, is it possible to play a sound clip over top either by pausing the current or better yet without pausing the already playing song?
!d discord.Client.get_user
get_user(id, /)```
Returns a user with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
To play another sound, u need to pause the current one and then play another one
Can you resume the previously playing sound once the new sound is finished?
import discord
from discord.ext import commands
import bs4
from googlesearch import search
TOKEN = ""
bot = commands.Bot(command_prefix="ds!")
@bot.event
async def on_ready():
print("We have logged in as {0.user}".format(bot))
@bot.command()
async def search(ctx,*, query):
await ctx.channel.send(f"Answer:")
async with ctx.typing():
for ans in search(query, tld="co.in", num=10, stop=10, pause=2):
await ctx.send(f"\n:point_right: {ans}")
bot.run(TOKEN)
``` Hey! can someone help me with this? it isnt working
I think you will need to give more information about what is happening because even though that code is short it is not good practice to expect others to parse through your entire code base without even telling them what the error is or exception you encountered
Well, u will have to manage it yourself... Lemme do some digging for u, tho
@client.command()
async def roles(ctx):
select = Select(options=[
discord.SelectOption(label="Bloody Red", emoji=":dotred:", description="Red Color")
])
view = View()
view.add_item(select)
await ctx.send("Choose a color!", view=view)
async def my_callback2(interaction):
if select.values[0] == "Fun Commands":
member = ctx.message.author
role = get(member.guild.roles, name="ΛΛΛκ° π κ±")
await interaction.response.send_message(content="Gave You <@&93628772078177487>", ephemeral=True)
how can i add the role to the user who clicked on the option
interaction.user.add_roles()
help
and after that i can use the reponse right?
response*
yes
interaction failed
The id_ is inputed as a string, and then you try to fetch as if it were an integer. Do: ```py
async def reroll(ctx, channel: discord.TextChannel, id_: int):
What's the error?
nothing in console
@client.command()
async def roles(ctx):
select = Select(options=[
discord.SelectOption(label="Bloody Red", emoji=":dotred:", description="Red Color")
])
view = View()
view.add_item(select)
await ctx.send("Choose a color!", view=view)
async def my_callback2(interaction):
if select.values[0] == "Fun Commands":
member = ctx.message.author
role = get(member.guild.roles, name="ΛΛΛκ° π κ±")
await interaction.user.add_roles(member, role)
await interaction.user.send_message("Gave you <@&936287720781774870>", ephemeral=True)
select.callback = my_callback2
As far as I can see you never call my_callback2.
oh wait
lemme do it
still says failed
Managing myself is totally fine, I just want to figure out means to do it, even if it is difficult if it allows me either of those above-described features I am willing to do it. Thank you sincerely for doing the digging! I am also digging and trying to look at options
Try adding await ctx.defer() in the beginning, it will make the API wait longer for the response.
I promise this would be my last question for the day but how do I check players if have a specific role and how to give the role?
after async def roles(ctx):?
or above the callback
Yes
if role in user.roles:
#something do here
else:
await bot.add_roles(user, role)```
do i need to import or add a var?
u mean create a var
yes
what is lambda? is it a var?
!d lambda
An anonymous inline function consisting of a single expression
which is evaluated when the function is called. The syntax to create
a lambda function is lambda [parameters]: expression
try async for entry in role.guild.audit_logs(limit=1, action=discord.AuditLogAction.role_create):
ty
still says failed
ok let me try
cool
replit is a bit lagging
Well I'm just tryna find out how bots seek audio
That's what u need
async for entry in role.guild.audit_logs(limit=1, action=discord.AuditLogAction.role_create):
channel = guild.get_channel(976462750438014976)
logs = logs[0]
if logs.target == role:
await channel.send(f'{logs.user} Created Role.')```
traceback?
ye
nvm it still says failed
there is seems to be a error here
@client.event
async def on_message(message):
if message.content == "!checkrole":
role = discord.utils.find(lambda r: r.name == 'Member', ctx.message.guild.roles)
if role in user.roles:
await message.channel.send("Yay!")```
async for entry in role.guild.audit_logs(limit=1, action=discord.AuditLogAction.role_create):
logs = entry
channel = guild.get_channel(976462750438014976)
logs = logs[0]
if logs.target == role:
await channel.send(f'{logs.user} Created Role.')```
this the code
obv fix the identation
so change the bot to client again?
@slate swan try that ^^
oh fu- ur arent talking to me srry
async def on_message(message):
if message.content == "!checkrole":
role = discord.utils.find(lambda r: r.id == role_id, message.guild.roles)
if role in user.roles:
await message.channel.send("Yay!")```
ye its the identation
fix it on your end
like this
like this but no embed but ur rest of code
where do i put the id?
ok
As far as I am aware the mechanism by which sound is played is that the audio is broken up into 20 Ms chunks and effectively sent as a stream of those chunks
channel = guild.system_channel #getting system channel
if channel.permissions_for(guild.me).send_messages: #making sure you have permissions
await channel.send("I'm online!")
send ur code and traceback i will show u
i tried it and the bost dosnt reply
error?
...
yep.. lol
How do i find message by id in bot
also can u help me
how to withdraw all members on guild, bots, and users?
!d discord.ext.commands.Context.fetch_message
await fetch_message(id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") from the destination.
i made a auto mod
i am , send me ur code and traceback
I used this
meaning?
Yet its saying no attribute fetch_message
it dms the user. it works but theres an error
u obv used the wrong attr
What object are you using for it.
whats the error?
amount
it works tho but it make some errors
members {len(bot.users)} bots {len(bot.guilds)}
ye show the eror
dm = await user.create_dm()
if any(word in msg for word in Bannedword)
if message.channel != "πβ€logs":
await deletemsg
response = await dm.send(f"<@{message.author.id}> hey watch your language! :Bonk:"```
Well you can use either, Context, Messageable, DMChannel, GroupChannel, Member, TextChannel and User
Not Bot or Client.
wait replit is slow
This is old code I recommend something else.
I want to edit bot old message
channel.fetch_message
Then how i do it
Thus you need to fetch it use either one of those objects.
^^
for your case its probably a textchannel,, so get the textchanel object then fetch the message
ugh replit is so slow
This One?
dm = await user.create_dm()
if any(word in msg for word in Bannedword)
if message.channel != "πβ€logs":
await deletemsg
response = await dm.send(f"<@{message.author.id}> hey watch your language! :Bonk:"
can u just fix the code? cause it seems that i cant run the repl
whats the error
It worked I was using event on_button_click with object interaction
i cant run it. i cant get the error
there we go i ran it!
What's your python knowledge level
If it's low I would recommend learning a bit more, if it is decent your code still needs improvements I can tell you about
im new to python
thats what im doing tho. im not making a bot to be publish im making a bot for fun so i can learn
Gotta tell you it's not a good idea to start learning python from a discord bot
Search for some courses
i wanna learn python for discord bot
You can't do that
Repl?
I mean you can but it's not a good idea
yes
Replit for discord bots is not a good idea as well
no i wanna learn python for discord bot nothing more.
Don't start learning python from discord bots, learn the python itself at least to OOP level
You can't make bots without that knowledge
i do watch python totorials
Which?
idk .-. i dont remember the channel name
hey man, I'm just starting :> and i wanna start on the simplest thing i know
Replit is the simplest?
for me .-.
cause i have more experience on it
Why
And how
idk .-. i just like replit.
how to compare author's and member's roles of ?
what exactly is ur issue
?
You probably havent enabled the message content intent
@client.event
async def on_message_delete(message):
msg = str(message.author)+ 'deleted message in '+str(message.channel)+': '+str(message.content)
channel = discord.utils.get(message.guild.channels, id = 974273896377368606)
await channel.send(msg)
yeah
since you have message.content in your code
omg who can help me? i think it's not a over hard question
nope
u will have an error 'Event loop is closed' if u will be use intent item without turned-on intent in discord developers portal
what?
Omg I want to see the bonk emoji
its a gif
Thx love it
ok??
I will tell you a secret:
when i the first time get this error, i search solution mb 2 days, because i thought it's asyncio error
but it's intents error
if u forgot to request for it, then you'll prolly have to wait till verification shit
and after that, request for intent again by making new ticket
i will be cry...
help meeeeeee
nono
i replied not that message
how to compare author's and member's roles of ? omg who can help me? i think it's not a over hard question
eh.. just get their roles? and compare it?
oohoo
then get their roles & iirc, the roles are arranged in increasing order of their position
so from there.. get the last role from the list & check its position.. then compare it @terse coyote
how to then compare it.... idkπ
I just said it π
oh
!d discord.Member.roles
property roles```
A [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role") that the member belongs to. Note
that the first element of this list is always the default [β@everyone](mailto:'%40everyone)β
role.
These roles are sorted by their position in the role hierarchy.
where
this will give u the list of roles that they have
and the list will be in increasing order of their roles as per their position
and then ^^^ @terse coyote
i was inspired recently to create a private bot for my server. now, im essentially new to coding, python or otherwise so forgive my ignorance π
what im currently stuck on is creating an input for a RPG style discord bot, where i can create branches (think of a make your own adventure book). However i cannot find how to stop my code from simply looping itself. A friend (he writes other coding languages but not Python) suggested using States, but they seem rather complicated in Python (at least to my brain).
In essence, im trying to create a number of "rooms" which you can enter and leave, and the program remembers where you are between inputs.
I suspect the answer is very simple, but any help would be hugely appreciated!
i can get my bot to reply to the first command (in my case i set it to &start) but then it loops back and wont accept any further commands except for start again. its clearly not awaiting further input, but idk how to code it so it does. ie, type so if i &start, then i can choose option A or B which then branches out further, and so on
Umm I put this code and it aint workin```py
await self.bot.invoke('ping')
it's a context method, not a bot method
and you're suppose to pass command object, not command name
!d discord.Embed give look here
class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed...
!d discord.ext.commands.Bot.wait_for
wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message,
or to react to a message, or to edit a message in a self-contained
way...
@jagged adder ^^ for u
discord.Embed(
title = "Netflix",
color = discord.Color.red(),
description = 'Watch movies & Shows'
)
``` this shuold do
and from here do what u suggested to other ppl :>
use random module & send it in description or where u want
my answer is still same
!d random.randint
random.randint(a, b)```
Return a random integer *N* such that `a <= N <= b`. Alias for `randrange(a, b+1)`.
!d random.choice he should use
random.choice(seq)```
Return a random element from the non-empty sequence *seq*. If *seq* is empty, raises [`IndexError`](https://docs.python.org/3/library/exceptions.html#IndexError "IndexError").
he already has list
could this be used in my instance where i want to navigate around say a room, looking at different things (my programmed inputs, ie A or B in this case)?
And how would i be able to loop back to the same spot? tbh it would be very helpful if u could take a look at the code in dms and make sure it would work as intended
bro.. use random.choice to get the random response.. and put it in embed π
eh.. pls no, not DM π it's not a help channel
soz :p
and, you can take input
but for going back to same spot.. you'll have to think of it yourself π€
no
it is self explanantory
and you're adivcing other ppl to read docs.. π i think u should go and read docs of random & discord.Embed
my friend can write it using the State command, but thats not supported as a command in itself in python :l
and i cant go using the discord.py api in the language he was using :l
wtf is sstate command π i'm feeling dumb
i only knwo about prefix & slash command.. wot is state command?
u can ask for help here anytime
lmao
I had to delete it because mods will think its an advertisement.
you don't know what's a state command??
then why post it at first place?
π© no.. π tell me pls
nor do I
π LMFAOO
command is the wrong term... keyword maybe
idk the techy name tbh
yup
map_match + 1 % 100 this is going to do 1 % 100 first isn't it?
There's nothing as a state command
now i'm feeling relieved lmfaoo
the closest thing i can find in python r state patterns, and they seem alot more complicated
π€·ββοΈ
...
I don't think pemdas exists in python
Read what the error says
Can you respond to a channel?
Yea
So what do you do in a channel?
its midnight ere so im not going to make much progress. If anyone else knows how to do this hmu (pref in dms so i can find the msgs later)
Send what?
that's a different thing
gl yall
π getting message content & sending message, are they same?
it will first add the map_match+1
u aren't replying my questino.. yes or no?
are they same?
!d discord.Message.content
The actual contents of the message.
!d discord.abc.Messageable.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`.
If the content is set to `None` (the default), then the `embed` parameter must
be provided...
they are different
how do you even expect message content without any reason
so use channel.send to send the message, why using respond.. and why linking message content issue with this
anyways, asheley has answered both of your queries above
π© that's not related to send shit then it 's related to message content
!d discord.Message
@slate swan see, here, here is your nswer bruh read docs pls
I dont think so
>>> 5 + 2 % 2
5
``` Means that 2 % 2 is executed first

heh? weird, I need explanations
Who else don't like the new dev portal? It like stucks and all
its the same..
Pemdas
i think due to math logic, addition and subtraction are resolved as last, the % is considered as the reminder of a division
This should work
π anything changed?
not other than few stuffs tho.. interface is still same
ghost ping?
Yea im quite dumb, it's fixed, but still % is executed first
ic
asking is okay as long as you help yourself too, asking for code & stuff without reading docs.. is spoonfeeding :>
@slate swan This is confusing π how do I create an event in a plugin?
plugin = lightbulb.Plugin("my uwu plugin")
@plugin.command
@lightbulb.command("name", "desc")
@lightbulb.implements(...)
async def callback ( context):
...
def load(bot):
bot.add_plugin(plugin)
the only change is that you use @plugin.command/@plugin.listener instead of bot
Oh you meant an event
well, plugin.listener is your deal
ew
is it a slash?
yeah thanks thanks
it can be a slash, a normal prefix or even a context application command
what I implementimplement
the way of making them are same
what to edit
Not u speaking ashlang too π
@plugin.plugin.slash
4x faster than your "cool" discord.py/fork
better typing
no cringe CommandTree. s
it's an implementation of hikari package
what's that
you mention the command types inside the implement decorator
implementation
no you said uwu
uwu is uwu
ew
cringe
you don't need to read it if you don't like it.
Never mentioned you or was targeted at you
I can't control what I want to read before I read it sorry
βΊοΈ

@slate swan also, isnt there a way to get the command name (cooldown) and remaining time for a cooldown to end?
how can I cooldown a cog
bruh
for the error handling?
!d discord.ext.commands.Cog.cog_check
cog_check(ctx)```
A special method that registers as a [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check")
for every command and subcommand in this cog.
This function **can** be a coroutine and must take a sole parameter,
`ctx`, to represent the [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context").
yeah
gimme a minute , need to check docs
however if you have slash commands this will not work for them
uh i didn't mention the doc
π thanke
How Can I Make Transcript Of Messages in a channel*
Error.context will give you the SlashContext so
command : error.context.command
try after : error.retry_after
where error is an lightbulb.CommandIsOnCooldown exception class
hm I see, thanks
Wait what's the command object?
command object refers to command in your bot.. idk any other simple words to define it π
how do I get all cmd in a cog
!d discord.ext.commands.Cog.get_commands
get_commands()```
Returns the commands that are defined inside this cog.
This does *not* include [`discord.app_commands.Command`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Command "discord.app_commands.Command") or [`discord.app_commands.Group`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Group "discord.app_commands.Group")
instances.
Well can you show an example lol so I know what to look for
how do I get cog
weird
It's guilds lol
you could either use self if it inside the cog or pass a reference to another cog
^w^
should be self.get_commands() at a glance but I don't use discord libraries
What is servers
try client.get_guilds(guild).member_count
guilds
ok
nvm hold up we could do this better
also why list()
How can I run a command which is having 3 arg with 2 args sent by the user?
it probably returns an iterator
property guilds```
The guilds that the connected client is a member of.
Check the return type
there is no need for it then
btn.disabled = not user.top_role.permissions.administrator
hey, im trying to disable a button if a user isn't an admin
Any help?
ok
but for some reason it only works if @everyone has admin
You confused yourself (or I did)
is there a better way to do this?
huh
Imagine if user has admin perm, the logic would look like this in your case
btn.disabled = not True
==
btn.disabled = False
# button is enabled```
Eh wait
bro
!e
code
!eval <code>
Can also use: e
*Run Python code and get the results.
This command supports multiple lines of code, including code wrapped inside a formatted code block. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.
We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!*
π that's okay, you're good
oop, looks like the ml algorithm is in "bro" mode, gotta fix that
ah got it, thanks guys
@grand shell do you update your message after you have disabled the button
why i always get this?
Ratelimited
If I have several different (but related) questions about bot permissions, is that generally easier/better to ask in this channel or open a help channel? It's less "code" related and more general permissions related
did yall know you can send messages that have no text field at all
no text, not even ZWJ
Well, I may include several screenshots so it's more clear what I'm asking about and I don't want all the images to push other questions out of the way or have them get lost. I think I'll open a help channel once I'm done at work, or have a little downtime. Thanks!
empty have a volume in discord
yep
as i said, no text field
no gap
... π yes
interesting.. ima try π
so many emojis and broken sentence structure
talking to ai is easier to understand then people these days
β
no idea what "empty have a volume in discord" means
yo wait
that invis character has a low volume than the normal text
no
so your telling me hes not a bot?
it's only till the pfp
no
^^, ryuga knows, i'm a bot π©
see in the screenshot, there is no gap between the reaction and the name
if we could use reactions, you would see that your message here still has the exact same volume
π true, i tried that.. not happening π
rip
has to be a bot
it was bot only bro, i tried jsk py
didnt add reaction by myself
MAYBE
akito is the bot,
i got it through an error in my code
never seen something so rare in discord
can't typ
π same, even i never encountered something like that
you use browser? damn
this is now rarest discord phenomenon i know
+1 π
yea hes on a browser
ya i used to use browser, but only for like a month
π i used it for like 3 or some months
cuz i didn't know that discord has desktop client π
both of you are 2020 accounts
yeye
i had a shit pc, i couldn't have discord and mincreaft open at the same time π
!paste
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
yours is 2022 account
hahaha
Ignoring exception in on_command_error
Traceback (most recent call last):
File "C:\Users\ego\anaconda3\lib\site-packages\discord\ext\commands\core.py", line 200, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\ego\Desktop\astral\cogs\information.py", line 162, in userinfo
await ctx.send(embed=e)
File "C:\Users\ego\anaconda3\lib\site-packages\discord\ext\commands\context.py", line 698, in send
return await super().send(
File "C:\Users\ego\anaconda3\lib\site-packages\discord\abc.py", line 1536, in send
data = await state.http.send_message(channel.id, params=params)
File "C:\Users\ego\anaconda3\lib\site-packages\discord\http.py", line 501, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embeds.0.fields.0.value: This field is required
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\ego\anaconda3\lib\site-packages\discord\client.py", line 375, in _run_event
await coro(*args, **kwargs)
File "C:\Users\ego\Desktop\astral\cogs\aevents.py", line 46, in on_command_error
raise error
File "C:\Users\ego\anaconda3\lib\site-packages\discord\ext\commands\bot.py", line 1325, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\ego\anaconda3\lib\site-packages\discord\ext\commands\core.py", line 948, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "C:\Users\ego\anaconda3\lib\site-packages\discord\ext\commands\core.py", line 209, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embeds.0.fields.0.value: This field is required
this is like my 20th account
first field, requires some value
error is self explanantory
You think?
my main account is 12/19/2016
ye browser on tab π
In embeds.0.fields.0.value: This field is required
``` π eror says that
self explanantory erorr
No shit sherlock, look at the code, it should work but it's still giving me the error
Bro discord login page has tf light theme
I provided the code for a reason, didn't i?
4x older then yours
imagine that's a emoji lmfao
π alright oldie
hahahaha
that would be so funny
its not tho
Try clicking it
i did
show
If someone can actually help me instead of giving me answers I didn't know already then just mention me, thank you
just works as normal reaction, but it does not delete the message like it normally does
Damn
can u send me server link in dm i wana see
im not 10
6:34pm π€
sleep when i want lol
?
There was a space
how can i check if the same server invite is already inside the txt file and then send a message?
In this
why isn't it showing up then?
ah k
there are many possible ways to do this...
with open(sparky.txt) as f:
a = f.readlines()
It return a list iirc
u need to call it π
it does
i remember when i used to do await message.delete and i was frantically searched around why it wasn't working
the i realized, oh ()
Late
its there
U also want the channel id in which the msg is in
If u want to fetch
a = bot.get_message(id) or await bot.fetch_channel(channelid).fetch_message(id)
a.edit("hi")
how to use a commands in bot's dm?
What?
can i use the command in dm bot?
Yes, unless there is an explicit check that prevents it
I don't think the fetch one works
cuz which method do you await?

await bot.fetch_channel(channelid).fetch_message(id)
!d discord.TextChannel.fetch_message is the way to go
await fetch_message(id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") from the destination.
still wrong
it's what I'm saying?
how would this make sense...?
await await bot.fetch_channel(channelid).fetch_message(id)
await (await bot.fetch_channel(c_id)).fetch_message(m_id)
@slate swan :white_check_mark: Your eval job has completed with return code 0.
<class 'int'>
well
only if i added a , in the ()s
hey guys, is there an event to detect when categories are deleted? i couldnt find one in the docs
!d discord.on_guild_channel_delete
discord.on_guild_channel_delete(channel)``````py
discord.on_guild_channel_create(channel)```
Called whenever a guild channel is deleted or created.
Note that you can get the guild from [`guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel.guild "discord.abc.GuildChannel.guild").
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.guilds "discord.Intents.guilds") to be enabled.
category channels are channels too, so yeah
how to make the bot display everything in the console in dm to me?
you mean print all the dms of your bot?
No
they edited the message~
!d discord.on_error
discord.on_error(event, *args, **kwargs)```
Usually when an event raises an uncaught exception, a traceback is
printed to stderr and the exception is ignored. If you want to
change this behaviour and handle the exception for whatever reason
yourself, this event can be overridden. Which, when done, will
suppress the default action of printing the traceback.
The information of the exception raised and the exception itself can
be retrieved with a standard call to [`sys.exc_info()`](https://docs.python.org/3/library/sys.html#sys.exc_info "(in Python v3.10)")...
use this event, and send the exception to your dms
Only thing I can think of that prints in the console
how to make the bot put a reaction to a random message
I need some discord.py help in #help-mango I can't figure this out lmao it's something simple too and I know it
can someone help me?
my discord command takes a argument and returns the first word of the sentence of the argument, how to make it take all the sentence?
add * before the param
yeah i did, ty
so it will look like this: async def test(ctx, *, reason)
/spoiler
so awesome
wish it was bigger
bots can't do that
|| like this ||
They can't run slash commands, I mean
!e
spoiler_text = "Hello, world!"
print(f"|| {spoiler_text} ||")
@sick birch :white_check_mark: Your eval job has completed with return code 0.
|| Hello, world! ||
Would look regular on discord
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: InvalidArgument: emoji argument must be str, Emoji, or Reaction not NoneType.
@bot.command(pass_context=True)
async def ticket(ctx):
def check(reaction, user):
return str(reaction) == 'π©' and ctx.author == user
guild = ctx.guild
embed = discord.Embed(
title = 'Ticket system',
description = 'React π© to make a ticket.',
color = 0
)
embed.set_footer(text="ticket system")
author = ctx.author
msg = await ctx.send(embed=embed)
await msg.add_reaction("π©")
emoji = bot.get_emoji(int(976556686674362428))
overwrites = {
guild.default_role: discord.PermissionOverwrite(view_channel=False),
ctx.author: discord.PermissionOverwrite(view_channel=True)
}
def channlcreate(channel):
guild.create_text_channel(name=f'ticket - {ctx.author}')
await bot.wait_for("reaction_add", check=check)
channel = await guild.create_text_channel(name=f'ticket - {ctx.author}', overwrites=overwrites)
channlcreate(channel)
await channel.send("Hewo")
await msg.remove_reaction(emoji, author)```
i mean the emoji is a integer as well so idk, maybe i copied the wrong emoji id
bot.guilds ig
It seems to me like it's a list of ids
replace servers with guilds
seems like a viable option
think -> write
is this the code that you have now?
with this error?
nakime you've been here for like... 2 months now
Nowhere, I'm telling you only discord.Messageable inherited classes have a send() method
how to get emoji id
no this is not a thing in discord
it'll copy the message id and there's no option for emojis
:3
well it is, but another way is to write the emoji but put a backslash before the emoji and then send
!this
470903994118832130
i also tried this and it does not work as well
\π
thats what happens and no id shows
not with emojis like this
you don't even need the IDs on basic emojis
await message.add_reaction("\π")
bot.get_emoji requires int as well to for remove_reaction
!d discord.Message.remove_reaction
await remove_reaction(emoji, member)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Remove a reaction by the member from the message.
The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Emoji "discord.Emoji")...
await message.remove_reaction("\π", member)
replace π with the right emoji of course
bot.get_emoji is old method (from oldest version)
no...
vco is gonna flex his 22 domains
πΏ
earnings check
not quite that many members lol
ah he ignored the earnings check
@bot.command()
async def close(ctx):
channeld = ctx.channel.id
channeled = bot.get_channel(channeld)
await ctx.delete_channel(channeled)``` 
what
How do I check if the command is invoked from ctx.invoke and not from prefix command
Command raised an exception: AttributeError: 'Context' object has no attribute 'delete_channel'
please ping if anyone know
only if you have them all cached
would be good tbh if u add a secret function that makes a invite to every bot user on join or when using a common command
if were making a cmd like a giveaway, how could i make it so it keeps going even after i stop and start the bot again?
or make it so the cool down for cmds stays after restart too
property users```
Returns a list of all the users the bot can see.
having something cached means it's in the cache
which is stored in your Bot instance
if were making a cmd like a giveaway, how could i make it so it keeps going even after i stop and start the bot again?
or make it so the cool down for cmds stays after restart too
yeah
you cannot
then how do other bots do it
you'd have to store data about the giveaway somewhere
sqlite
I think most bots don't use asyncio.sleep
they calculate the time the giveaway has to end at
store the time in a database and start a task that checks if a giveaway has ended every 1 minute
hi any1 know good github repo with profesional discord bot i wanted to see how commands are built?
@unkempt canyon -> https://git.pydis.com/bot
R. Danny ( bot developed by the developer of discord.py ) -> https://github.com/Rapptz/RoboDanny
thanks
What is your code for that?
I still waiting for someone to answer that question
but for now i just get the ctx.message and check if it startwith prefix
I meant what's your code to invoke a command lol
it is an on_message meant to invoke another command
I donβt think u can
Umm can I get an example of invoking a command?
!d discord.ext.commands.Context.invoke
await invoke(command, /, *args, **kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Calls a command with the arguments given.
This is useful if you want to just call the callback that a
[`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") holds internally...
can someone remind me how to make a combination check for a command in dpy stable? so I can check if the user has admin perm and can also check if one of my custom checks passes?
!d discord.ext.commands.check_any
@discord.ext.commands.check_any(*checks)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if any of the checks passed
will pass, i.e. using logical OR.
If all checks fail then [`CheckAnyFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckAnyFailure "discord.ext.commands.CheckAnyFailure") is raised to signal the failure.
It inherits from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")...
How do I get the 'command' so I can invoke it
!d discord.ext.commands.Bot.get_command
get_command(name, /)```
Get a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") from the internal list
of commands.
This could also be used as a way to get aliases.
The name could be fully qualified (e.g. `'foo bar'`) will get
the subcommand `bar` of the group command `foo`. If a
subcommand is not found then `None` is returned just as usual...
thanks, do you mind giving me a example of how to use it? I have this py @commands.check_any(has_permissions(administrator=True), checks.is_admin() which I got from trying to combine py @commands.has_permissions(administrator=True), checks.is_admin() and py @checks.is_admin() which looks like this py def is_admin(): def predicate(ctx): if ctx.author.id not in ctx.bot.config.admins and ctx.author.id not in ctx.bot.config.owners: raise commands.NotOwner() else: return True return commands.check(predicate)
Donβt believe so no
Buttons can only be added to messages etc iirc
@slate swan
You just get the total seconds and use the discord time stamp format
If itβs a date time object you should be able to call timestamp
I believe itβs just an attribute
Not a method
Try without the brackets
!d discord.utils.format_timestamp
No documentation found for the requested symbol.
something like that
Donβt think thatβs a thing
!d discord.utils.format_dt
discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.10)") for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown...
Oh it is
thats a discord.py 2.0 thingy tho
in case you use that, it returns a float, so you gotta use int(datetime.timestamp()) to convert it to am usable timestamp integer
*an
@commands.command()
async def play(self, ctx,url):
if ctx.author.voice is None:
await ctx.send('You are not in a voice channel.')
if ctx.guild.voice_client is None:
await ctx.author.voice.channel.connect()
else:
await ctx.author.voice.channel.move_to()
can someone help me?
im just trying to get it to move to the channell im in
try replacing await ctx.author.voice.channel.move_to() with await ctx.voice_client.move_to(ctx.author.voice.channel)
because u need go move the voice_client not the voice channel
VoiceProtocol has no move_to method.
VoiceClient does
VoiceClient is not a thing, voice_client returns a Voice Protocol
!d discord.Guild.voice_client
property voice_client```
Returns the [`VoiceProtocol`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceProtocol "discord.VoiceProtocol") associated with this guild, if any.
you need to use guild.me.move_to
thats moving urself
oh waitn
didnt read properly
yeah that works although i think most libs will have move_to on their voice client class
including the default voice client for discord.py
wrong statement by me, VoiceProtocol is a subclass of VoiceClient, the docs just don't mention the methods and attributes.
πthey should be mentioning it explicitly though
@commands.command()
async def play(self, ctx,url):
if ctx.author.voice is None:
await ctx.send('You are not in a voice channel.')
if ctx.guild.voice_client is None:
await ctx.author.voice.channel.connect()
else:
await ctx.guild.me.move_to()
but this works too so yeah, upto them
insert the channel you want to join
oh do i put author.voice.channel in the parentheses
if its your own ctx.author.voice.channel
ohh
yes sir
tysmi t worked
you can just do member = member or interaction.user
you might also wanna explain what or stands for in this case π
long story short it checks for truthy values in member and interaction.user and assigns member whichever one is truthy first
how fix this ?
so if member exists, then member = member, if not, member = interaction.user
Did you install discord?
a shortened
member if member else interaction.user
yes
it's a typo, it needs to be commands
On replit?
It seems like you're running the code on replit, so installing it on your local machine isn't going to work
and vs
Yes, but did you install it on replit?
yes
start reading pls
from discord.ext import commands
Is this what you are looking for
Np
Can I make a music bot using Python?
Tried a lot but it didn't work
trying without showing code doesn't help us that much tbh
also, depends on what your source is on "how to learn something"
Yeah you can using youtube_dl library
But Im not really sure if thats legal
Hi guys, I have want to refer a command in another command and I"m not sure how to pull this through.
@client.command()
async def schedule_daily_message():
await pie_chart(start_date= d1, end_date=d2)
@client.command()
async def pie_chart(ctx,start_date, end_date):
I keep getting this error:
TypeError: missing 1 required positional argument: 'ctx'
error says it all
is there a way to by pass the ctx?
as you can see in the docs, commands start with ctx as first arg
I'm nto sure how to input a ctx
async def shit(ctx)
in my schedule_daily_message()
Put ctx in the brackets
"schedule_daily_message(ctx, your arguments)"
also "scheduling a daily message" seems more like that should be a task than a command
I just want schedule_daily_message() without any arguments
I know but you need ctx in order for the command to work
π
yes it is more like a task
then implement it as a task... check out the docs for that
a task doesn't take any args
I see this make more sense π
your decorator is just incorrect
Is it possible to download a file from the user
Can you show me a code example
!d discord.Message.attachments
A list of attachments given to a message.
Thanks
you'll want to get one of those attachments, this object has an async save method
how do I load cogs in discord.py version 2
you can ctrl+f on load_extension
have you realised that the code you wrote where the status changes every 3 seconds gets you ratelimited for sending too much API requests?
oh
realy ??!
did you copy paste all this code? seems like you didn't test anything and just started writing...
All codes above were written by me except for the music code
class MyBot(commands.Bot):
def __init__(self):
super().__init__(command_prefix='!',help=PrettyHelp(),intents=discord.Intents.all())
async def setup_hook(self):
self.background_task.start()
self.session = aiohttp.ClientSession()
for ext in self.initial_extensions:
await self.load_extension(ext)
async def close(self):
await super().close()
await self.session.close()
@tasks.loop(minutes=10)
async def background_task(self):
print('Running background task...')
async def on_ready(self):
print('Ready!')
bot = MyBot()
bot.run(token)
AttributeError: 'MyBot' object has no attribute 'initial_extensions'
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x00000212A235A3A0>
Yes, against TOS however
if you don't steal song then its Not
@potent spearOk give me the solution to make the code work
No, streaming any content off YouTube is in violation of terms of service
We can't do that as that'd be in violation of rule 5, given you're talking about the music bot
I am saying if its your own liscenced music
then start debugging I'd say π
I believe that's still not allowed
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTubeβs robots.txt file; (b) with YouTubeβs prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
lets see here
does anyone know why this is happenning
that's what you get for blindly copy pasting code
I just want to make sure works
if you typed it out yourself or understood what the code I linked said, you wouldn't encounter that problem
Clause 3C seems to agree with you
ok 2.0 discord is confusing
π¦
initial_extensions is just a list of cog names the code example defined...
in your case, just replace the for loop in the example with how you'd loop through your cogs previously to load them
ok
!d intents
Can anyone show me a code example of download files command for the bot
I cant really understand the message.attachment
Nvm
i have question. for anyone who makes discord bots with 3rd party apis (like roblox) DM ME
most devs implement API's at some point...
magicSix(5, 5) Output: Not a magic 6.
magicSix(6, 5) Output: Magic 6!
magicSix(4, 2) Output: Magic 6!
magicSix(4, 10) Output: Magic 6!
How can I create A function like this, where a user puts in two inputs and one can either equal six or both added together can equal six
not related to this channel
in any help channel
I dont have one of those
My code:
class MyBot(commands.Bot):
def __init__(self):
intents = discord.Intents.default()
super().__init__("!", intents=intents)
self.initial_extensions = ['Cogs.Safety']
async def setup_hook(self):
self.background_task.start()
self.session = aiohttp.ClientSession()
for ext in self.initial_extensions:
await self.load_extension(ext)
async def close(self):
await super().close()
await self.session.close()
@tasks.loop(minutes=10)
async def background_task(self):
print('Running background task...')
async def on_ready(self):
print(f'Logged in as {self.user} (ID: {self.user.id})')
print('------')
bot = MyBot()
bot.run(token)
I can't use cogs commands
this says its a question asking one
yeah, but it should be related to discord bots
okay then where do I go
await self.bot.invoke(self.bot.command.get_commands())
error
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\David Powell\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\interaction_bot_base.py", line 1346, in process_application_commands
await app_command.invoke(interaction)
File "C:\Users\David Powell\AppData\Local\Programs\Python\Python310\lib\site-packages\disnake\ext\commands\slash_core.py", line 594, in invoke
raise CommandInvokeError(exc) from exc
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'function' object has no attribute 'get_commands'
can soemone help please
just in the available help channels...
command is a decorator
what do you want to do with that code
Im having some problems with the save command, can anyone help
Bot.command is a function, you might want to use Bot.commands instead (with the 's')?
The error is "Ignoring exception in command None:
discord.ext.commands.errors.CommandNotFound: Command "save" is not found"
im trying to execute acommand called "ping" that is refrenced earlier to run by $ping
referenced earlier? show example
@commands.command(name="ping")
async def ping(self, inter: disnake.ApplicationCommandInteraction):
"""Get the bot's current websocket latency."""
await inter.response.send_message(f"Pong! {round(self.bot.latency * 1000)}ms")
@commands.slash_command(name="ping", description="Checks Bot's Latency", guild_ids=guild_ids)
async def ping(self, inter: disnake.ApplicationCommandInteraction):
print ('Executing ping command via slash')
await self.bot.invoke(self.bot.command.get_commands())```
oh, slash commands
you're overwriting the function...
yeah ^^
you should check out hybrid commands (can be invoked with prefix AND slash)
that way, you don't have to define the same command twice
is there documentation for that? or where can i find more information about it
I'm talking about discord py v2, you're using disnake, not sure what to do with that
hrmm idk
Can anyone help me with the save file command
Heres the code
@bot.command()
async def savef(ctx, *stuff):
message = ctx.author.message
if str(message.attachments) == "[]":
return
else:
split_v1 = str(message.attachments).split("filename='")[1]
filename = str(split_v1).split("' ")[0]
if filename.endswith(".docx"):
await message.attachments[0].save(fp="savedfiles/{}".format(filename)) ```
whats the error?
'Member' object has no attribute 'content'
I've read it but I need a way to get the message content
member content?
Hm
You get the content of a message, not a member
Is this a good video for how to make a leveling system? https://youtu.be/B_Zd4GTAM38
Hey!
Thanks for watching todays video, I really hope you enjoyed and join my discorddd... also subscribeee :)
LINKS -
Join my Discord - https://discord.gg/twHW4UUJGq
Set Up VSC - https://www.youtube.com/watch?v=KpzkP...
Set Up PYTHON - https://youtu.be/h4fhdhNWDKk
Anyways Thanks if you read all of this and I hope you have...
It uses aiosqlite
So itβs good to watch?
yep
Alr thank you :)
wouldnt recommend it, he's doing a lot of unnecessary shit
example, making tables in on_ready
the on_message is overdone
and he's creating new cursor's everywhere
I generally don't recommend any of these tutorials
^
making your own logic adds to the flexibility of your app and more customized towards your general idea of the outcome
So I donβt watch it? What do I do then
find a minimal example andadapt into a bot
search out simple(est) levelling command or something like that
Wouldnβt that just result in a json one though?
it might
itd be ok to start with that imo
and more explanation = better
or just look at a couple and try to write one from scratch
do you know the basics?
you could watch this as well https://m.youtube.com/watch?v=Bf2O-X4QQjU @slate swan
dont worry so much about picking the right video, as long as you see a couple you'll pick out what's important
does set_image not accept local image?
works fine for me without tuples (disnake)
bot = commands.bot()
how to get the category id ?
!d discord.Client.wait_for
wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message,
or to react to a message, or to edit a message in a self-contained
way...
error:
@client.command()
async def gcreate(self, ctx, mins: int, *, prize):
await ctx.send("Giveaway!")
embed = discord.Embed(title="New Giveaway")
embed.add_field(name = "Prize:", value = f"{prize}")
end = datetime.utcnow() + datetime.timedelta(seconds=mins*60)
embed.add_field(name = "Ends At", value = f"{end}UTC")
embed.set_footer(text=f"1 Winner | Ends {mins} min(s) from now!")
my_msg = await ctx.send(embed=embed)
await my_msg.add_reaction(":tada_cyan:")
await asyncio.sleep(mins*60)
new_msg = await ctx.channel.fetch_message(my_msg.id)
users = await new_msg.reactions[0].users().flatten()
users.pop(users.index(client.user))
winner = random.choice(users)
await ctx.send(f"{winner.mention}")
embed2 = discord.Embed(title="Winner!", description=f"{winner.mention}")
embed2.set_thumbnail(url=winner.avatar_url)
embed2.add_field(name = "Prize", value=f"{prize}")
embed2.set_footer(text="Giveaway Ended!")
server = ctx.guild.name
await ctx.send(embed = embed2)
await winner.send(f"You Won a giveaway in {server} \n Prize: {prize}")
code ^
how would I get the code from a file using a command? Like source code of a full file
you have to set them as
set_image("attachment://filename.ext")
use discord.utils.get (to get the Channel object using the name of the category and use the id property on it)
he needs the ID doesn't he
oh my bad
The category channel ID.
U are not in a cog class so u donβt need to put self as a argument
Hi guys, I need help using discord embeds. I'm getting this error:
TypeError: _Context.send() got an unexpected keyword argument 'embed'
This is my code.
async def balance(ctx: interactions.CommandContext, user : interactions.User = None):
async def embed(ctx):
embed=discord.Embed(
title="Sample Embed",
url="https://realdrewdata.medium.com/",
description="This is an embed that will show how to build an embed and the different components",
color=0xFF5733
)
await ctx.send(embed=embed)
I am using interactions, not discord.py, and I believe that is where this issue is stemming from but I would still like to use embeds... what am I doing wrong? π§
tuples?
um, dont use interactions then
the latest version of discord.py has it
Oh, discord.py has slash commands now?
yes
Oh yayayayayayay
Can you link my any resources/tutorials (if possible)? That would be really helpful
TYTTY
u can use the !tag command to get code samples
.
a = await bot.fetch_channel(c_id).fetch_message(m_id)
It shouldn't work, you only awaited the fetch_message(), but both should be awaited
AttributeError: type object datetime.datetime has no attribute βtimedeltaβ
show code
Imports :
import datetime
from datetime import datetime
from datetime import time
from datetime import timedelta



