#discord-bots
1 messages · Page 281 of 1
I saw this also
lol
yeah implement your own check
in your custom check you're able to check whether the user have the admin permission or has your custom role!
^^
!paste
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
https://paste.pythondiscord.com/TDBQ
these error handlers arent doing anything
there not raising errors
I want it to ignore this error handler and only use the try and except error handlers
@tree.error
async def on_app_command_error(interaction: discord.Interaction, error: AppCommandError):
command = interaction.command.name
channel2 = client.get_channel(1112053260879147130)
if isinstance(error, app_commands.CommandOnCooldown):
await interaction.followup.send(error, ephemeral=True)
else:
button = Button(label="support server", url="")
view = View()
view.add_item(button)
embed = discord.Embed(title="An error has occured", description="If you need help with this error join the support server. ", colour=discord.Colour.red())
await interaction.followup.send(embed=embed, view=view)
await channel2.send(f"{command} command used by {interaction.user} but an error occured")
traceback.print_exc(limit=None, file=None, chain=True)
do u know about the exception handler hierarchy
i think so
then whats the issue
cause the error dosent fall under category of attribute error or http exception
keep a broad exception clause if u want to handle for all cases
it does though
show traceback
u might wanna register a command specific error handler for this tho
seems cleaner than try except
yeah true
File "/Users/zagzag/vscode/zagzag/zagzag.py", line 627, in kick
await member.kick()
File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/member.py", line 762, in kick
await self.guild.kick(self, reason=reason)
File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/guild.py", line 3643, in kick
await self._state.http.kick(user.id, self.id, reason=reason)
File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/http.py", line 739, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/app_commands/commands.py", line 828, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "/Users/zagzag/vscode/zagzag/zagzag.py", line 639, in kick
if member not in interaction.guild:
TypeError: argument of type 'Guild' is not iterable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/app_commands/tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/app_commands/commands.py", line 853, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/app_commands/commands.py", line 842, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'kick' raised an exception: TypeError: argument of type 'Guild' is not iterable```
oh wait
guild is not iterable
its a type error
if member is not in interaction.guild:
Can I get some of that coke?
member is the Member object
pepsi
Euw
ok
Might as well eat a cup of sugar instead
wait is this correct?
cant drink it
no
I wish
It should be interaction.guild.members
is it if member not in interaction.guild.members:
Hmm
Me when people don't read answers to their already asked question
Hi Krypton
the bot is just thinking and not responding
I'm currently using this to use custom emoji from a specific guild. Is there any better way to achieve this?
guild = discord.utils.get(client.guilds, id=1135157269328302110)
primary_keystone_emoji = discord.utils.get(guild.emojis, name=primary_keystone.replace(' ', '_'))
secondary_three_emoji = discord.utils.get(guild.emojis, name=secondary_three)
first_shard_emoji = discord.utils.get(guild.emojis, name=first_shard.replace(' ', '_'))
second_shard_emoji = discord.utils.get(guild.emojis, name=second_shard.replace(' ', '_'))
third_shard_emoji = discord.utils.get(guild.emojis, name=third_shard.replace(' ', '_'))```
no error
I heard to use <:emoji:emoji id> but the problem is that there are 50 different emojis, which means that I have to save all the emoji ids in a json file anyway?
What's the problem
yes
What's the problem with my current method?
Messiness
useless method calls
If you already know their IDs, you can just use client.get_guild and guild.get_emoji
Or even literally just make a variables of the emoji string, like pit = ""
So if there is function that requires 250 emojis you need to sit for an hour to save all the ids? That is the proper way to do it?
you already did that but didnt store ids but names
Not true, I'm actually using a list:
SHARD_OPTIONS = [
["Adaptive Force", "Attack Speed", "Ability Haste"],
["Adaptive Force", "Armor", "Magic Resist"],
["Health Scaling", "Armor", "Magic Resist"]
]
first_shard = random.choice(SHARD_OPTIONS[0])
second_shard = random.choice(SHARD_OPTIONS[1])
third_shard = random.choice(SHARD_OPTIONS[2])```
And?
elif member not in interaction.guild.members:
pass
elif member.bot:
pass``` its ignoring this
how does that change anything
You have only pass in it, of course it will ignore it
You're basically doing nothing
do I use return then?
Not gonna be any different if you don't have anything after it
Im checking if it is a bot then do nothing
dont raise an error
What?
If the member is a bot I dont want it to raise error
Then don't??
What's the actual problem you're having
I'm not even sure what you're trying to do at this point
a kick command
and what are you stuck on?
except HTTPException:
if member == client.user:
command = interaction.command.name
channel2 = client.get_channel(1112053260879147130)
button = Button(label="support server", url="")
view = View()
view.add_item(button)
embed = discord.Embed(title="An error has occured", description="If you need help with this error join the support server. ", colour=discord.Colour.red())
await interaction.followup.send(embed=embed, view=view)
await channel2.send(f"{command} command used by {interaction.user} but an error occured 1")
elif member not in interaction.guild.members:
pass
print("1")
elif member.bot:
pass
print("2")```
this except handler
im trying to check if the member is no in the guild because they prob have their dms off
and bots do too
but its just going to on_app_command_error
I dont want it to
@slate swan
I know
May be worth sending the code with proper indentation
ok
Because here your indentation is screaming
where is this located
under a slash command
And a more broader overview of your code is probably better
E.g. sharing everything instead of parts of it
so you have a try except in a command
!paste
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
yeah
https://paste.pythondiscord.com/ULAQ
full code
https://paste.pythondiscord.com/ULAQ#1L16-L16
this is pointless too
ok
Just use return??
true ^
This code has too much spaghetti
You know you can use per command error handers right
Would prevent that 🍝 code
elif member.bot or member.something:
return
else:
raise e
File "/Users/zagzag/vscode/zagzag/zagzag.py", line 630, in kick
log2 = int(log.decode("utf-8"))
AttributeError: 'NoneType' object has no attribute 'decode'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/app_commands/commands.py", line 828, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "/Users/zagzag/vscode/zagzag/zagzag.py", line 635, in kick
await member.send(f"you were kicked from ``{interaction.guild.name}`` reason: {reason}")
File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/abc.py", line 1516, in send
channel = await self._get_channel()
File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/member.py", line 435, in _get_channel
ch = await self.create_dm()
File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/member.py", line 236, in general
return await getattr(self._user, x)(*args, **kwargs)
File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/user.py", line 530, in create_dm
data: DMChannelPayload = await state.http.start_private_message(self.id)
File "/Users/zagzag/Library/Python/3.9/lib/python/site-packages/discord/http.py", line 745, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50007): Cannot send messages to this user
The above exception was the direct cause of the following exception:
log is None
😟
what
here
you said it was pointless
but if i take it out it raises this error
!e ```py
def x():
pass
print("does code after pass work")
x()
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
does code after pass work
Proper handling of errors
Catch errors, use except X: pass
contextlib.suppress would be at least better
so do I put pass after?
no you dont put it at all
i think you are missing the point of this keyword
!d pass
7.4. The pass statement
pass_stmt ::= "pass"
``` [`pass`](https://docs.python.org/3/reference/simple_stmts.html#pass) is a null operation — when it is executed, nothing happens. It is useful as a placeholder when a statement is required syntactically, but no code needs to be executed, for example:
```py
def f(arg): pass # a function that does nothing (yet)
class C: pass # a class with no methods (yet)
when it is executed, nothing happens.
its only useful for example when ```py
def function():
pass
...
ah ok
except AttributeError:
await member.send(f"you were kicked from ``{interaction.guild.name}`` reason: {reason}")
``` so this is fine?
would work the same as before with pass
so yeah thats good
E.g. you can't do
print("Stuff")
def x():
# Implement later
x()
so you use pass
👍
how do I fix this error
well
If log is None
you make log not None
thats fine
idk how you gather it 
By having log not being None or handling correctly when it's None
i know
Then you know how to do it, that's good
if log is None: pass``` 
ok
Don't just copy paste everything 
that wont work ☠️
oh sarcasm


anyway pass needs to be under
not next to
Doesn't matter
How can i make a restart, and turn off command in discord.py?
Next to it works fine as well
oh.
!e py if None is None: pass
@slate swan :warning: Your 3.11 eval job has completed with return code 0.
[No output]
totally correct syntax
oh ok
!d discord.ext.commands.Bot.close
await close()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Closes the connection to Discord.
im tryna use discord.Guild.ban but when i run it i get this error:
File "main.py", line 58
await guild.ban(user, *, reason=Reason)
^^^^
SyntaxError: iterable argument unpacking follows keyword argument unpacking
code: ```async def ban(interaction:discord.Interaction, member:discord.Member, *, Reason:str):
await guild.ban(user, *, reason=Reason)
await interaction.response.send_message(f"User {member.mention} has been banned for {Reason} ")
how does one fix this
i think my syntax is really wrong but idk
whats Reason?
Use interaction.guild
reason for ban
the * is only used when defining functions its not used to pass arguments
It just explained what's wrong
Read the error
idk what it means lol
the * is not a valid argument in simple terms
ok
meaning dont just copy function definitions from docs
ok
!e
print(*(1 for _ in range(10)))
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
1 1 1 1 1 1 1 1 1 1
all that * means is that everything after it must be passed as keyword only
protip you can use .ban() method directly on Member object
so the code would just be
await guild.ban(user, reason=Reason)
await interaction.response.send_message(f"User {member.mention} has been banned for {Reason} ")```?
!d discord.Member.ban
await ban(*, delete_message_days=..., delete_message_seconds=..., reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Bans this member. Equivalent to [`Guild.ban()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild.ban "discord.Guild.ban").
c++ has entered the chat
whats the difference between guild.ban and member.ban
hell nah those pointers
that in guild.ban you need to pass member to ban and when doing member.ban it already knows what member to ban
(the one that method is used on)
so guild.ban lets u pick
discord/member.py lines 743 to 748
await self.guild.ban(
self,
reason=reason,
delete_message_days=delete_message_days,
delete_message_seconds=delete_message_seconds,
)```
this is how it works in source code if you understand it
it just calls guild.ban with self being member itself
delete_message_days is an int right
I fixed it by checking if the key is in the db
!d discord.Guild.ban
await ban(user, *, reason=None, delete_message_days=..., delete_message_seconds=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Bans a user from the guild.
The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
You must have [`ban_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") to do this.
check the docs


