#discord-bots
1 messages Β· Page 173 of 1
Where reference is stored in interaction? (in context it is context.message.reference)
interaction?
or just fetch the message and use reference from there
uhh, isn't for message commands?
nope
uses an Interaction message object
Represents the original interaction response message.
ok, thanks
This allows you to edit or delete the message associated with the interaction response. To retrieve this object see Interaction.original_response().
hmm simple ones or challenging ones
both
Loads, how good are you at making bots?
is it for practice or do u plan to make it for a public bot
need to know based on rate limit
i dont really care about how hard
u could make a platformer haven't seen that before
An engine to run a Westmarch D&D server.

i dont understand this
Β―_(γ)_/Β―
making games is fun made a decent one recently its in my pfp made the website too but idk if it suits your taste 
checking
Reminds me of what I'm making.
ic
cool
is that open src
not yet
rewriting it for open source
prolly in few months gonna add a bunch of new features too
what image manipulation lib did u use
pillow 
closed source rn only with a few friends sorry
then add me to the friends 
u can join the server if you want to rn...
sure
i just met u today lol
How do I change the "Reason:" field label and the reason value to appear on the same line?
Still not showing it on the same line
embed.add_field(name=f"**Reason:\u200b**", value=f"{reason}", inline=True)```
embed.add_field(name=f"\u200b", value=f"**Reason:** {reason}", inline=True)
you can also do it all in the description if you want
man this syntax highlgihting is so bad
I still want some space between "title" and "reason"
use on mobile that way u wont have expectations in first place
ah then use a field or add more newlines
no expectations == no dissapointment
true
This one adds to much space in my opinion
then do it in the name leave the value empty
You mean like this?
embed.add_field(name=f"**Reason:** {reason}", value=f"", inline=True)```
what's the issue you're facing?
nice
My bot not working
Ok.
can i update my bot config.json without restarting the script?
average nitro flex. gift me too
read the json using json.load
huuh
!d json.load
json.load(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)```
Deserialize *fp* (a `.read()`-supporting [text file](https://docs.python.org/3/glossary.html#term-text-file) or [binary file](https://docs.python.org/3/glossary.html#term-binary-file) containing a JSON document) to a Python object using this [conversion table](https://docs.python.org/3/library/json.html#json-to-py-table).
*object\_hook* is an optional function that will be called with the result of any object literal decoded (a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "dict")). The return value of *object\_hook* will be used instead of the [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "dict"). This feature can be used to implement custom decoders (e.g. [JSON-RPC](https://www.jsonrpc.org) class hinting).
*object\_pairs\_hook* is an optional function that will be called with the result of any object literal decoded with an ordered list of pairs. The return value of *object\_pairs\_hook* will be used instead of the [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "dict"). This feature can be used to implement custom decoders. If *object\_hook* is also defined, the *object\_pairs\_hook* takes priority.
no i meant is there a way i can just make a command to do so rather than calling it everytime
I'll tell you the same thing I tell all the others, making a discord bot is not the best first project.
figured it
its not my first project its just im making such a vast project the first time 
i wanna do user customization and preferences
then you write a function that does what you need and call it as you need it.
did it, ty 
one more doubt is there a way i can run multiple bots from same script?
NPC? π
Non Player Character.
yes how do you make NPCs in discord bots lmaoooooo
Are you asking how or just trying to make jokes?
both
Good luck figuring it out then.
i fr am
Nice, I'm working on more or less the same thing.
ππso shall i use loops?
ouch, that new to python huh?
yes
Now this is not want you want to hear, but you might be better off making a few small things to learn with rather than jumping in the deep end right off the bat before you know how to swim.
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
thanks
okok
Know how to play Blackjack?
a bit, why?
If you want an idea to practice with, try writing a program that deals cards from a deck.
Not even the entire game of Blackjack, just the card dealer.
ah okay
my bot literally started ignoring my commands for sum reason, anybody knows why? (intents are on)
Did you just start using on_message?
yes
i love you so much
Any time
!d asyncio.create_task
asyncio.create_task(coro, *, name=None, context=None)```
Wrap the *coro* [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine) into a [`Task`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task "asyncio.Task") and schedule its execution. Return the Task object.
If *name* is not `None`, it is set as the name of the task using [`Task.set_name()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.Task.set_name "asyncio.Task.set_name").
An optional keyword-only *context* argument allows specifying a custom [`contextvars.Context`](https://docs.python.org/3/library/contextvars.html#contextvars.Context "contextvars.Context") for the *coro* to run in. The current context copy is created when no *context* is provided.
The task is executed in the loop returned by [`get_running_loop()`](https://docs.python.org/3/library/asyncio-eventloop.html#asyncio.get_running_loop "asyncio.get_running_loop"), [`RuntimeError`](https://docs.python.org/3/library/exceptions.html#RuntimeError "RuntimeError") is raised if there is no running loop in current thread.
Note
[`asyncio.TaskGroup.create_task()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.TaskGroup.create_task "asyncio.TaskGroup.create_task") is a newer alternative that allows for convenient waiting for a group of related tasks.
Hi
hello
So the question I'm stuck on, how would this get the names/id's without me defining them in the top like i did before? i'm assuming the approach you're taking is calling the data using for loops right?
You can populate dictionaries on the fly as long as you have defined them as dictionaries first.
a_dict={}
a_dict["User_One"]={"Name":"J. R. Bob Dobbs"}
print (a_dict)
So in this example there is a top level entry called User_One and the name : name pair is a child of it.
getting this amazing error when trying to send the message, is this because its taking too long to respond?
TraceBack:
File "C:\Users\Lenovo User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 862, in _do_call
return await self._callback(interaction, **params) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\Users\Lenovo User\Desktop\LifeAsPy\Hypixel Api\BetterCocoa\main.py", line 40, in session
await interaction.response.send_message(f'Session of `{username}`', file=discord.File(f"./database/{username}.png"))
File "C:\Users\Lenovo User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\interactions.py", line 769, in send_message
await adapter.create_interaction_response(
File "C:\Users\Lenovo User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\webhook\async_.py", line 218, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
The above exception was the direct cause of the following exception:
TraceBack:
File "C:\Users\Lenovo User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\tree.py", line 1242, in _call
await command._invoke_with_namespace(interaction, namespace)
File "C:\Users\Lenovo User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 887, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Lenovo User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 880, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'session' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction```
ohhh so how do i get members?
AttributeError: 'dict' object has no attribute 'members'
self.TheData = members?
or
TheData.members = {}
?
["member"]
So using the list you would get from Guild.members you could fun a for loop and pull them out one by one.
for each in Guild.members:
a_dict[each.id]={"name":each.name}
the website can't be found.
so i just put a for loop in the command at the top? i don't need to define the string i'm trying to obtain like I did?
Nope, if you run that for loop (after a little integration) it will populate a dict with the ID and usernames of everyone on the server.
All depends on how you want it to work.
Yes
First project?
Just a heads up, this is like trying to run before you can crawl.
Do it, I wonder who 381870129706958858 is. let us know.
What the actual hell
I know, I'm just wondering if it's the same as a 555phoone number.
bot = Client() π
Are you making own wrapper or smth
Calm down, everyone starts somewhere.
They're doing the mobile status hack
what is it?
What the what
FYI that is against discords terms of service
You are accessing the API in a way that is not supported
Or documented, for that matter
its the one where it shows mobile status on bots by sending an identify payload as mobile to discord
ah ic
nothing important, I remember something after I hit enter.
It's open source isn't it
TypeError: 'Member' object does not support item assignment...?
let's see the code.
for member in self.TheData.members:
member[member.id]={"name":member.name} ```
member[member.id] here member is an instance of discord.Member not dict
You need to define member as a dict
so you can't do that
the_dict={}
for member in self.TheData.members:
the_dict[member.id]={"name":member.name}
ohhhh
How's that working for ya?
would these go in the init or in the @commands decorator?
__init__ runs on startup(or just when that file/class is loaded)
@commands will run each time you call the command.
so if it's a dictionary, it should grab the data when the command is ran incase things change. got it
That and ctx will make it easy to get the guild/server
What is wrong with this piece of code?? ```py
inactive_channels = list(channel for channel in inactive_server.text_channels for inactive_server in bot.guilds)
`NameError: name 'inactive_server' is not defined`
What is inactive_server supposed to be?
an iterator, for inactive_server in bot.guilds
inactive_server is (supposed to be) the discord.Guild object
ctx doesn't mean i have to add the guild ID i'm trying to obtain the info from, it auto grabs it. right?
It's also not defined so the computer has no idea what it is.
it should be able to be read in the listcomp iterator
(it does for inactive_server in bot.guilds)
yes, ctx is short for context. it gives you the context the command was used under.
But it's not, post the full code and I'll take a look.
Sure, hold on
def inactive():
q = list(w for w in inactive_server.text_channels for inactive_server in bot.guilds)
w = list(w.last_message for w in q)
e = w.map(lambda q: q.edited_at or q.created_at)
r = sorted(e)
return r, min(e), max(e)
inactive()
(without qeval at the start)
sure wait
Alright hold on
check DMs
So inactive_server is a thing built into discord.py?
No, it should be a list of discord.TextChannel for each discord.Guild of bot.guilds defined as inactive_server
so let's say it should be something like ```py
def get_all_persons() -> dict[tuple[Person]]:
...
class Person:
name = ...
...
my_list = [person.name for person in persons.keys() for persons in get_all_persons()]
here it would say that persons is not defined
As seen in here https://i.imgur.com/G1A9Kpb.png
Ya, because it's not being defined anywhere in this code.
I thought it should? https://i.imgur.com/mqd03JO.png
What documentation are you reading from? can you link it?
role = discord.utils.get(message.guild.roles, name="Premium")
await message.author.add_roles(role)``` 'int' object is not iterable
is it possible to have multiple on_message listeners running @ the same time?
One in each cog.
I'm not reading docs, I'm just trying to iterate through all my guilds and iterate through all the channels (a listcomp).
https://www.w3schools.com/python/python_lists_comprehension.asp
wb if there's
@bot.event
async def on_message(message: discord.Message) -> None:
if message.author == bot.user or message.author.bot:
return
await bot.process_commands(message)
```this thing in the main file
ok, you have lost me. You are making a discord.py bot, right?
Correct.
How much of the code did you write yourself and how much did you copy and paste?
I wrote it to iterate through all the channels of each guild the bot is in.
Nothing was copied nor was pasted.
Hey @slate swan!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
ok, then where are you defining inactive_server at?
Hey @slate swan!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
Here: https://i.imgur.com/kZDUx30.png ```py
def inactive():
q = list(w for w in inactive_server.text_channels for inactive_server in bot.guilds)
w = list(w.last_message for w in q)
e = w.map(lambda q: q.edited_at or q.created_at)
r = sorted(e)
return r, min(e), max(e)
inactive()
Hey @slate swan!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
Hey @slate swan!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
you are calling it before you are defining it.
read the bot, use paste bin.
Aight
@crimson mauve Alright, should it be written this way? ```py
def inactive() -> list:
channels = list(channel for server in bot.guilds for channel in server.text_channels)
...
...
it should be defined in this way now
Not going to lie having const owners = ["1020440076024557628"]; is a red flag, makes me think you are putting in backdoors.
Run it and you tell me.
Alright.
write it out the long way if you need to.
π
how'd u get a colorful border for screen scraping? o.o
it's an effect they put it though on image editing software like Gimp before they post it.
ohhhhh ty. also, TypeError: sequence item 0: expected str instance, int found
mem_dict={}
for member in self.TheData.members:
mem_dict[member.id]={"name":member.name} ```
so what do i list it as? I tried `Embed.add_field(name="Member Names", value='\n'.join(mem_list))`
Want to just take this to DM?
sure! idc
is it possible to give out roles with a command in a specific server?
Yes
!d discord.Member.add_roles
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s.
You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
How can I make a command message "dismiss" right away before it"times out" when there is not supposed to be a message sent back so no interaction.response.send_message to make it go away
am I explaining that right
You want to respond to an interaction without sending a message?
Just so it doesn't time out?
yea, don't want a message to appear but I want the pop up to not time out, just disappear after the command is used.
the reason is because the command should be accepted in channel or via DM, but always DM the results to the user who used it
!d discord.InteractionResponse.defer
await defer(*, ephemeral=False, thinking=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Defers the interaction response.
This is typically used when the interaction is acknowledged and a secondary action will be done later.
This is only supported with the following interaction types...
ah, cool!
how do i specify the guild
A Member is already tied to a guild
Do you want to be able to give roles to users in other servers?
because i got a redeem command that gives ya a role when you redeem a key in dms, thats why i cant do juist guild
Ah. You can use
guild = bot.get_guild(123)
To get the guild via it's ID
okok, lemme try
'int' object is not iterable
Can you show me your code?
And the full traceback, since this error is somewhere else
I think you can also type hint a command parameter with discord.Guild and it'll attempt to convert an input into a Guild object. So inputting an ID or name would work. But your bot has to be able to 'see' the guild.
@bot.command()
async def redeem(ctx: commands.Context, guild: discord.Guild, code: str) -> None:
...
im using client.even
on_message/ the bot dms
You aren't using the commands extension?
I would recommend that you do
Discord.py will handle the hard work of parsing for you
@client.event
async def on_message(message):
guild = client.get_guild(1060335114703339520)
channellol = client.get_channel(1061293482188210217)
channellol1 = client.get_channel(1061293482188210217)
with open('key_codes_premium', 'r') as key_codes_premium:
unredeemed = key_codes_premium.read()
if (message.content == f'{unredeemed}'):
dmchannel = await message.author.create_dm()
embed = discord.Embed(title=f"{key_emoji} PREMIUM KEY (1 MONTH)",
description=f'``KEY REDEEMED SUCCESSFULLY.``', color=0x2F3136)
await dmchannel.send(embed=embed)
chars = string.ascii_letters + string.digits
keysb = ('MH' + '-' + 'PREMIUM' + '-' + ''.join(random.choice(chars) for i in range(6)) + '-' + ''.join(
random.choice(chars) for i in range(6)) + '-' + ''.join(
random.choice(chars) for i in range(6)) + '-' + ''.join(random.choice(chars) for i in range(6)))
with open('key_codes_premium', 'w') as premiumware:
premiumware.write(keysb)
with open('premium', 'w') as f:
f.write(f"{str(message.author.id)}\n")
f.close()
await asyncio.sleep(2.5)
embed2 = discord.Embed(title=f"{key_emoji}A PREMIUM KEY WAS REDEEMED!",
description=f'``REDEEMED BY {str(message.author)}.``',
color=0x2F3136)
await channellol.send(embed=embed2)
role = discord.utils.get(message.guild.roles, name="Premium")
await message.author.add_roles(role)
await client.process_commands(message)```
AttributeError: 'NoneType' object has no attribute 'roles'
you wanna do guild.roles not message.guild.roles
message.guild is None when the message is received in a dm
cuz it's not in a server
so you're basically doing None.roles
await message.author.add_roles(role) you won't be able to do that either
so what should i replace it with
get a member object from the guild you have with the message's author's id
member = guild.get_member(message.author.id) if you have your intents
basically binds the user to the guild if he's in the guild
the whole time I'm assuming you're sending the bot a message via dm
yeah
wait why would i add that
because if you dm the bot, message.author is a user
the user is not connected to the guild
if someone's not in a guild, you can't add roles to that person
you can only add roles to member
the difference between a User and a Member is that a User is just a profile
a Member is a profile in a server
member = guild.get_member(message.author.id)
role = discord.utils.get(guild.roles, name="Premium")
await member.add_roles(role)```does that work
a User could be in many servers with the bot, the bot wouldn't know which server you're talking about
how can you do a bot that if you send a message to x channel it will delete the message and send the message that was deleted to channel y in the same server? with on_message yes but what after it?
so you attach the User to a server
that seems ok
AttributeError: 'NoneType' object has no attribute 'id'
you're lucky I'm a compiler
the bot didn't find a role in that server that's named Premium
Ashley's writing a book
Ashley stopped writing the book
π
she's at it again
?
You can compare message.channel to channel X and do something if they're equivalent
What are some of the reasons as to why I could be getting Unknown interaction for my View?
- The bot is online.
- The bot has the correct permissions.
- The command was working as of yesterday.
- I did not modify the code
The error happens exactly on this line of code:
await interaction.response.edit_message(view=self)
@discord.ui.button(label="Confirm", style=discord.ButtonStyle.green, emoji=":white_check_mark:", custom_id="utility_confirm")
async def callback(self, interaction: discord.Interaction, button):
try:
## Lots of stuff happening here but no modification to interaction
except Exception as err:
btn.label = "Err!"
await interaction.response.edit_message(content="blabla", view=self)
else:
await interaction.response.edit_message(view=self) # Error happening here.. Unknown interaction
Ignore the button parameter there.
you're not responding fast enough. What are you doing inside your try block?
I'm setting data inside MongoDB, and then creating a voice channel based on that data.
Overall, the timeout is set to 120 seconds, shouldn't it be waiting for an input ?
that's probably taking more than 3 seconds, consider deferring the interaction first and then sending a followup
from discord.ext import tasks
@tasks.loop(hours = 69)
async def find_channels() -> None:
try:
bot.x_channel = bot.get_channel(x_channel_id) or await bot.fetch_channel(channel_id)
except ...
# same with bot.y_channel
@bot.listen("on_message")
async def on_message(message: discord.Message) -> None:
if message.channel == bot.x_channel:
await message.delete()
await bot.y_channel.send(...)
"use it as an example"
why're you using tasks here?
yes okey, thank you
To not get the channels again and again π
you're taking too long to respond to the application's command interaction
You don't seem to be in a class (judging from the indentation), apparently you're still using self
you're still using self
wot
if you want to use self then pass the bot instance to the function while calling it
.
await set_emoji_quiz(self, 234567654321, 1256787654321, 1678987654321)
assuming you're within a cog
the ids smh
whatever you pass into them
bro
guild_id
message_id
channel_id
whatever_and_whatnot
It's your code? You should know what args you need
^
AttributeError: 'Bot' object has no attribute 'x'
what does this error mean
or how do i fix it
It means exactly what it says. What are you trying to do?
trying to do this
Thanks, this solved my problem.
"learn to use classes and objects"
Just learn OOP overall
ok okimii
why does my client.event block my commands?
i have on_message and then its the only thing that works but not the commands anymore?
@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready")
The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine "(in Python v3.11)").
Example...
!d discord.ext.commands.Bot.process_commands
await process_commands(message, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
This function processes the commands that have been registered to the bot and other groups. Without this coroutine, none of the commands will be triggered.
By default, this coroutine is called inside the [`on_message()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_message "discord.on_message") event. If you choose to override the [`on_message()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_message "discord.on_message") event, then you should invoke this coroutine as well.
This is built using other low level tools, and is equivalent to a call to [`get_context()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") followed by a call to [`invoke()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke").
This also checks if the messageβs author is a bot and doesnβt call [`get_context()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.get_context "discord.ext.commands.Bot.get_context") or [`invoke()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.invoke "discord.ext.commands.Bot.invoke") if so.
Changed in version 2.0: `message` parameter is now positional-only.
umm maybe a dumb question but what does bot and client have in difference, or is client.listen just the same thing?
don't kinda get it
they're just variable names
you should probably name it bot when it's a commands.Bot instance, and client when it's a discord.Client instance
how did you play an audio file in vc?
@client.command()
async def say(ctx, *, text=""):
if text == "":
await ctx.send("You must provide some text for me to say out loud!")
return
voice_client = get(ctx.bot.voice_clients, guild=ctx.guild)
if voice_client is None:
await ctx.send("I'm not in a voice channel...")
return
if ctx.author.voice:
tts_engine.save_to_file(text, 'src/assets/voice.mp3')
tts_engine.runAndWait()
os.system("rm src/assets/voice.mp3")
else:
await ctx.send("please join a voice channel then bring me in there!")```
thats what ive got, i just have to figure out how to make the file play qwq
im on linux, if that matters
depends on ur variable
!d discord.VoiceClient.play
play(source, *, after=None)```
Plays an [`AudioSource`](https://discordpy.readthedocs.io/en/latest/api.html#discord.AudioSource "discord.AudioSource").
The finalizer, `after` is called after the source has been exhausted or an error occurred.
If an error happens while the audio player is running, the exception is caught and the audio player is then stopped. If no after callback is passed, any caught exception will be logged using the library logger.
Changed in version 2.0: Instead of writing to `sys.stderr`, the libraryβs logger is used.
and then take a look at the various audio sources
how much latency in a bot is "bad"?
The amount varies so, the general rule is, if you can notice when it's delayed consistently you'll probably want to fix that
Otherwise if you cannot notice it, keep it as is
Average sudo enjoyers: π
Average doas enjoyers: π
what
You need to construct first
Otherwise you'd need to pass an instance
So VoiceClient()
ah
Actually ignore that part
You usually don't wanna create a VoiceClient manually
You get a VoiceClient object by using .connect on a VoiceChannel
!d discord.VoiceChannel.connect
await connect(*, timeout=60.0, reconnect=True, cls=<class 'discord.voice_client.VoiceClient'>, self_deaf=False, self_mute=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Connects to voice and creates a [`VoiceClient`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceClient "discord.VoiceClient") to establish your connection to the voice server.
This requires [`voice_states`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.voice_states "discord.Intents.voice_states").
You can get this from like, member.channel
my join command is somewhere else 
voice_client = get(ctx.bot.voice_clients, guild=ctx.guild)
if voice_client is None:
await ctx.send("I'm not in a voice channel...")
return```
Well, since your join command is separated I guess you could do a dictionary
Let's say you start off with an empty dictionary called voice_channels like this {}
When your join command is called, make a new key-value pair like {user_id: await channel.connect()}
Then in you're other command where you play the file, get the VoiceClient via voice_channels[user_id]
God damn
I'll just morph the 2 commands
I just dont know how to check if the bot is alr in vc
so It doesn't try to connect twice
jeez
If your bot is already in that channel it will toss up a ClientException β You are already connected to a voice channel. error. You can wrap it in a try/except and just pass it.
ah true
Damn, I want to work on other peoples stuff more than my own today.
!contribute :)
Contribute to Python Discord's Open Source Projects
Looking to contribute to Open Source Projects for the first time? Want to add a feature or fix a bug on the bots on this server? We have on-going projects that people can contribute to, even if you've never contributed to open source before!
Projects to Contribute to
β’ Sir Lancebot - our fun, beginner-friendly bot
β’ Python - our utility & moderation bot
β’ Site - resources, guides, and more
Where to start
- Read our contribution guide
- Chat with us in #dev-contrib if you're ready to jump in or have any questions
- Open an issue or ask to be assigned to an issue to work on
all the interesting issues are already taken π
do people still use prefix commands these days
i want discord to do some input validation for me
hello, i have a slight issue?
cogs seem to be loading but no commands are showing from the cogs themselves on the help command
Alright, I'll try to remember my github then.
how do you get date and time when message in discord is sended , in own timezone
because message.created_at doesn't give my own timeozones time
My client.event s are working but my client.command() s are not, any ideas?
is client discord.ext.commands.Bot()?
what do you mean?
did you do something like py bot = commands.Bot(command_prefix='>', case_insensitive=True, intents=intents)
I have
client = commands.Bot(command_prefix = 'ED: ')
you need the message intent, which is not a default intent
I don't know what that means but I have another discord bot that has exactly the same code and it works
to add it, go to the dev page and turnon the message intent on your dashboard, then use this:py intents = discord.Intents.default() intents.message_content = True bot = commands.Bot(command_prefix='PREFIX', case_insensitive=True, intents=intents)
Just doing it now
ok
AttributeError: 'Intents' object has no attribute 'message_content'
what version of discord.py are you using?
not sure
is it the latest one?
I installed it a while ago so maybe not
when did you install it?
Easily a year ago likely more, not 100% sure
ok, can you run pip freeze in your terminal and send the version of discord.py
1.7.3
there's the problem.
How do I update it?
the latest is 2.0.1
also why does it work with my other code if it's outdated there too?
update using pip install --upgrade discord.py
is your other code hosted on a different device?
Unknown interaction error !
nope, same pc and stuff
virtual env?
It's all run off my pc written in idle
hmm i have no idea then
Just being dodgy ig haha
can someone help π
well I;m just letting you n=know that if you do update, there are a few breaking changes and a new way to start the bot, so head over to the docs to see them all
are you trying tomake a button?
oh wow, a lot of errors
yeah
it's made , but the callback doesn't work ! on click , it shows unknown interaction's error
can i see how you defined your callback?
ok so the buttons show up but when they are clicked they throw an error
exactly
i defer them all
but same error
is there any way to fix this ?
it looks like one of the buttonstyles are throwing an error too
gimm a few mins to test
okay
ok try adding a thinking=True inside the defer() funca
that way you use the followup in your code instead of trying to send a response
you are a legend ! this worked π
np
i just added the thinking you said about , and edited the time.sleep by asyncio.sleep
nice
is it possible to send a message that is visible to a specific members ?
i don't mean ephemeral
or using ephemeral without response
mods = ['1047266960519467057']
def check_Mod(ctx):
if ctx.author.id in mods:
IsMod = True
else:
IsMod = False
return IsMod
@bot.command()
async def bought(ctx,id=None,item=None):
IsMod = check_Mod(ctx)
if IsMod == False:
return await ctx.send("Your not a mod.", delete_after=10)
if id == None:
return await ctx.send(".bought <id> <item>", delete_after=10)
if item == None:
return await ctx.send(".bought <id> <item>", delete_after=10)
query.execute("""INSERT INTO LOGS (USER_ID, ITEM) VALUES (?, ?)""",(id, item,))
return await ctx.send("Sent to logs.")
keeps returning that im not a mod , any thoughts
The mods list is string of IDs, the ctx.author.id return an int
The userβs unique ID.
why not check their roles rather than hardcoding a list of users?
def check_mod(ctx):
return any(role.name == "Moderator" for role in ctx.author.roles)```
its more of a my server only bot then everyone use bot
UnboundLocalError: local variable 'uptime' referenced before assignment
I dont get it... can you guys help ?
Do you have a function named uptime ?
Because you are calling that in the 4th uncommented line
But that is also being stored on a variable named uptime
That's a conflict of name
import discord
from discord.ext import tasks
import datetime
client = discord.Client(intents=discord.Intents.default())
Replace YOUR_TOKEN_HERE with your Discord bot token
TOKEN = 'xxxx'
Replace YOUR_CHANNEL_ID with the ID of the channel you want to send the message to
CHANNEL_ID = 'xxxxx'
@tasks.loop(minutes=5)
async def send_uptime_message():
# Get the current time
current_time = datetime.datetime.utcnow()
# Check if the computer has been turned on within the last 5 minutes
# You may need to adjust this time depending on the performance of your computer
uptime = datetime.datetime.fromtimestamp(uptime()).strftime('%Y-%m-%d %H:%M:%S')
if current_time - datetime.timedelta(minutes=5) < uptime:
# If the computer has been turned on within the last 5 minutes, send a message to the Discord channel
channel = client.get_channel(CHANNEL_ID)
await channel.send('Your computer has been turned on!')
@client.event
async def on_ready():
send_uptime_message.start()
client.run(TOKEN)
Please check here code: https://pastebin.com/kwJrnigq
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
no solution commands message error giveaway and also image problem.
uptime = datetime.datetime.fromtimestamp(uptime())...
1st of all
A variable can't reference itself if it hasn't been assigned a value previously
2ndly you can't call a variable
I see yeah, thanks!
What are some top commands for discord bots?
I keep getting this error with my help command: Traceback (most recent call last): File "/root/bot/akro.py", line 14, in <module> async def help(ctx, *args): File "/usr/local/lib/python3.10/dist-packages/discord/ext/commands/core.py", line 1513, in decorator self.add_command(result) File "/usr/local/lib/python3.10/dist-packages/discord/ext/commands/bot.py", line 245, in add_command super().add_command(command) File "/usr/local/lib/python3.10/dist-packages/discord/ext/commands/core.py", line 1348, in add_command raise CommandRegistrationError(command.name) discord.ext.commands.errors.CommandRegistrationError: The command help is already an existing command or alias. but i do not have a other help command in my code any reasons why this could happen?
No worries π
Discord.py bots have a help command by default. You can define your bot with help_command = None
Remove the default help command
thank you.
thank you.
Tbh if you want a help command, don't remove the default one. Rather subclass it
But that's the choice of one own
Whenever i put the help_command = None i get the same error
Put it in the bot instance constructor
it has to be when you define the bot
bot = commands.Bot(command_prefix = get_prefix, help_command =None, intents=intents)
i use client = commands.Bot
it would be the same just with client at the start right?
client = commands.Bot(help_command = None)
thank you
They're an instance of the same class, so there's no difference, it's just the var name
How do I make a member get a dm when they join a server?
on_member_join
!d discord.on_member_join
discord.on_member_join(member)```
Called when a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member") joins a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild "discord.Guild").
This requires [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") to be enabled.
@bot event
on member join(user):
user.send("message")```
how do I use it and how do I dm a user
kinda like that
async def on_member_join(member):
# Send the DM to the member
await member.send("```
or @bot.event
i think i've only ever used client
Thanks jonah, this has also helped me with my code as well
It works well, but how do I put the user's name without the discriminator?
No problem.
What are some useful commands to add to my bot?
ban, unmute, mute, warn, help, unban, kick, ticket system, xp system
Discord already have most of those built in
Its makes it more convenient for me when i have it in my bot
instead of having to go to there profile and doing it manually
How can i reach my guild's member name in server? (server username)
list = ""
for victim_user_id, percentage in targeted_victims:
idlist = await bot.fetch_user(victim_user_id)
guildlist = await bot.fetch_guild(victim_user_id)
chance = (percentage * 100)
list += (f"Server username: \"{guildlist.name}\", username: \"{idlist.name}\" ve %{chance:.0f} chance got.\n")
await message.channel.send(f"msg")```
Guys how can i make a !d commands like @unkempt canyon in my discord.py bot
I actually the saw the command code but was not able to understand so can anyone help me?
The basic idea is that documentation has an "inventory" file that can be downloaded and parsed to get information on all documented symbols. That can be used to found where to webscrape the doc text. The @unkempt canyon command is complex because it has optimizations to cache results.
they are literally built in commands
u donβt have to do it manually, itβs a slash cmd by default
How can I get the inventory file
UNO game command
Really useful
The url varies. For example, for the Python docs it is https://docs.python.org/3/objects.inv
may i get help too please?
What's your question?
You need to get the guild first, and then get the member object in that guild
guild = bot.get_guild(guild_id)
member = guild.get_member(victim_user_id)
nickname = member.name
if member.nick is not None:
nickname = member.nick```
Ah, you can simplify that logic by just using member.display_name
why dont we use fetch instead of get?
fetch makes a request to the API, get gets it from the bot's cache
get_member needs to be called on an instance of a Guild. This is why my example uses get_guild() first. Furthermore, get_member is not a coroutine function and does not need to be awaited. Notice how my example does not use await.
then it should work?
guildlist = bot.get_guild(last_message.guild)
idlist = discord.Guild.get_member(victim_user_id)
chance = (percentage * 100)```
You're still not calling get_member on an instance of a Guild. You'll get the same error you showed earlier.
If you can already get a Guild instance from last_message.guild, then you do not need to use get_guild
i dont get this one
discord.Guild is a type. You need an instance of this type because get_member() is an instance method rather than a static or class method. One way to get an instance of it is to use get_guild() - it returns an instance of discord.Guild.
i did it but i got same error. i did this one
guild1 = bot.get_guild(last_message.guild.id)
It looks like last_message.guild already returns an instance of a Guild, so you don't need get_guild - it's redundant in this case.
member = last_message.guild.get_member(victim_user_id)
if member is not None:
name = member.display_name
else:
# member doesn't exist in the guild - handle this case somehow...
thaaank you
but if i dont got a last mesaage guild, how would it be?
oh this one, got it
How can I make a discord bot?
Read the documentation or watch a tutorial. https://discordpy.readthedocs.io/en/stable/index.html
ok... anyone got some suggestions for pagimations?
here's the code
https://paste.pythondiscord.com/deniripife
here's the error
https://paste.pythondiscord.com/toxoyujima
thoughts? suggestions?
--> self.TheData = {}
--> self.TheData.members
dictionaries don't have a .members attribute which is what the error tells you
i forgot to redefine the ctx.guild x.x
ok... now AttributeError: 'DataGrab' object has no attribute 'create_embed'
I can't see a create_embed method in the code you sent
do u want my paginator?
its simple and can be overwritten however u want it
line45, i removed it.
that's up to you π
i've been working on this for a bit and was trying to make a universal one that uses discord ui buttons.
https://paste.pythondiscord.com/vufaluyowa it includes the subclassed base view i use for all my views
its in disnake tho u have to make it discord in those places
also u can remove the on_error thats for my exception handler
whats the difference between disnake and discord.ui.buttons?
just replace disnake with discord and u will be fine
gotcha. also
yeah lol that was in mine
if u have a custom exception handler then u can use it with ur own custom exception
otherwise remove it
gotcha.
i got no error, but when i run the command it shows me app not respond error, code: https://paste.pythondiscord.com/azizemewed
gotcha! tyvm!
one last question, so where do i define my dict?
the ClassicPaginator __init__ ?
which library is this
official discord.py
nb: i alr try @bot.tree.error but still not work
what for tho?
average spoon feeder
nah above average
did u use bot.start() to start the bot?
bot.run..?
are u sure ur error handler is not eating up the error?
@huntMob.error
async def huntMobError(ctx, error: app_commands.AppCommandError):
if isinstance(error, app_commands.CommandOnCooldown):
em = discord.Embed(title=f"Don't Genocide!", description=f"The mobs need time to detect your existence, check again in {error.retry_after:.2f}s.",
color=ctx.author.color)
await ctx.send(embed=em)
u dont have an else
i see, thanks
... yeah, it print error Hybrid command raised an error: You are on cooldown. Try again in 58.08s but why it doesn't send the cooldown message?
updated:
@huntMob.error
async def huntMobError(ctx, error: app_commands.AppCommandError):
if isinstance(error, app_commands.CommandOnCooldown):
em = discord.Embed(title=f"Don't Genocide!", description=f"The mobs need time to detect your existence, check again in {error.retry_after:.2f}s.",
color=ctx.author.color)
await ctx.send(embed=em)
else:
print(error)```
what is the type of the error? is it not app_commands.CommandOnCooldown
hybrid commands raise a commands.commandoncooldown
also not sure app commands have ctx in error
They have interaction
its most probably an interaction
Hybrid command raised an error: You are on cooldown. Try again in 58.08s
hybrids have context...
I was talking about app commands, not hybrid
I never used hybrid so can't comment on that
π€
meant in general context
Oh hm
updated:
@huntMob.error
async def huntMobError(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
em = discord.Embed(title=f"Don't Genocide!", description=f"The mobs need time to detect your existence, check again in {error.retry_after:.2f}s.",
color=ctx.author.color)
await ctx.send(embed=em)
else:
print(error)``` still can't
no error in terminal?
i'm not understand, care to elaborate?
Hybrid command raised an error: You are on cooldown. Try again in 56.94s -> from print(error)
that was for asher π€·ββοΈ
oh ok
are you using the commands.cooldown decorator or app_commands.cooldown decorator
the app_commands.cooldown decorator, how to use the commands.cooldown one? (i use it for slash command)
what thing that replace the "key" arg
Exact same, but commands is for commands.Context and app_commands is for discord.Interaction
!d discord.ext.commands.BucketType.user
The user bucket operates on a per-user basis.
you need a bucket there
given that you just use the author id as key, this should be fine
tysm
tysm too
and tysm
for member in ctx.guild.members:
self.DataPost[f"Member: {member.name} Member.ID {member.id}\n"] = None
print(f"Data from DataPost: {self.DataPost.keys()}\n")
for role in ctx.guild.roles:
self.DataPost[f"Role: {role.name} Role.ID {role.id}\n"] = None
print(f"Data from DataPost: {self.DataPost.keys()}\n")
for category in ctx.guild.categories:
self.DataPost[f"Category: {category.name} Category.ID {category.id}\n"] = None
print(f"Data from DataPost: {self.DataPost.keys()}\n")
for channel in ctx.guild.channels:
self.DataPost[f"Channel: {channel.name} Channel.ID {channel.id}\n"] = None
print(f"Data from DataPost: {self.DataPost.keys()}\n")
you should be defining it inside the __init__ or as a classvar if it's to be binded with the class
which init 
wdym which, each class has only one init
their are two __init__'s in the code if you looked at the code he sent before you answered, you would of known that. 
how do we reference channels in embeds, meaning actually click on em to be redirected.
Current code
info=""
text_channels=[channel for channel in guild.text_channels if ('view_channel',True) in channel.permissions_for(guild.get_role(1061579212349263933))]
text_channel_description=[text_channel.topic for text_channel in text_channels]
for i in range (0,len(text_channels)):
info=info+f"#{text_channels[i]} -> {text_channel_description[i]}\n\n"
embed = Embed(title="Server Guide",colour=discord.Color.purple(),description=info)
<#channel_id>
thank you
Can you send a message into a text channel from the on_ready event?
Yeah
await [channel here].send('message here')
You shouldn't really be doing anything inside of on_ready
Sending a message doesn't really affect much, it's not really needed but you can do it regardless
yeah thanks
it could disconnect your bot and since on_ready is triggered multiple times [discord.py], it could duplicate the messages
true, i only use it for when i'm locally running the bot to test
ok
then where should I want to put a background task?
that runs while the bot does
wait can you literally just call a task outside of an event/command
good afternoon. please tell me. I study the documentation and often meet such functions. what to do to call them?
events?
hi ash
you don't call them, when the are inside a Client subclass, functions meeting certain names will be automatically used as event functions, and here on_message_edit is also an event
hello
error says it as much
progress.items is not a package
class TwitchStuff(commands.Cog):
def __init__(self):
self.live_notifs_loop.start()``` raises```py
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.twitch' raised an error: TypeError: TwitchStuff.__init__() takes 1 positional argument but 2 were given``` im so confused
def __init(self, bot): self.bot = bot
thanks it worked
ik
but how do i even import it correctly
i thought thats how u import stuff
from file name import something
Running this command:
@bot.tree.command(name='ttsjoin', description='Connects bot to vc for tts')
async def ttsjoin(interaction: discord.Interaction, *, channel: discord.VoiceChannel=None):
if not channel:
try:
channel = interaction.author.voice.channel
except AttributeError:
await interaction.response.send_message('No channel to join. Please either specify a valid channel or join one.')
vc = interaction.voice_client
if vc:
if vc.channel.id == channel.id:
return
try:
await vc.move_to(channel)
except asyncio.TimeoutError:
raise interaction.response.send_message(f'Moving to channel: <{channel}> timed out.')
else:
try:
await channel.connect()
except asyncio.TimeoutError:
raise interaction.response.send_message(f'Connecting to channel: <{channel}> timed out.')
await interaction.response.send_message(f'Connected to: **{channel}**', delete_after=20)```
raises
```discord.app_commands.errors.CommandInvokeError: Command 'ttsjoin' raised an exception: AttributeError: 'Interaction' object has no attribute 'voice_bot'```
Can anyone help please?
it has to be ctx.voice_bot usually
So vc = ctx.voice_bot?
I'm smoothbrain, which line do I putthat in
wait u already have channel.connect so u dont need it
just delete the voce_client bits from ur code it should automatically switch vcs
discord.app_commands.errors.CommandInvokeError: Command 'ttsjoin' raised an exception: AttributeError: 'Interaction' object has no attribute 'move_to'
I assume move_to is incorrect
All good
!d discord.Member.move_to
bye
await move_to(channel, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Moves a member to a new voice channel (they must be connected first).
You must have [`move_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.move_members "discord.Permissions.move_members") to do this.
This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
Changed in version 1.1: Can now pass `None` to kick a member from voice.
its a method of member object
no they want to bot to move to the user's vc
a bot in a server is a member as well.
i guess yeah but to use that you would need perms
permissions to move yourself?
which would be unnecessary if you just connect to vc
What if the bot is not currently in a vc? Does it still work? And if so how do I implment the code?
you cannot connect again if you're already in a vc
ye i'm guessing since it can move other users it is like admins dragging ppl into a new vc
then you'll have to use connect
if you use it on your user its like clicking on a.voice channel
oh ok it should be fine then
!d discord.VoiceClient this should generally be used to control voice protocols in dpy tho
class discord.VoiceClient```
Represents a Discord voice connection.
You do not create these, you typically get them from e.g. [`VoiceChannel.connect()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceChannel.connect "discord.VoiceChannel.connect").
Warning
In order to use PCM based AudioSources, you must have the opus library installed on your system and loaded through [`opus.load_opus()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.opus.load_opus "discord.opus.load_opus"). Otherwise, your AudioSources must be opus encoded (e.g. using [`FFmpegOpusAudio`](https://discordpy.readthedocs.io/en/latest/api.html#discord.FFmpegOpusAudio "discord.FFmpegOpusAudio")) or the library will not be able to transmit audio.
!intents
Using intents in discord.py
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
you need to provide intents
What about reading
Is there any downfall to using Intents.all() everywhere?
Listening for intents your bot does not require increases load
When you provide only required intents, gateway already filters the unneeded ones out, in other case you filter them and spend computing power and network bandwidth
So I'll be fine as long as I'm not running it on a 5602.
Probably except pyvenv.cfg too
Cool, was just wondering if the API would hate me.
I mean imagine a situation when your bot is on 3 servers, each has 100k members and every second 1k members changes their status (that's unrealistic but potentially may happen). You would receive 1k events, that would affect bandwidth certainly, and depending on how lib processes events, it would take computing powers as well
If you are new to coding I don't recommend starting from a discord bot due to complexity of that application
To project root folder
and how?
venv is like autogenerated folder you shouldn't be touching
Just select them and drag onto root folder?
I have to agree with Exenifix here, Discord.py is not the best place to start.
It is, but so is swimming if you know how to swim.
Something small, something like a little script that deals out a deck of cards.
- basic python (variables, loops, math, etc)
- data structures (list, dict)
- functions
- OOP basics
Minimum
i know some basics like loops, list, dictionary, if, else, variables. that kind of stuff
Need funcs and OOP
And after that, classes.
Classes is OOP term
Then you're not that new to coding
ok
could've used dataclass
i started 1 week ago

i do almost nothing else the whole day Xd
async programming where?
also typehints if slash commands
It's possible to learn from discord bots
Hiya, I was just wondering if there's a way I can code a /commandslist slash command and have it list the name and description for every command in the .py file.
So for example, for the ban command it would grab the name and description from the async def line and put it into a text message and repeat that for every command:
@bot.tree.command(name='ban', description='Bans a member from the server')
@has_permissions(ban_members=True)
async def ban(interaction: discord.Interaction, member: discord.Member, reason: str=None):
guild = interaction.guild
await member.send(f"You have been banned from: ***{guild.name}*** | {reason}")
await member.ban(reason=reason)
embed = discord.Embed(title=(f'***{member} has been banned*** | {reason}'), color=0xf6ff00)
await interaction.response.send_message(embed=embed)```
Is this possible? And if so how can I implement it into my code? (I am a beginner to coding so I may not understand some things sorry)
Like I did π€
Being quick doesn't mean you learned enough about it to be somewhat useful
still pretty fast 
Not how can I get symbols documentation from that file?
aye event loop knowledge and basic stuff is still needed
@solid orbit you can develop bots ig, this will help you to improve current knowledge and gain new
okay
I still don't certainly know what event loop is
hmm fair enough 
It's just a thing that has to be in every async app and has some methods for async stuff
!d discord.ext.commands.Bot.walk_commands
for ... in walk_commands()```
An iterator that recursively walks through all commands and subcommands.
Changed in version 1.4: Duplicates due to aliases are no longer returned
Idk how it works
Yeah typehints are must-know
It's a property
What are you trying to do with it?
Don't call it
message.author.id will give you their user ID
Check?
Your "ID" is a string
Experimenting with different help commands and came across this one which only gets the bot to send the message: help
How can I edit the code and get it to work for every command + show the description? (i.e. It goes through every command, grabs the name and description and puts them into a single message)
Help code:
@bot.tree.command(name="help", description="Returns all commands available")
async def help(interaction: discord.Interaction):
helptext = "(tildetildetilde)"
for command in bot.commands:
helptext+=f"{command}\n"
helptext+="(tildetildetilde)"
await interaction.response.send_message(helptext)```
Sample code (other command):
```python
@bot.tree.command(name='nick', description='Changes the nickname of a member')
@has_permissions(manage_nicknames=True)
async def nick(interaction: discord.Interaction, member: discord.Member, nick: str=None):
if nick == None:
await member.edit(nick=nick)
embed = discord.Embed(title=(f"Reset {member}'s nickname"), color=0xf6ff00)
await interaction.response.send_message(embed=embed)
else:
await member.edit(nick=nick)
embed = discord.Embed(title=(f"Changed {member}'s nickname to {nick}"), color=0xf6ff00)
await interaction.response.send_message(embed=embed)```
(btw the (tildetildetilde) is so Discord markdown doesn't break, normally there's 3 consecutive tildes there)
a slash command for displaying the commands your bot has is a weird thing to write when the user can already see all of your slash commands listed with their descriptions
but regardless you're likely only seeing help because you're iterating through prefix commands rather than the commands registered on your command tree
!d discord.app_commands.CommandTree.get_commands
get_commands(*, guild=None, type=None)```
Gets all application commands from the tree.
Actually yeah true, but what if I want to make the command so I can organise the commands into categories (moderation, fun, roles) rather than have default discord organise by alphabetical order
if you think a guide is worth it then thats fine ig
How do I insert the current date and time in Sweden instead?
import datetime
# Get the current UTC time
timestamp = datetime.datetime.utcnow()
# Insert the document into the collection
warnings_collection.insert_one({"user_id": member.id, "reason": actual_reason, "moderator_id": ctx.author.id, "timestamp": timestamp})```
https://stackoverflow.com/questions/68664644/how-can-i-convert-from-utc-time-to-local-time-in-python
can you check that how many reactions a message has? like when a message has 2 x reaction it sends a message
because i can't do with client.wait_for("reaction_add") because the bot puts automatically 2 different type of reactions so it would trigger the event instant
Hello I have this error someone can help me?
!d discord.User.avatar
property avatar```
Returns an [`Asset`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Asset "discord.Asset") for the avatar the user has.
If the user does not have a traditional avatar, `None` is returned. If you want the avatar that a user has displayed, consider [`display_avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.display_avatar "discord.User.display_avatar").
!d discord.Asset.url
property url```
Returns the underlying URL of the asset.
.
Working on the first part of an afk command, however I think I accidentally made it so you can add [AFK] to anybody's name when provided the option. How can I edit it so a user can only change THEIR OWN afk status?
@bot.tree.command(name='afk', description='Sets an AFK status to display when you are mentioned by another member')
async def afk(interaction: discord.Interaction, member: discord.Member, reason: str=None):
if member.nick == None:
await member.edit(nick=(f'[AFK] {member.name}'))
embed = discord.Embed(title=(f"Changed your status to AFK | {reason}"), color=0xf6ff00)
await interaction.response.send_message(embed=embed)
else:
await member.edit(nick=(f'[AFK] {member.nick}'))
embed = discord.Embed(title=(f"Changed your status to AFK | {reason}"), color=0xf6ff00)
await interaction.response.send_message(embed=embed)```
someone can help me how to fix that?
catgal pointed you towards the .avatar attribute, which itself has a .url attribute
???
!d Discord.message.reactions
No documentation found for the requested symbol.
you've made member a parameter of your command so if you only want it to affect the command user, remove the parameter and reference the caller instead with interaction.user
It will give you a list of the reactions in a message, subtract 2 because the bot adds some already.
seems like you should be using the check= parameter by writing a check function to ignore any reactions added by itself
Working on handling errors with my bot, specifically the MissingPermissions one, however I cannot get the code to work. What can I do to fix it?
bot.tree.command(name='kick', description='Kicks a member from the server')
@has_permissions(kick_members=True)
async def kick(interaction: discord.Interaction, member: discord.Member, reason: str=None):
guild = interaction.guild
await member.send(f"You have been kicked from: ***{guild.name}*** | {reason}")
await member.kick(reason=reason)
embed = discord.Embed(title=(f'***{member} has been kicked*** | {reason}'), color=0xf6ff00)
await interaction.response.send_message(embed=embed)
@bot.listen()
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.send(":redTick: You don't have permission to kick members.")
else:
raise error```
Ideally I want the @bot.listen() to work for every command, not just the kick one I sampled
You still need to define it as a command
How would I go about doing that? (I'm pretty much brand new to coding discord.py since I started around a week ago)
@has_permissions(kick_members=True)
@commands.command()
async def kick(interaction: discord.Interaction, member: discord.Member, reason: str=None):
Oh wait, you are using tree.
isnt there a on_application_command_error for slash commands or something?
No
Is this your main file or a cog?
!d discord.app_commands.CommandTree.error
@error(coro)```
A decorator that registers a coroutine as a local error handler.
This must match the signature of the [`on_error()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree.on_error "discord.app_commands.CommandTree.on_error") callback.
The error passed will be derived from [`AppCommandError`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.AppCommandError "discord.app_commands.AppCommandError").
owh
Main, I don't haev any cogs
discord.app_commands.errors.CommandInvokeError: Command 'get_blook_info' raised an exception: AttributeError: 'str' object has no attribute 'to_dict'
Halp
(example json):
"Aid_Blook": {"Desc": "A cool guy", "Img": "aid.png", "Rarity": "Uncommon"},
pythton:
async def get_blook_info(interaction:discord.Interaction,choice: Choice[int]):
await interaction.response.defer()
with open('blook.json') as f:
blooks = json.load(f)
blooks[choice.name]
em = discord.Embed(title=choice.name, description=f'{blooks[choice.name]["Desc"]}\n\nRarity: {blooks[choice.name]["Rarity"]}')
img = blooks[choice.name]['Img']
await interaction.followup.send(embed=em, file=img)
why
can a bot make a user join a vc on an interaction
sounds dumb but someone said it is possible
!d discord.Member.move_to
await move_to(channel, *, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Moves a member to a new voice channel (they must be connected first).
You must have [`move_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.move_members "discord.Permissions.move_members") to do this.
This raises the same exceptions as [`edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member.edit "discord.Member.edit").
Changed in version 1.1: Can now pass `None` to kick a member from voice.
i have a bot which sends a message to another channel when user sends the message, and when the message sended from the bot gets x amount of reactions it should dm the user who sent the message. But how do i get it inside the another event/function?
yep it is to move user from one to another but it can make a user join a vc right?
Like if user is not in vc but the interaction will join him in a vc
I do not know of a way to do that.
Your_Function(Info_To_Pass_To_That_Function)
yea i know this but what do i put in the function where the message.author is
What?
wait a sec
@client.listen()
async def on_message(message):
sender = message.author
#and code
@client.listen()
async def on_reaction_add(reaction, message):
## and here i want to use the sender variable```
i don't get it how it works, to pass the functions
ohhh, one sec
@client.listen()
async def on_message(message):
sender = message.author
#and code
@client.listen()
async def on_reaction_add(reaction, message):
sender = message.author
on_reaction_add has the same exact message object as on_message
!d discord.Message
class discord.Message```
Represents a message from Discord.
x == y Checks if two messages are equal.
x != y Checks if two messages are not equal.
hash(x) Returns the messageβs hash.
yea sorry forgot to say that in the on_message i have the bot send the message to another channel and delete it, and then the message.author changes to the bot and when you react to the message that the bot sended i need the original message sender to message to dm with the bot
so it's not the same message.author
You'll have to use a database
and store the message author id and stuff when you delete the message and send it to another channel
Lol, looking at it again, on_reaction_add does not have message, that's supposed to be user.
And To get the Message being reacted, access it via Reaction.message.
From there you get message.author
yea ookey imma try, thank you
good luck
Sorry, you lost me there. It's doing what?
It's the what the bot can see avatars part I'm getting lost on.
Oh, you want to pick one random user from that list and display they pic?
Let's start with just showing one random user and work up from there.
That's why I'm here
random.choice(list) is going to be your friend here.
Ah, that's because it's not a list, it returns a bunch of members objects, just not in a list.
what you want is guild.members
It's not going to be from ever single server the bot is a part of, only the server the command is being run in.
depends entirely on how you write your code.
how do i change an embed description after creating it
message.edit(embed=NewEmbed)
no like
i've a discord.Embed(title='x')
and i want to change the description later
yea i don't really get this cuz the message that the bot sends is in embed, can you give some sort of example of how to use that what you said.
has the message already been sent?
no
does somebody know what i have to do with this error message?:
Hey @solid orbit!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
TheEmbed=discord.Embed(title='x')
TheEmbed.title="Something new"
``` I think that will work.
and same for .description, i presume?
I want to say yes, but I did put this down without testing it myself first.
sure, one sec
Hey i have a conceptual question in myh mind. Like discord limits are 50 req per second btw suppose if a nuker is using ddos tool +threads to make 1m request a second then can it cuz more than 50 valid reqs??
No
Whats the login behind it
Well, kinda.
A DDOS is like if 1000 people came up to you and started trying to talk all at once.
I'll let you finish the analogy then.
.
@client.listen()
async def on_message(message):
sender = message.author
#and code
@client.listen()
async def on_reaction_add(reaction, message):
The_Message = reaction.message
The_author_of_the_message = The_Message.author
So you are trying to make an anti-nuke bot that can handle 1,000,000+ attacks a second?
wtf?
@crimson mauve thinking of
Btw unfortunately cant handle 50 bans only it is stopping the nuker at 75 now
Discor increased the limit i think so
Anti-nukers are on the same level as antivirus software. If you are at that point you have already mess up.
yea
Btw i made it completely clean
also you cant stop it if the bot just hits prune members lmao
Before or after it shots its shot?
u can ban the bot sure but it wont stop the member pruning
yeah just use on_ban event then get author of ban
Btw currently my plan is to make the fastest antiban
Its stopping the nuker at 50
Cux the nuker is using taskpool io to make 110 reqs per seconds
I didn't ask and if you feel the need to tell me without promt I'm going to say that's sus.
It's good to make body armor, it's better to train people not to be in the way of the bullet.
Could your bot stop my bot?
Btw untill you face a bullet with your self made body armour you can never know the strength of your armour
that discord refuses to patch themselves lol
That's a good idea, wearing it during initial testing is not.
Lmao anti community spam i haven't setup yeat in myh new bot
because it doesn't show in audit logs who is doing it.
I wil by tommorow
It's a 20 line server nuker that keeps all the people.
Could you stop it?
Bruh i also want to learn it how do u bypass the audit log i tried every method
@crimson mauve howw i k that u r making requestss to the api
Btw i tried it to evrything got logged
So it will log the damage done?
Yes it was
Now lemme clarify ur confusion
It only works in new servers
Btw in older servers everything gets logged
I tried it on my older server
If u need to test it there then come dm
I will be providing u invite of that server
What is wrong with this code?
@client.command()
async def warn(ctx, member: discord.Member, *, reason: str):
# Get the URL of the warned user's avatar
avatar_url = member.avatar_url
embed.set_author(name=f"Warn β’ {member.name}#{member.discriminator}", icon_url=avatar_url)
# Send the embed to the channel
await channel.send(embed=embed)```
are you on discord.py v2?
then member.avatar_url is now member.avatar.url
Still doesn't work
# Get the URL of the warned user's avatar
avatar_url = member.avatar.url
embed.set_author(name=f"Warn β’ {member.name}#{member.discriminator}", icon_url=avatar_url)```
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'url'
!d discord.Member.display_avatar consider using this instead of avatar
property display_avatar```
Returns the memberβs display avatar.
For regular members this is just their avatar, but if they have a guild specific avatar then that is returned instead.
New in version 2.0.
if the user doesn't have an avatar set then that will happen, you can use what Lee said
Still doesn't work:
# Get the URL of the warned user's avatar
avatar_url = member.display_avatar_url
embed.set_author(name=f"Warn β’ {member.name}#{member.discriminator}", icon_url=avatar_url)
# Send the embed to the channel
await channel.send(embed=embed)```
Neither does avatar_url = discord.Member.display_avatar
Because display_avatar still returns a Discord.Asset
If you click on the blue link in the replied message you can see.
Meaning; member.display_avatar_url has to be member.display_avatar.url
Since you are accessing the properties of the class discord.Asset
Thank you
Where are you getting member from?
Also quick tip, since member is a discord.Member object the __str__ cast function will return the username and the discriminator. Meaning ```py
# Get the URL of the warned user's avatar
avatar_url = member.display_avatar_url
embed.set_author(name=f"Warn β’ {member.name}#{member.discriminator}", icon_url=avatar_url)```
I the same as:
embed.set_author(name=f"Warn β’ {member}", icon_url=member.display_avatar.url)
wait, I scrolled up higher.
# Warn command
@client.command()
async def warn(ctx, member: discord.Member, *, reason: str):```
And you are passing the full mention like @young dagger when you run the command?
Huh, when did that change?
I should able to use it with userID as well
always that way
Since... forever. It's a MemberConverter since you call it with the typehint.
Β―_(γ)_/Β―
!d discord.ext.commands.MemberConverter
class discord.ext.commands.MemberConverter(*args, **kwargs)```
Converts to a [`Member`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Member "discord.Member").
All lookups are via the local guild. If in a DM context, then the lookup is done by the global cache.
The lookup strategy is as follows (in order)...
Lucas videos tell you can typehinting with discord.Member only accepts mentions but MemberConverter accepts ids and stuff
I could just never get it to work with anything but mentions.
I was confused for a long time
Well I don't know Lucas videos, but it seems to me that there wasn't a lot of research in his videos.
yeah his videos are full of bad practices
Yet to see a YT video that does it 90%, heck 60% correctly.
naming Bot as client, "json database", iterating over every banned member in unban command
Yep..
have a code that works on user input from the bot
there's a command in it that basically sets the value as true or false
now, when i do
@client.command()
async def config_xyz(ctx, arg1):
with open('json.json', 'w') as f:
config = json.load(f)
config['xyz'] = bool(arg1)
outfile = open("json.json", "w")
json.dump(config, outfile)
await ctx.send('done')β
this code somehow only changes the value for true that is if the xyz is set to false it changes that to true however doesnt do it for false. Any suggestions?
Is the indentation actually like this in the code or did Discord just mess it up?
dc messed it up
Good old Discord
Can you fix up the indents real fast?
i would but im on phone rn πΆβπ«οΈ
i never get tilde keys to work on phone ;.;
@client.command()
async def config_xyz(ctx, arg1):
with open('json.json', 'w') as f:
config = json.load(f)
config['xyz'] = bool(arg1)
outfile = open("json.json", "w")
json.dump(config, outfile)
await ctx.send('done')β
Does this look right?
Press and hold the quote key on iOS
!e
print(bool("True"))
print(bool("False"))
@sick birch :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | True
002 | True
omg what
Reason being bool(str) checks if the str is truthy/falsy
It's only false when it's an empty string
So it doesn't do what you expect it to do
!e print(bool(""))
@sick birch :white_check_mark: Your 3.11 eval job has completed with return code 0.
False
i-wow
Fortunately it's got a simple fix
what is it
@client.command()
async def config_xyz(ctx, arg1: bool):
...
Discord.py will appropriately convert it to a boolean for you
ohh, so i wont have to deal with that empty string bs?
No. "True" becomes True and "False" becomes False
π€―
Also things like "On", "Off", "0" and "1"