File "main.py", line 58, in ban
await interaction.guild.ban(user,reason=reason)
NameError: name 'user' is not defined
for example if you want the person who ran the command its ctx.author
ok
if its slash command its actually interaction.user
but i belive you dont want to ban person who used /ban command
true
than why isn't 'user' defined if it the library provides it for me
..
my brain is failing
it wont randomly spawn varriable in your code
ok
oh bruh
good point
not forgetting the varaibles i defined sounds like a good idea
also i like ur pfp down
👍
tortle
@bot.tree.command(name = 'kick')
@app_commands.describe(user = 'Who do you want to kick?', reason = 'Why do you want to kick them?')
async def kick(ctx, interaction: discord.Interaction, user: discord.Member, reason: str):
if interaction.user.permissions.kick_members:
await bot.kick(user)
await interaction.response.send_message(f'Seccsesfuly kicked {user}.', ephemeral = True)
else:
await interaction.response.send_message(f'{interaction.user.mention} dont have the required permission(s).', ephemeral = True)
Traceback (most recent call last):
File "/home/fady/Documents/Code/public/FlareMod/bot.py", line 29, in <module>
exec(f.read())
File "<string>", line 3, in <module>
File "/home/fady/.local/lib/python3.10/site-packages/discord/app_commands/tree.py", line 887, in decorator
command = Command(
File "/home/fady/.local/lib/python3.10/site-packages/discord/app_commands/commands.py", line 666, in init
self._params: Dict[str, CommandParameter] = _extract_parameters_from_callback(callback, callback.globals)
File "/home/fady/.local/lib/python3.10/site-packages/discord/app_commands/commands.py", line 374, in _extract_parameters_from_callback
param = annotation_to_parameter(resolved, parameter)
File "/home/fady/.local/lib/python3.10/site-packages/discord/app_commands/transformers.py", line 833, in annotation_to_parameter
(inner, default, validate_default) = get_supported_annotation(annotation)
File "/home/fady/.local/lib/python3.10/site-packages/discord/app_commands/transformers.py", line 792, in get_supported_annotation
raise TypeError(f'unsupported type annotation {annotation!r}')
TypeError: unsupported type annotation <class 'discord.interactions.Interaction'>
user.kick(reason=reason)
That doesn't exist either

Your ctx parameter is actually an interaction
And interaction is the first parameter for user, which has not supported type
(in such code)
Oh nvm it's an instance of Member
Might want to rename it to member so it's not misleading
okay
heyy how to make a button
thank ya
how to check user permissions
can you disable slash commands like normal commands with a check?
or is it not possible
!d discord.Member.guild_permissions
property guild_permissions```
Returns the member’s guild permissions.
This only takes into consideration the guild permissions and not most of the implied permissions or any of the channel permission overwrites. For 100% accurate permission calculation, please use [`abc.GuildChannel.permissions_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.GuildChannel.permissions_for "discord.abc.GuildChannel.permissions_for").
This does take into consideration guild ownership, the administrator implication, and whether the member is timed out.
Changed in version 2.0: Member timeouts are taken into consideration.
!d discord.app_commands.check
@discord.app_commands.check(predicate)```
A decorator that adds a check to an application command.
These checks should be predicates that take in a single parameter taking a [`Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction"). If the check returns a `False`-like value then during invocation a [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure "discord.app_commands.CheckFailure") exception is raised and sent to the appropriate error handlers.
These checks can be either a coroutine or not.
Examples
Creating a basic check to see if the command invoker is you...
or built in ones Like has_permissions or has_role
thanks
https://discord.com/channels/267624335836053506/1137406071443566682
can anyone help me pls the problem is been in the above link to the help seciton of server
@slate swan can u pls look into is sir
if i dont have the message content intent can i still get the message type?
!d discord.Message.content
The actual contents of the message. If Intents.message_content is not enabled this will always be an empty string unless the bot is mentioned or the message is a direct message.
How can I handle discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions errors?
what
check the bot has the right permissions to do the actions
I want to handle the errors
Can you give us more context?
Should I use if isinstance(error, commands.CommandError): for this?
Example
if isinstance(error, commands.CommandError):
# Handle the Forbidden error here
try:
await ctx.author.send(f":x: **Denied Permissions** Please contact an Admin. The following permissions are denied in #{ctx.channel.name} for Ultimate Bravery.")
return
except discord.Forbidden:
return```
is it normal for my commands to not work when i have no message content intent? i have already removed the custom prefix feature
Is this in an error handler for a command?
Yes
If prefix yes
If slash no
Yeah I'm using
@client.event
async def on_command_error(ctx, error):```
yes, the point of message content intents is to make people migrate away from prefix commands
You would catch discord.Forbidden
Tbh it's been 3 years everyone should've just made slash commands
but it was enforced only 1+ year ago
How can I make it so that you don't always have to set a dot, just write something and the embed is created directly
?
!d discord.Embed
class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
x == y Checks if two embeds are equal.
New in version 2.0...
If you count pre release then yes
is there an event when a application command gets invoked like on_command
nvm found it, it was hidden
FileNotFoundError: [WinError 3] Le chemin d’accès spécifié est introuvable : 'pms'
can someone help me pls ?..
ty
wait how ?
@slate swan
How what
what habe i to change ?
You are supposed to go to the docs i linked about Embed and read what methods it has
And find one matching what you need
Im sure you will find it
ty
..
i receive an error meaning that the directory pms doesn't exist but it exists ..
check if u gave correct path to file
it's a path to a directory
to get directory files list with os.listdir method sir
check if its coded correctly
more info u give = more help we can give.
telling us file not found... ok, there's multiple possible causes for this.
u should always show some code lines as well
it was working before i just changed the dir to another one
async def Methods(ctx : discord.AutocompleteContext):
fileslist = os.listdir(f'pms')
data = []
for file in fileslist :
filename = file.replace(".json", "")
data.append(filename)
return data
check if u maybe running it in admin if not then os lazy to tell have no perms
yep i see why u gave wrong dir
try to click on file name right button and copy file path
yeah but sometimes i change to another pc and location it can cause problems bcz i'm running this code from my usb key
the code just worked rn wtf 💀
only sometimes? jkjk
yeah 
Sounds like a question for #tools-and-devops
Thanks! I just realized that this probably wasn't the best place to post it : )
could someone help my with slash commands in discord.py please?
This is a basic syntax, keep in mind this is not meant to be used as is.
is it necessary to create like a new command tree for the client or can i just use the tree of commands.Bot?
If you use a Client you would need to make the tree yourself correct. Keep in mind although preferred by most experienced discord.py coders, it does have some challenges added due to Bot including other functionality like extensions.
hi, i am trying to figure out why emojis aren't working
is there another way I can specify the 🐡 , 🐟 , and ⚠️ emojis without copying them directly? I am storing these values in a database
Some parts of the embed won't render emotes, mentions etc properly on some Discord clients, if I recall correctly
It looks like you're using the footer to write your text but I can't tell properly, try using the description
ye it is description (will need to confirm ngl)
footer can render unicode emoji correctly, you just have to actually insert the unicode character for discord to render it
!charinfo 🐟
😮
either "\U0001f41f", "\N{FISH}", or "🐟"
in a python script that is, for a database you'd probably want to insert the actual character (third one)
hi yall Im currently learning python and I want to learn how to be a discord bot dev and being able to scrap the web and make automation bots. What are things do I need to learn to become proficent at that? Ive heard of selienum. but yeah thats all ive heard of.
stupid indentation? maybe??, but im stuck
Did you ping me?
You... pinged me, in this chan--never mind.
oh yea
i did
u a hepler right?
just i dont know if i cant or can do that here
can i?
I wouldn't recommend pinging people randomly. Individuals will help you when they are able. I have not used discord_slash.
I'm fairly certain that's an invalid module name though.
Why do you need discord_slash when you have discord.py 
it will work without it?
discord.py has had native support for slash commands for quite a while now
I haven't used discord_slash either, I just use discord.py for all my slash commands
can u give an code example ?
Discord_slash is an old lib and it doesn't support dpy v2+ afaik
how can I add clear and say?
What's this?
Then what's say?
and then it clears the messages
Tbh did u even look at the example robin sent above
There isn't a bug you are just doing it wrong
yea i tried a couple of methods that why i asked if someone know who can i have both
clear and say
Or 2 different commands
/clear
And
/say
Like this
no
Then?
The await after in your is outside for loop inline with if statement that might be the problem
anyone knows how to fix this?
Traceback (most recent call last):
File "D:\DISCORD BOT\app.py", line 48, in <module>
@bot.slash_command(guild_id = [1135998495166316577],description = "tets 1")
^^^^^^^^^^^^^^^^^
AttributeError: 'Bot' object has no attribute 'slash_command'. Did you mean: 'add_command'?
Well, did you?
wdym
it worked for me i changed the version and i switch it for the original version and its says this
If you are using discord.py there is no such thing as .slash_command decorator
so its pycord or smth?
yea its pycord
async def recruited(ctx: discord.Interaction):
embed = discord.Embed(title="Recruitment Statistics", color=rnp_color, description=f"""
Members Recruited Last Minute: {grabRecruited()}""")
ctx.channel.send(embed=embed)```
the command isnt showing up when i do /recruited
and i synced the command tree
fixed
if it would be pycord you wouldnt be getting the error
maybe you want to use pycord but have installed other libraries
check what discord libraries you have
pip list to get list of all
ahh can anyone just tell me how to do oath2a thing so that when a person type a command in my discord game bot he joins a server directly
You will need to have the user go through the normal Oauth2 "Authorization code" grant flow, and once you've exchanged the code for an access token, you can use that to join users into a server
and how can i set this thing up in my bot?
i have 0 idea of it so can u pls guild me
if you are new to discord api i wouldnt bother to set it up its hard to understand for beginner but if you wish to give it a try here are the docs and few examples in python https://discord.com/developers/docs/topics/oauth2
so time for a
i have a problem wehre i update the code for a command, restart the bot, then it still uses the old code
i synced the command tree so idk why
Did you save the changes? 🤷
yes
😫
---------------------------------------------------
**Members Recruited All Time:** `{grabRecruited("all")}`
**Members Recruited Past Month:** `{grabRecruited("month")}`
**Members Recruited Past Week:** `{grabRecruited("week")}`
**Members Recruited Past Day:** `{grabRecruited("day")}`
---------------------------------------------------
""")```
thats the new embed ^^
thats whats its showing after i restart the bot, make sure the code is saved, and sync the command tree
What is your previous code?
i dont have it
I can't just imagine it and be correct
because i changed it
all that changed was the description of the embed
but its not changing
What was the previous code's embed looks like?
the image above
thats the old code embed
and i updated the code to make it look better
and it still shows the old code
how do you restart the bot?
terminate the program and start it back up
dont make fun of me... but i use replit to host it while using uptime robot to ping it every 5 minutes with a keep alive script
i know its bad, but it does what i need it to
if you put for example print in the command
and run the command it wont print it out?
let me try
doesnt print
idk why its just using the old code when i pasted in the new code
i dont really use raises
could you tell me how
async def recruited(ctx: discord.Interaction):
embed = discord.Embed(title="Recruitment Statistics", color=rnp_color, timestamp=datetime.now(),description=f"""
---------------------------------------------------
**Members Recruited All Time:** `{grabRecruited("all")}`
**Members Recruited Past Month:** `{grabRecruited("month")}`
**Members Recruited Past Week:** `{grabRecruited("week")}`
**Members Recruited Past Day:** `{grabRecruited("day")}`
---------------------------------------------------
""")
await ctx.response.send_message(embed=embed)
print("hi")```
just raise is fine
so literally just put raise at the end?
@slate swan :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | raise
004 | RuntimeError: No active exception to reraise
RuntimeError 
nothing showed in console when i used it
not even a runtime error
maybe refreshing the page will work
well then the bot taht is running is not the one hosted on replit
then who the fuck is hosting it????
its not being hosted on my computer
you have an on_ready event?
i mightve possibly hosted it on my computer
im terminating it to see if thats the problem
most likely
and yes i do
you most likely have a print in here like Logged in does it print out on replit?
you have any text based command?
like a prefix command?
yes
no
:/
just prints "Command Tree Synced"
we could have checked it the bot is running twice by seeing if it outputs double
but if you dong send anything to channel
what if i turn off the repl
and then try the commands
and if they work then we know its running somehwere else
can try
how about you put in this code ```py
@bot.command()
async def test(ctx):
await ctx.send("...?")
"command "test" is not found"
how about you print out bot.commands in on_ready
hey
oh can i send a question i was stuck in it for 3days i opened diff books but still not got exact answer
that would be a great help
it didnt print anything
no errors
damn'
may i see code
ima dm it to u
why not here
!paste
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
the bot loaded prints
but the bot.commands does not
its using the old code as i said
not even empty list?
!d discord.ext.commands.Bot.commands
property commands```
A unique set of commands without aliases that are registered.
whats that for
for me seeing the docs about it
ah
well but this must print something 
its using old code but prints output to console in current one?
thats like not possible
no
basically everything that was put in the code before i updated that one embed works
everything after does not
okay but if you put a print statement it shoud print out right
how about we try raising error again
in on_ready
could be replit issue
it probably 100% is
another point why not use it
Why you should not use free hosting services for Discord bots
(this message is a temporary pin and will eventually be on our webstie)Replit
While this may seem like a nice and free service, it has a lot more caveats than you might think, such as:
- The machines are super underpowered.
- This means your bot will lag a lot as it gets bigger.
- You need to run a webserver alongside your bot to prevent it from being shut off.
- This isn't a trivial task, and eats more of the machines power.
- Repl.it uses an ephemeral file system.
- This means any file you saved via your bot will be overwritten when you next launch.
- They use a shared IP for everything running on the service.
This one is important - if someone is running a user bot on their service and gets banned, everyone on that IP will be banned. Including you.
from https://discord.com/channels/267624335836053506/965291480992321536
yeah all that doesnt matter to me
as long as the bot runs and works
im not paying for hosting for a fun community bot
@slate swan
something is broken 😭
im hosting on my computer now and it just wont recognize my slash commands
do you sync properly?
someone got the token somehow
pur luck? idk cus i didnt leak it
well you must have shared it somehow if someone got it
i specifically remember covering it up
well reset it on dev portal so its not valid anymore
god nukers fucking suck
multiple weeks of work just washed away because some little fucking degenerate eating cheetos over their computer with no friends or real life outside of discord is bored
What did they do
Gray = Secondary
Blue = Primary
That's the kind of buttons they are
And if you don't know how to use buttons -> https://github.com/Rapptz/discord.py/tree/master/examples/views
!d discord.ButtonStyle
class discord.ButtonStyle```
Represents the style of the button component.
New in version 2.0.
list of all available styles ^
idk where to start looking but was thinking of a simple bot that shows and update time every minute without user input
@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True, name=None)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
A hands-on guide to Discord.py
I'll check it out thanks
@slate swan what is a dpy masterclass?
a project to make guides for discord.py for each topic
few people from here make it
Didn't it have site? Cannot find it in the repo.
what do you mean?
A hands-on guide to Discord.py
A tutorial/guide explaining all features in discord.py and how to make a discord bot from scratch. - GitHub - FallenDeity/discord.py-masterclass: A tutorial/guide explaining all features in discord...
Maybe have a link in the repo main md
It's in the about, just blind don't mind me
you wish to contribute?
@discord.ext.commands.is_owner()```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that checks if the person invoking this command is the owner of the bot.
This is powered by [`Bot.is_owner()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.is_owner "discord.ext.commands.Bot.is_owner").
This check raises a special exception, [`NotOwner`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NotOwner "discord.ext.commands.NotOwner") that is derived from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
I have this discord chatbot, how do i make it answer when being dm?
registed on_message event
Can any one give a docs or something to help me in ban command
@slate swan
How I can set ban time
This is my command
@bot.command()
async def ban(ctx, member: discord.Member, *, reason=None):
if reason == None:
reason = "this user was been banned by" + ctx.message.author.display_name
await member.ban(reason=reason)
await ctx.send(member.name + " Has been banned")
..
@naive briar
Why you type and delete
What?
.
Oh
It works that bot unbans the user after given amount of time
That means it hard to make
It means that's not easy idk if so hard
Ok thx very much
Hello, is anyone able to direct me to a guide to working with slash commands in discord-py?
Thank you! It looks great!
How would you set up a bot so any time a command is sent it checks if the prefix is ._ rather than the normal bot prefix . and if the prefix is ._ then it will send the results of the command to the user's DMs rather than the chat. To be more specific, I want this to work on any command send, not just one. I'm doing this specifically because I don't want to add an if/else to every command.
easiest solution would be to make 2 commands one normal and one for dms like this ```py
@bot.command()
async def command(ctx):
# normal
@bot.command()
async def _command(ctx):
# dms
thats honestly kinda tempting, but at that point I might as well do the if/else so the help command isn't completely cluttered
i just dont know how you could make it notify command handle function should it send to dms or no
Well, you can probably edit the command handling part of the bot and use your own modified context
Where in the documentation should I start for doing that?
A hands-on guide to Discord.py
Thank you 
discord/ext/commands/bot.py lines 1387 to 1395
if message.author.bot:
return
ctx = await self.get_context(message)
# the type of the invocation context's bot attribute will be correct
await self.invoke(ctx) # type: ignore
async def on_message(self, message: Message, /) -> None:
await self.process_commands(message)```
Ok... So im having issues with coding my discord bot using Python and Visual Studio Code.
Im trying to implement a cog system for storing commands and organizing them, but every attempt i make i keep getting "bot.load.extention" errors with the cog system.. what am i doing wrong?
Did Discord.py disconue Cogs?
Discord.py still uses cogs, could you send an example of how you're loading them and the file structure?
Yeah gimme a sec
import discord
from discord.ext import commands
import os
from dotenv import load_dotenv
# Load environment variables from .env
load_dotenv()
# Get the bot token from the environment variable
TOKEN = os.getenv('DISCORD_TOKEN')
# Create a discord.Intents object with all intents enabled
intents = discord.Intents.all()
bot = commands.Bot(command_prefix='!', intents=intents)
# Cog: Command1
class Command1(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(name='command1')
async def command1(self, ctx):
# Action for command1
await ctx.send('This is command 1!')
# Cog: Command2
class Command2(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(name='command2')
async def command2(self, ctx):
# Action for command2
await ctx.send('This is command 2!')
# Load cogs when the bot is ready
@bot.event
async def on_ready():
print(f'We have logged in as {bot.user}')
await bot.add_cog(Command1(bot))
await bot.add_cog(Command2(bot))
# Run the bot with the loaded token
bot.run(TOKEN)
Are the cogs in the same file or are they seperate?
i tried them both ways in same fold and separate and same error
the bot refused to load in the cogs lol
and lastly i tried in the same .py file and still wouldnt work
you load cogs with
bot.load_extension('cogs.COGNAMEHERE')
And put the cogs into a folder named cogs
is the folder name mandatorily named cogs? or can i code it to be differnt
I don't know
baaaah
Not used discord.py much, your answer will be somewhere in the docs
https://discordpy.readthedocs.io/en/stable/ext/commands/cogs.html
originally the code was suppose to work like this:
import discord
from discord.ext import commands
import os
bot = commands.Bot(command_prefix='!')
# Load commands from the 'commands' folder
for filename in os.listdir('./commands'):
if filename.endswith('.py'):
bot.load_extension(f'commands.{filename[:-3]}')
@bot.event
async def on_ready():
print(f'We have logged in as {bot.user}')
# Replace 'YOUR_BOT_TOKEN' with your actual bot token
bot.run('YOUR_BOT_TOKEN')
cuz i was trying to make each command its own .py file
but got hung up on the bot not loading the folder commands
its like once i take the commands out of the bot.py file and put it in a cog system with the command in its own .py file it just breaks the bot
Thats technically possible
Are you adding the proper identifiers to the commands when they're a cog?
Well you need to run the bot first then add the extensions. You can add extensions before the bot start but I'm unsure you can add it before running.
You can i believe. But you need to await it anyways
!d discord.ext.commands.Bot.load_extension
await load_extension(name, *, package=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Loads an extension.
An extension is a python module that contains commands, cogs, or listeners.
An extension must have a global function, `setup` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the `bot`.
Changed in version 2.0: This method is now a [coroutine](https://docs.python.org/3/glossary.html#term-coroutine).
Depends on the version he's using but for newer versions that's true, great catch.
The devs of this chat also are making a more in-depth guides for FAQ's -> https://fallendeity.github.io/discord.py-masterclass/creating-a-bot/#making-an-advanced-bot
ok sooo.. .for example im doing this: tell me if its correct or not cuz it just seems like my bot hates me.
|bot.py|
from discord.ext import commands
import os
bot = commands.Bot(command_prefix='!')
# Load commands from the 'commands' folder
for filename in os.listdir('./commands'):
if filename.endswith('.py'):
bot.load_extension(f'commands.{filename[:-3]}')
@bot.event
async def on_ready():
print(f'We have logged in as {bot.user}')
# Replace 'YOUR_BOT_TOKEN' with your actual bot token
bot.run('YOUR_BOT_TOKEN')
|commands1.py| > in the commands folder = commands/command1.py|
class Command1(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command(name='command1')
async def command1(self, ctx):
# Action for command1
await ctx.send('This is command 1!')
def setup(bot):
bot.add_cog(Command1(bot))
the error comes back on "bot.load_extension(f'commands.{filename[:-3]}')"
every time
As Vitness pointed out loading extensions has to be done async. I recommend using the setup_hook.
# Function to load the commands cog
def load_commands_cog():
bot.load_extension('commands')
# Load cogs using setup_hook when the bot is ready
@bot.event
async def on_ready():
print(f'We have logged in as {bot.user}')
bot.add_listener(load_commands_cog)
???
Chat gpt it seems?
i have it trying to help me yes,... and its doing a horrible jog for something its MENT for XD
You're looking for something like this ```py
import discord
from discord.ext import commands
import os
class CustomBot(commands.Bot)
def init(self, *args, **kwargs)
super().init(*args, **kwargs)
async def setup_hook(self) -> None:
# Load commands from the 'commands' folder
for filename in os.listdir('./commands'):
if filename.endswith('.py'):
await bot.load_extension(f'commands.{filename[:-3]}')
async def on_ready() -> None:
print(f'We have logged in as {bot.user}')
bot = CustomBot(command_prefix='!')
Replace 'YOUR_BOT_TOKEN' with your actual bot token
bot.run('YOUR_BOT_TOKEN')
If its community creation so how the discord telling the date of unban
Oh
class CustomBot(commands.Bot)
def __init__(self, *args, **kwargs)
super().__init__(*args, **kwargs)
what is this?
Python code 
This is just to pass all the args & kwargs you put in the CustomBot object to pass to the commands.Bot object allowing to overwrite existing functions from commands.Bot.
@dense mesa I highly recommend using this -> https://fallendeity.github.io/discord.py-masterclass/creating-a-bot/
It goes trough all the basics and syntax you will need to know in order to get a basic grasp on discord.py
ok yeah it seems this system of cogs and extensions ChatGPT has no knowledge of.
just tried an example for it to analyze and it failed and wouldnt generate XD fun fun
It could have it since it did get added before 2021 but it would be outdated anyways.
yeah and im not paying just yet for gtp 4
ugh ... my brain is ganna hate me the next couple week now
i believe most online dpy resources arent comprehensive to begin with
I was thinking to contribute to the masterclass
or to the official guide
Rapptz/discord.py#7654
actually im not sure if thats still alive, last edit was a year ago
hm last commit to the docs/guide branch was february
Gpt-4 doesn't have newer info just better answers.
bah 😦
hense why i reframed from paying for it lol
...for now
shit i even have AI assistance installed in my Virtual Studio Code. which honestly is very helpful
Well you can use the guide I sent you and ask here.
I used github copilot for a year as technical review, everyone called it amazing but I wasn't that impressed.
Yeah it autocompletes some stuff, but when you are working with all the newest versions of different libraries it just doesn't help or just guesses.
lol copilot is amazing IF you have limited to no coding knowledge/experience
which is me
I'm an enthusiast, not a boneified coder.
I'd use copilot for LTS versions of certain programming languages and older libs but for new ones not so much.
when i dont provide a reason, the command doesnt work, why? py @client.command() async def ban (ctx, member:discord.User=None,*, reason = None): if reason == None: reason = "No Reason Provided." return embed = discord.Embed( title=f"*You have been banned from {ctx.guild.name} for {reason}*", color=0xfa6859) await member.send(embed=embed) embed = discord.Embed(color=0xfa6859) embed = discord.Embed( title= f"__**MEMBER SUCCESSFULLY BANNED**__ {hammer_emoji}", url="", color=0xfa6859) embed.add_field( name=f'**{member_emoji} MEMBER**', value=f' {member} ', inline=False) embed.add_field( name=f'**{scroll_emoji} REASON**', value=f"{reason}", inline=False) await ctx.send(embed=embed) # await ctx.guild.ban(member, reason=reason)
And.. I don't like spending 10 bucks a month on yet another subscription.
Is the embed reason empty when one is provided?
It should always state something a tleast.
no
Read your own code
Ah yeah.
Just remove that whole if and put the default value in the function.
or i can just delete the "return"
You could but in the function imo is cleaner.
I forgot how to install discord.py and discord.py 2.0
Me too been using Hikari ever since..
pip install library==version
poetry add discord.py
What about the raptzz GitHub
?
pip install git+<git_link>
Thanks
Do keep in mind this is not recommended and you will not get support if it's a library side issue.
No just the git+ and then the link.
no
Ok
Any reason you would need the dev branch @formal basin
What's the name of timeout permission in has_permissions
Like
@has_permission(what should I type here)
!d discord.Permissions.moderate_members
Returns True if a user can time out other members.
New in version 2.0.
@has_permissin(moderate_members=True)
?
prob 
Yes
can somone help here #1137774844600139828
I always get the error message in the first image, once the code in the second image runs for a minute or so. The exact time it takes is not consistent and it also happens in roughly the same time frame when I increase the sleep time.
Any idea what could be causing this?
The logs mean that the bot has connected to Discord, try seeing if the bot has enough perms to send messages, embeds etc
Can you verify the image location? The error generally means the file isn't present in that location anymore
(BTW u do know that u sent a screenshot of this channel right?)
And well, I would like to see the code of the command u r tryna invoke
do u have an on_message event?
It shouldn't interact with any file. The response for the http request is just a dictionary with some strings and stuff.
I think I may have finally found the culprit though.
You are requesting something from your locally hosted API?
yes.
Seems I managed to fix my issue as well. I spent two days completely perplexed and it turns out that the answer was that a global boolean is (unsurprisingly) not thread safe...
I replaced it with a janky queue that just acts like a boolean but as long as it works I guess it's okay. lol
Yea globals suck in most of the cases
global is a deadly keyword to use
Looks like there's a different issue now. 😭
I guess that happens when I queue too many discord commands and they have to wait for the http request? (not the one from my earlier image)
The error message says something about "command hd" which I have currently queued a bunch of.
Well, it looks like aiohttp timed out the request
Can I tell it to wait indefinitely in this specific case?
iirc there was a timeout kwarg in the constructor, lemme find
Thank you!
Yes
!d aiohttp.ClientSession
class aiohttp.ClientSession(base_url=None, *, connector=None, cookies=None, headers=None, skip_auto_headers=None, auth=None, json_serialize=json.dumps, ...)```
The class for creating client sessions and making requests.
Set the timeout argument to None
thank you!

Create slash command with the right decorator, make it purge messages when executed
https://gist.github.com/AbstractUmbra/a9c188797ae194e592efe05fa129c57f for slash commands and for purging you can use
await purge(*, limit=100, check=..., before=None, after=None, around=None, oldest_first=None, bulk=True, reason=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Purges a list of messages that meet the criteria given by the predicate `check`. If a `check` is not provided then all messages are deleted without discrimination.
You must have [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages) to delete messages even if they are your own. Having [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history) is also needed to retrieve message history.
Changed in version 2.0: The `reason` keyword-only parameter was added.
Examples
Deleting bot’s messages...
Struggling rn
It is back and now it happens much more quickly. 😭
I just tried to make it delete and resend the message in certain cases. As far as I can tell I didn't even touch the http request...
I thought I fixed it again (by fixing my weird "async with" stuff and adding "await" in front of the http request) but now it is back again for the third time.
This async stuff is complicated man.
share your code
The function that is causing the error message is too long for discord.
thx
!paste
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 Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
https://paste.pythondiscord.com/LC7Q
This is probably some of the worst code in the history of python. I am trying to learn as I'm going along. 😅
the error message points at the http request specifically. I have another request to the same server which doesn't have any problems. That one doesn't get spammed as often though.
Those are both queues though. Apparently that's fine?
It may be fine, but the use of global makes your code hell
Will the queues work without it?
I've seen it used with queues but I'm not sure if that person knew what they were doing either...
I'm using a lot of queues because they are the only working way I know of sharing information between asynchronous functions. So far that seems to work.
enable message_content intent
There is no ctx argument in the on_message event, only message
And you may want to not leak your token, even just parts of it
Yes
idk how to code it
discord.py 2.0+ slash command info and examples. GitHub Gist: instantly share code, notes, and snippets.
shii ty
hi yall
yo
The error explained it in plain English
lmfao
oh
string indices must be integers, not str
!e
print("meow"["a"])
@naive briar :x: Your 3.11 eval job has completed with return code 1.
001 | /home/main.py:1: SyntaxWarning: str indices must be integers or slices, not str; perhaps you missed a comma?
002 | print("meow"["a"])
003 | Traceback (most recent call last):
004 | File "/home/main.py", line 1, in <module>
005 | print("meow"["a"])
006 | ~~~~~~^^^^^
007 | TypeError: string indices must be integers, not 'str'
!e "something"[1:2] # works
"something"["some_key"] # wont work
!e
print("meow"[2])
@slate swan :x: Your 3.11 eval job has completed with return code 1.
001 | /home/main.py:2: SyntaxWarning: str indices must be integers or slices, not str; perhaps you missed a comma?
002 | "something"["some_key"] # wont work
003 | Traceback (most recent call last):
004 | File "/home/main.py", line 2, in <module>
005 | "something"["some_key"] # wont work
006 | ~~~~~~~~~~~^^^^^^^^^^^^
007 | TypeError: string indices must be integers, not 'str'
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
o
bruh
wait then how am i supposed to access my table
How did you load your "table"
print out what server actually is
If you just read the file and didn't load it into a dict, it's only going to be a string
server shouldd be lizzy_xds server
im asking for actual value so print it out
also why isnt it looping thru the full table
i thought for loops loop through their arrays until broken/ended
its just the dictionary key not a dictionary
what is Configurations["something"]
Indexing the dictionary
oh this way
!e
a = {"key_1": 0, "key_2": 1}
for b in a:
print(b)
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | key_1
002 | key_2
items()```
Return a new view of the dictionary’s items (`(key, value)` pairs). See the [documentation of view objects](https://docs.python.org/3/library/stdtypes.html#dict-views).
!e
a = {"key_1": 0, "key_2": 1}
for b in a.values():
print(b)
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 0
002 | 1
or values if you dont neeed the keys
try
now see what you get when you do .values()
Only returns the children
Dictionary keys can't be repeated

!e
a = {"b": 0, "b": 1", b": 2}
print(a)
wondering how easy (or complicated) will it be to shard a discord bot across multiple hosts
i.e. instead of being sharded on one machine, it will sharded across multiple ones
!e
a = {"b": 0, "b": "1", b": 2}
print(a)
🧐
!e
a = {"b": 0, "b": "1", "b": 2}
print(a)
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
{'b': 2}
Only three tries 🥱
'ServerInformation' : {{}, {}}
'ServerInformation' : [{}, {}]
I don't think is the appropriate channel for that
I was trying to show that dict keys can't be repeated
oh
But you're right
wondering how easy (or complicated) will it be to shard a discord bot across multiple hosts
i.e. instead of being sharded on one machine, it will sharded across multiple ones
It's still not looping through the dictionary until it's printed all the objects, though
It's only printing the first one
i would say its not doable or not so easy if it is at least
@slate swan hey man can you help me out w this for asec
how would isolate AdChannelID's key?
you want to access this key?
I think it should be doable considering you can have multiple instances of the same bot running from different IPs
please don't use ableist language
do you not know how to access the keys?

that's clusters
mb mb
oh
so how complicated is it?
ah clusters 
mhm, I'm not that expert in that camp since I haven't ever tried it since I didn't need it, but I have a guide written by someone that I know, so I could share
I mean cluster a bot is something that you do when you reach a considerable amount of guilds and users
is from discord import app_commands for application commands
okay
here's the guide @slate swan @untold flax https://medium.com/@skelmis/clustering-a-python-discord-bot-13f409f4c5b2
A simplistic tutorial on clustering Python discord bots utilizing Docker.
thanks. I didn't know there was a term for that.
ah so just split up to many docker services
basically every cluster handles only X amout of shards
AttributeError: module 'datetime' has no attribute 'now'
the docker thing and github action thing are to deploy the Bot
it's datetime.datetime.now so
from datetime import datetime
datetime.now()
# or
from datetime.datetime import now
now()
# or
import datetime
datetime.datetime.now()
the diffcult part would be making sure that all the clusters are aware of each other
i.e if you send a command then only one responds
iirc the library should handle that automatically
that's why you pass shards info to the AutoShardedBot class
lemme take a look
@client.event
async def on_message_edit(before, after):
z = client.get_channel(1137779370988154936)
embed = discord.Embed(title=f"{before.author} Edited Their Message",
description=f"Before: {before.content}\nAfter: {after.content}\nAuthor: {before.author.mention}\nLocation: {before.channel.mention}",
timestamp=datetime.now(), color=discord.Colour.blue())
embed.set_author(name=after.author.name, icon_url=after.author.display_avatar)
await z.send(embed=embed)```
from datetime import datetime btw
ah yeah then basically this runs multiple docker services and the AutoShardedInteractionBot starts and listen only X number of shards (with a given ID which is generated)
@glad cradle 🙏
mh it should work
would be cool if you tell us whats the issue
@slate swan
!e ```py
from datetime import datetime
datetime.now()
@slate swan :warning: Your 3.11 eval job has completed with return code 0.
[No output]
if you have this import is must work
show your imports
maybe you have something that overrides it
@bot.command()
@has_permissions(moderate_members=True)
async def timeout(ctx, member: discord.Member, time):
if "s" in time or "S" in time:
gettime = time.strip("s")
if (gettime) > 2419200:
await ctx.reply("Timeout time cannot be more than 28 days")
else:
newtime = datetime.timedelta(seconds=int(gettime))
await member.edit(timed_out_until=discord.utils.utcnow() + newtime)
await ctx.reply(member.mention + " Has been timed out")
@timeout.error
async def timeout_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.reply("**You don't Have permissions to use this command**")
Why the command not working
import discord
from discord import client
from discord.ext import commands
import json
import os
import requests
import asyncio
import string
import random
import time
from datetime import datetime
how about you print this -> print(dir(datetime))
nvm i fixed it
?
there was a thingy bellow
👍
not working doesnt actually tell us anything can you elaborate
ty anyway
Nothing happens when I type it
Nothing in console and the bot doesn't make any thing
you have message_content intent right?
firstly check if it even is called
put a print at top of function and see if it prints out
Wait
could be many reasons share code, error or elaborate more about not work meaning
crap i already deleted it
@slate swan yup its called
@harsh orbit do you have an on_message event?
then debug it more by checking if the if is true
No + other commands are working
and further inside till you find whats wrong
Thats gonna take a lot of time 😫
i would start by printing out whats stored under member and time varriables
Ok i will start checking
hi down
mhm
All the problem because i didnt set int to gettime in the if
why wont this define
What is the actual error?
i fixed it
turns out you need async to have await
Yeah you do
If it would be find it wouldnt error
Can you print out the patron dict?
Print out patron and see what is has
yeah 1 sec
holy shit
im a dumbass
i forgot to save my config file
is there a way for me to put two strings in this conditional?
Can you elaborate?
if something in string or other_something in string: ...
like i want to reply to "Roger Guedes" and "Ribamar"
and Roger Guedes is alredy there
but i don't know how to put roger guedes and ribamar at the same time



