#discord-bots
1 messages · Page 298 of 1
I don't really understand how it could be useful tbh
Why would you want the bot token then?
??????
what
So you want to send the message from the bot account that the token is associated with?
sounds like commands to me
i don’t think so, i think he just made a typo lol
doubt
like for example, ?help
then what do you want?
so basically on_message and just check for hello
Then what would a command do?
Then you wouldn't need the bot token, or guild ID
he just wants to bot to print it out in the channel when he runs the script
i understand it’s not practical either but he’s just learning ofc
Yes, but I don't see why he would need a token as an arg for that
you need a bot token for discord
Yes, but you don't need to include it as an arg
But not as an arg
It's only needed in run()
don’t forget your .env
is anyone making discord bots now? 💀
yeah trying to go against ToS
wdym
welp music
aah right
but making bots isn't against tos
before there were like 10 people active in this channel
yeah
welp there are loopholes
ig it wasn't defined
nope
Yes bobux bot is in active stage of development!
And promotional campaign
I accidentally broke voting rewards and they didn't work for a week so I had to make apology video
🥶
how I can change bot name & photo nfrom the project?
hai shrey
Until they can cover every bots functions with built in versions like they are moderation tools right now, people will be making bots.
There are moderation tools by discord, but people still make moderation bots
So just always :p
Yea ik, discords mod tools still don't cover as much as some bots
Like?
Idk about that but i found the discord in built moderation system better
Why we have #discord-bots and not #telegram-bots ?
Having issues with my bot not sending a DM and setting the user's nickname, any help would be appreciated, if you need further information, please let me know.
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.
Can u tell us the error you are getting
I am not getting any errors at all, it just doesn't set the nickname or send the user the message congratulating them on completing their application.
I am thinking it something to do with how I am defining the user but I am not to sure.
well i was going to say invite links but i guess you can do that with keyword matching and regex
Where or what command is having a problem?
Is it the enlisted command?
And that's one hella code
Oh and one more thing use an async lib for db
As a synchronous lib can cause blocking
is it sending the one at the beginning before sending the embed
I believe it is where handle_accept_application function is
I tried running it through ChatGPT4 to see if it could find the error but it couldn't
I should've really put in try statements and implemented better error handling, would've made it alot easier but this is more of a side project and just for a bit a fun
#makeerrorhandlinganorm
I know I know lol
can you discord.utils.get a list of roles?
I am still learning Python so almost everything I do, I am way out of my depth but I feel it's a lot more fun
understandabler
I think so?
Try using print statement after every line
With try statements?
i dont think it takes a list object, thats probably why its not assigning any roles, your get is returning None
No without try except
Oh, but then why would me sending the message not work?
We are just checking to see till where your code is executed
Okay, so just literally print("Done")?
Is there a quick way to do that?
!d discord.utils.get
discord.utils.get(iterable, /, **attrs)```
A helper that returns the first element in the iterable that meets all the traits passed in `attrs`. This is an alternative for [`find()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.utils.find).
When multiple attributes are specified, they are checked using logical AND, not logical OR. Meaning they have to meet every attribute passed in and not one of them.
To have a nested attribute search (i.e. search by `x.y`) then pass in `x__y` as the keyword argument.
If nothing is found that matches the attributes passed, then `None` is returned.
Changed in version 2.0: The `iterable` parameter is now positional-only.
Changed in version 2.0: The `iterable` parameter supports [asynchronous iterable](https://docs.python.org/3/glossary.html#term-asynchronous-iterable)s...
this works
try:
blah blah blah
print("successful")
except:
print("error here")```
It takes any iterable, so it can take list objects
in its most basic form
hmmm ok
Okay, so what could I use instead then?
Instead of what?
I can do either but I got 2 people telling me to do different lol
Which ever you feel easier
Well, I need to get the roles to assign the member
But both are doing samething
What's the problem with the discord.utils.get? Because I see none
its all preference but i personally have a print in both cases
I thought it won't work when getting roles from the server?
We won't know the issue unless he debugs it
i just didnt know if it took a list or not
Why would that be? The only problem I'm seeing is that you're trying to check if the id attribute of the role objects is a list, which will never be true
Are you talking about the iterable or *attrs argument?
staff_role = discord.utils.get(user.roles, id=staff_role_id) his staff_role_id is a list
So what would I change it too?
That is true
That's valid 🤷
that was my only question about it, i didnt know it took a list
It can take anything
throw some print() statements around your code and see where it stops
Apparently there isn't any exeptions, it ran all of the code.
Make it actually check if the roles' IDs is in the list instead of checking if their IDs are equal to a list?
async def handle_accept_application(message, user):
# Check if the user who added the reaction is a staff member
staff_role_id = [1147834535728402523, 1147834296778887221, 1147834091455139870, 1147991729790779556, 1147991646714208286, 1147990426603749442] # Replace with the staff role ID
staff_role = discord.utils.get(user.roles, id=staff_role_id)
if staff_role is None:
return # Only staff members can accept applications
# Get the information from the message's embed
try:
embed = message.embeds[0]
applicant_mention = embed.description.split("\n")[0].split(":")[1].strip()
division = embed.description.split("\n")[3].split(":")[1].strip()
applicant_id_match = re.search(r'\d+', applicant_mention)
except Exception as e:
print(f"Error: {e}")
# Extract the user ID from the mention
try:
if applicant_id_match:
applicant_id = int(applicant_id_match.group())
else:
await user.send("Invalid mention format in the application.")
return
except Exception as e:
print(f"Error: {e}")
# Update the rank to "Accepted" in the database
try:
cursor.execute('''
UPDATE enlistments
SET rank = ?
WHERE user_id = ?
''', ("Private", applicant_id))
conn.commit()
except Exception as e:
print(f"Error: {e}")
# Fetch the applicant's user object
try:
applicant = await bot.fetch_user(applicant_id)
except Exception as e:
print(f"Error: {e}")
# Get the server (guild) and member objects
try:
server_id = 1147831792712306749 # Replace with your server ID
server = bot.get_guild(server_id)
member = server.get_member(applicant_id)
except Exception as e:
print(f"Error: {e}")
try:
if member is not None:
# Assign roles based on division
Infantry = discord.utils.get(server.roles, name="Army")
MilitaryPolice = discord.utils.get(server.roles, name="Military Police")
Logistics = discord.utils.get(server.roles, name="Logistics")
V1 = discord.utils.get(server.roles, name="V1 Authorisation")
if division == str(Infantry):
await member.add_roles(Infantry)
await member.add_roles(V1)
elif division == str(MilitaryPolice):
await member.add_roles(MilitaryPolice)
await member.add_roles(V1)
elif division == str(Logistics):
await member.add_roles(Logistics)
await member.add_roles(V1)
except Exception as e:
print(f"Error: {e}")
try:
if division == "Infantry":
x = "ARMY"
elif division == "Military Police":
x = "MP"
elif division == "Logistics":
x = "LOG"
r = "PVT"
new_nickname = f"{r} | {applicant.name} | {x}" # Customize the new nickname format
await member.edit(nick=new_nickname)
except Exception as e:
print(f"Error: {e}")
try:
await applicant.send("Congratulations! Your application has been accepted. You are now a member of the division.")
except Exception as e:
print(f"Error: {e}")
else:
try:
await user.send("Failed to find the applicant in the server. Make sure they are still a member of the server.")
except Exception as e:
print(f"Error: {e}")
Like this:
staff_role_id = [1147834535728402523, 1147834296778887221, 1147834091455139870, 1147991729790779556, 1147991646714208286, 1147990426603749442]
staff_role_id = any(role.id in staff_role_id for role in user.roles)
if not staff_role_id:
return
Ah
why no one answer me?
Damn I am struggling
staff_role_id = [1147834535728402523, 1147834296778887221, 1147834091455139870, 1147991729790779556, 1147991646714208286, 1147990426603749442]
has_staff_role = any(role.id in staff_role_id for role in user.roles)
if has_staff_role is True:
staff_role_id = discord.utils.get(user.roles, id=staff_role_id)
elif has_staff_role:
return
@naive briar This look right?
Probably better to make staff_role_id a set, so checking if value in it will be O(1), and you named your temporal variable same way as list, it will overwrite it
.....
I do not understand.
Check documentation about any()
No, you're still checking if the roles' IDs are equal to a list
bruh
import discord
from discord.ext import commands
# Initialize the bot
intents = discord.Intents.default()
intents.typing = False
intents.presences = False
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.event
async def on_ready():
print(f'Logged in as {bot.user.name}')
@bot.command()
async def change_name(ctx, new_name):
if ctx.author.guild_permissions.manage_guild: # Check if the user has 'Manage Server' permission
await bot.user.edit(username=new_name)
await ctx.send(f'Bot name changed to {new_name}')
else:
await ctx.send('You do not have permission to change the bot name.')
bot.run('YOUR_BOT_TOKEN')
``` From ChatGPT4 to change bot name.
```py
import discord
from discord.ext import commands
# Initialize the bot
intents = discord.Intents.default()
intents.typing = False
intents.presences = False
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.event
async def on_ready():
print(f'Logged in as {bot.user.name}')
@bot.command()
async def change_avatar(ctx, avatar_url):
if ctx.author.guild_permissions.manage_guild: # Check if the user has 'Manage Server' permission
async with aiohttp.ClientSession() as session:
async with session.get(avatar_url) as response:
if response.status == 200:
data = await response.read()
await bot.user.edit(avatar=data)
await ctx.send('Bot avatar changed successfully.')
else:
await ctx.send('Failed to fetch the image. Make sure the URL is valid.')
else:
await ctx.send('You do not have permission to change the bot avatar.')
bot.run('YOUR_BOT_TOKEN')
``` From ChatGPT4 on how to change avatar.
!rule 10
My bad.
bot.user.edit whats wrong
!d discord.ClientUser.edit
await edit(*, username=..., avatar=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the current profile of the client.
Note
To upload an avatar, a [bytes-like object](https://docs.python.org/3/glossary.html#term-bytes-like-object) must be passed in that represents the image being uploaded. If this is done through a file then the file must be opened via `open('some_filename', 'rb')` and the [bytes-like object](https://docs.python.org/3/glossary.html#term-bytes-like-object) is given through the use of `fp.read()`.
The only image formats supported for uploading is JPEG and PNG.
Changed in version 2.0: The edit is no longer in-place, instead the newly edited client user is returned...
!d any
any(iterable)```
Return `True` if any element of the *iterable* is true. If the iterable is empty, return `False`. Equivalent to:
```py
def any(iterable):
for element in iterable:
if element:
return True
return False
Chain them with or then
I don't understand that message one bit
Nor do I
I am just beginning with Python in the grand scheme of things so this is getting confusing
But I am wanting and willing to learn
Why is not it
def any(iterable):
for element in iterable:
if element:
break
return element
Either last or first Boolean True
Anywayy
Im not helping
Right, it seems to have fixed the issue and now for the most part works however, I am getting the error below and for some reason, it keeps saying {x} is undefined when editing the nickname.
2023-09-05 13:24:24 ERROR discord.client Ignoring exception in on_reaction_add
Traceback (most recent call last):
File "C:\Users\kiera\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "c:\Users\kiera\Desktop\CDC Discord Bot\main.py", line 217, in on_reaction_add
await handle_accept_application(reaction.message, user)
File "c:\Users\kiera\Desktop\CDC Discord Bot\main.py", line 332, in handle_accept_application
await message.add_reaction("✅") # Accept
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\kiera\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\message.py", line 1116, in add_reaction
await self._state.http.add_reaction(self.channel.id, self.id, emoji)
File "C:\Users\kiera\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\http.py", line 741, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10008): Unknown Message
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.
await message.delete() # <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
# Add reaction options for staff to accept or deny the application
await message.add_reaction("✅") # Accept
await message.add_reaction("❌") # Deny
how do you want to add a reaction to deleted message
magic?
Time travel is not magic it is science
they are not going back in time tho
they are just trying to add reaction to something that doesn't exist
Because magic exists
Null ref
always hated the pointers
Imagine those reaction appear in log of deleted messages?
In the accounts with self bots that save deleted messages
Idk, python is all references
They become strange when mixed with variables
" What is variable??? "
That is the question that i got when trying C
i need a very smart and fast individual to help me with finishing a very beneficial discord bot for a big project im working on for a server. i currently have a friend that is very experienced with coding and we have got a good amount of the coding done but i would like to get someone else that can help speed up the process. the bot is meant to track messages and VC hours and convert them into points then have leaderboard ranking system. seperate channels with automatic refreshing embed leaderboards of the top 10 people in the server with the highest points for alltime, monthly, weekly & daily. what has been done so far is the .stats command which is meant to provide basic information on an individuals stats in the server, but we have not been able to fully finish this to begin on the leaderboard coding. i need someone that can help with tracking VC hours (time spent in any voice call) and display that time on the stats command and convert it into points (1 second = 1 point by default, if the user is boosting it is 2x points per second) 1 message in chat = 1 point. (double for boosting) below is a screenshot of the current embed displayed when the command is used. please hit me up if you can work with me, i am willing to provide a big reward on your end considering this will help my new server a lot. i can make huge active servers
i also have created all of the embeds that i want to use, including the ones for the leaderboards. just need someone to help with the coding of stuff. if you are able to continue from the current code we have now that would be great
distributing the points by 1 sec might cause you to run into ratelimits
What?
like if bot is checking every second who is active in vc wouldn't that cause ratelimit issues
considering it is also counting message sent count and other stuff
Just don't? You can just use the on voice update events and keep track with a dict or something
yeah that was what i gonna suggest
that it keeps track of total seconds spent in the vc and when user leaves the vc it then allocates the point or allocates em at a fix time like after every hour or day
yes
ah k
but can anyone help me with slash commands in discord.py i dont understand how they work
examples ^
ah k
Looking for feedback
https://discord.com/channels/267624335836053506/1148617310022668308
blud was using pep 9001 style guide
Never looked at it in my life
Python Enhancement Proposals (PEPs)
It's always been popular
Looks like all the examples I learned from lol
I think it's simply the oldest one with the most people using it
AFAIK they all accomplish the same, just personal preference
the only reason discord.py is seen as "main" library for discord bots is cause other popular libs are forks of it
nextcord/__init__.py lines 7 to 8
:copyright: (c) 2015-2021 Rapptz
:copyright: (c) 2021-present Nextcord Developers```
`disnake/__init__.py` line 8
```py
:copyright: (c) 2015-2021 Rapptz, 2021-present Disnake Development```
`discord/__init__.py` line 7
```py
:copyright: (c) 2015-2021 Rapptz & (c) 2021-present Pycord Development```
The spaces portion in this cracks me up
There isn’t a single programmer alive at this point who isn’t using an ultra-wide monitor. To accommodate these extremely wide monitors, all lines must now be at least 120 characters long, and no longer than 240 characters.
simple as that
im also fan of unimport keyword
Also like 90% of the formatting in that was courtesy of vscode
Running my stuff in a vm so I had that terminal running alongside vscode and retyped it
For some reason and I am not lying it doesn't delete the message 💀
Can someone share a simple code for discord bot using cogs in it
From the fact it says "Unknown message" i believe it does
Also it can't just don't delete without any errors and continue executing
The docs already has that
import discord
from discord.ext import commands
bot = commands.Bot('.', intents=discord.Intents.default())
class Cog(commands.Cog): ...
@bot.event
async def setup_hook():
await bot.add_cog(Cog())
bot.run(TOKEN)
well, they explain cogs and extensions separately which makes it a bit confusing on how they're combined in conventional code
yea
almost bare minimum of cogs+extensions: ```py
cogs/my_cog.py
class MyCog(commands.Cog):
def init(self, bot):
self.bot = bot
async def setup(bot):
await bot.add_cog(MyCog(bot)) py
main.py
bot = commands.Bot(...)
@bot.event
async def setup_hook():
await bot.load_extension("cogs.my_cog")
bot.run(...)```
thanks
thanks
in simple terms Cog is a class that is a subclass of commands.Cog class while extension is a file that contains setup function in it
I just needed help on how to load up the cogs and stuff some codes doesn't even use the asyncio functionality so it was a bit confusing.
Extension 'cogs.greetings' raised an error: TypeError: object NoneType can't be used in 'await' expression
I'm getting this error now when loading up the bot
You did ```py
await None
somewhere it seems
show code
usually means you forgot to add async in front of def setup():
this is the main file
it's not here
it's in the link
The error is inside the cogs.greetings
what's in that file

guessed :p
and add_cog should be awaited
ok brother tysm
Did you interaction.response
why that ??
You actually need to respond to interactions
Slash commands always should be responded in some way. You didn't respond anything
If you don't respond to an interaction it'll fail. Or you can defer the interaction
Ye, all interactions, not just commands
like that ? 😅
Maybe
What library is that
pycord
I'm not familiar with that one
but as i know it doesn't require any response ://
Interactions require responses
Any interaction reqiures response
Command, button, user command, anything
ok but how in that case ??
Ye, it has respond method so that should work
huh
It looks like you're never actually sending the enable/disable for the user to click
Or you send disable and there you don't have some response
nah i selected enable :/
Oh
no that's why i'm confused 😅
Then it's failing somewhere before your print
Everything else is fixed however, when it comes to handle_accept_application, the bot doesn't add roles or change their nickname correctly.
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.
And you don't have any errors?
no error occurs dude
Do you have error handlers?
Things like raidmode.error, cog_command_error, on_application_command_error
idk then
pycord dark magic
Take out the "enable/disable" in your discord.Option and go straight to choices
pycords slash command implementation makes me want to burn my computer
Pycord docs don't show that bit In the examples
It also shows this instead of just ctx
ctx: discord.ApplicationContext
bruh wtf i removed the choices to make the user able to type but it still require to select a choice
i restarted discord but the problem still the same 💀
bot.slash_command(name="animal")
async def animal_command(
ctx: discord.ApplicationContext,
animal_type: discord.Option(str, choices=['Marine', 'Land']),
animal: discord.Option(str, autocomplete=discord.utils.basic_autocomplete(get_animal_types))
):
await ctx.respond(f'You picked an animal type of `{animal_type}` that led you to pick `{animal}`!')```
This is the example from the documents. It should looks similar
discord.Option has it. It's description https://docs.pycord.dev/en/stable/api/application_commands.html#discord.Option
Command Permission Decorators: Commands: Shortcut Decorators: Objects: Attributes full_parent_name, qualified_id, qualified_name. Methods@ after_invoke,@ before_invoke,@ error, def get_cooldown_ret...
but i think there is a certain problem because the script is different to what the bot executes idk
Bot only does what you tell it to
i removed the choices but the bot still give choices
i mean there is a bug with the api or idk
i'm confused rn
So you changed it to choice : str
yup
It's giving you options because options are still there lol if you want to type, make it choice : str
Instead of discord.Option(xxxx)
huh dude i always use this syntax for choices or not and it's working
Or maybe discord.Option(str)? Idk pycord is beyond me. I'm just trying to absorb info from the docs rn
@bot.event
async def on_ready():
print(f'Logged in as {bot.user.name} with the ID of {bot.user.id}')
presence_list = ["1", "2", "3"]
async def change_presence():
while True:
presence = random.choice(presence_list)
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name=presence))
await asyncio.sleep(10)
bot.loop.create_task(change_presence())
await bot.change_presence(status=discord.Status.idle)
bot isn't going on idle, any ideas?
I guess what he has is already correct. Only with choices arg it will give choices
I guess you just immediatly change it to listening
to online*
pycord voodoo. I gotta head out anyways
idrk what to do though
i mean i know its probably cause of the loop but where else can i place it
aren't going to make a command for it lol
pass status in the change_presence inside the loop
In one change
In first you set status to idle
and in second you set it back to online
because it's the default one
so i should set it after?
yeah i just did that i gotta wait for bot to update
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name=presence), status=discord.Status.idle)
still not changing i think
nope
should work
did you keep some other change_presence?
@bot.event
async def on_ready():
print(f'Logged in as {bot.user.name} with the ID of {bot.user.id}')
presence_list = ["ds", "d", "s"]
async def change_presence():
while True:
presence = random.choice(presence_list)
await bot.change_presence(status=discord.Status.idle)
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name=presence), status=discord.Status.idle)
await asyncio.sleep(10)
bot.loop.create_task(change_presence())
thats all i have to do with change presence but i'll check
yeah it is
oh crap it just changed
i guess the one function call did work, just had to wait for it to update
only issue is now, if i ever want to change the status in some command for whatever reason i wont really be able to but thanks
You can, just put that code into a command and take some input on what to change it to
true
Don't do shit in on_ready
If you want something to be looped infinite create a task
ModuleNotFoundError: No module named 'discord'
Are you using a venv?
I don't know
Did you create one?
pycord?
@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).
oh alr
Using discord.py is it possible to have embeds with integrated buttons? Using a server invite as an example, but I'm not trying to mimic its design to be clear, I just want the embed to have the button in the box with it rather than below
nope you cant
Damn thats unfortunate, thanks for the response 
I can totally imagine the new scams that would pop up if that was possible
fr
Does anyone have any examples on how to create dropdown menus?
Also, this might be a longshot but does dpy have a converter to convert a countries name to it's flag?
no
that is completely out of scope
true enough
I have an example with disnake iirc it should be exactly the same as discord.py
One sec
Will emojis work in embed titles?
Double check the discord.py repo examples though they might have something
Might only be Unicode emojis that work
yeah it is the same
||i PR'd the dropdown example
||
lol nice
now I gotta paginate this embed
I plan on doing a drop down menu example next for the #1051603408597024828 section
Covered modals pretty well imo
And yes you can most definitely have emoji in embed titles. Footers don't allow anything fun though
i have this embed pinned in my dev server whenever i forget
drop downs are pretty easy
Yea I'm probably going to mix it in with a giveaway bot that doesn't require a database and has weighted entries based on roles
How are you going to create a giveaway bot without a database?
Already done
How are you storing the data
i did a similar thing with your guide too when i was writing my quiz system, except i used the message content to present a single question and then gave either a select menu or a modal with a single input to receive the answer
The one I currently have made is just a reaction count, but the updated version will use buttons and store the users in the embed
Probably have a dict or something idk. I'll figure it out
What if the code restarts?
Shouldn't randomly restart, but that's why I currently have it set to look at reactions after a timer. And I made a reroll command that will check the message as well
:incoming_envelope: :ok_hand: applied timeout to @upbeat mason until <t:1693956098:f> (10 minutes) (reason: newlines spam - sent 101 newlines).
The <@&831776746206265384> have been alerted for review.
trash bot

!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.
Guys on the Internet it tells me I can get a Reaction emoji with reaction.emoji but It keeps saying "tuple has no attribute emoji"
On a reacted message
reaction, user = await bot.wait_for("reaction_add", check=check)
await ctx.send(reaction)
if str(reaction.emoji) == "➕":
Thats when it Just stops and gives me this error
(<Reaction emoji='heavy_plus_sign' me=True count=2>, <Member id=1017915595083231283 name='heromaex' global_name='heromaex' bot=False nick=None guild=<Guild id=1148733192510128188 name="heromaex's server" shard_id=0 chunked=True member_count=3>>) Is what it gives me
Ok wow now that I have it in plain sight it makes sense
Thanks haha, solved it
How do I disable a dropdown menu after a certain amount of time?
Or, would it be better just to sleep the command, then remove it entirely
is it based on the view timeout or just an arbitrary time?
if its the former, you can store your message/interaction in the view and edit it during on_timeout()
Arbitrary I guess
I don't want the resource use I guess
How long is the timeout?
its however long you want it to be
Also, how would I update the embed when the user selects an option in the dropdown?
discord.InteractionResponse.edit_message?
yup
the Select.values attribute will give you a list of the option values chosen
I see that
Also, one of the options should edit the embed back to it's original state, how would I get the original message?
Should I take it as a value in the __init__, and pass it when I initialize the class in the command
Or is there a method/attr that returns the original message
passing the embed at the start sounds reasonable
u can get the interaction response but if it has been edited it wont give the original
Yeah I'll just pass it then
u can store the original message as an attribute
^ though dpy doesnt really document which message objects are cached (which will change with edit events)
@hushed galleon have a favor to ask real quick if you wanna check your dm
err id rather just answer questions here
yea i get that, i honestly just dont know wtf im doing and theres passwords and information stuff in my code and im pingponging between the code and chatgpt to try to fix it, im just trying to figure out why its not posting to discord
i can tell you rate limits, webhooks, and proxies are fine. and any ai is like no youre good should be posting
This seem reasonable enough?
class ShippingLineDropdown(discord.ui.Select):
def __init__(self, sorted_lines: dict[str, list[float, float]], original_embed: discord.Embed) -> None:
self.original_embed = original_embed
options = [discord.SelectOption(label="All Lines")]
for value in sorted_lines.keys():
options.append(discord.SelectOption(label=value))
super().__init__(placeholder="Select a shipping line for more information", options=options)
async def callback(self, interaction: discord.Interaction) -> None:
if self.values[0] == "All Lines":
await interaction.response.edit_message(embed=self.original_embed)
else:
await interaction.response.send_message(f"Placeholder")
dis be pissing me off fr
My whole code is kinda cursed
Before I release for beta testing I'm going to move everything into cogs and utils files
Everything is in 1 file rn
yeah that looks about right
How do i do options on slash command discordpy? Can someone show me an example
dropdown or choices?
i will assume args options
but you are going to have to explain which one you want. dropdowns/selects, or arg choices
Hello, so i am not rally good with pagination and stuff... and i found this on the pip website:
https://pypi.org/project/discord.py-pagination/
would i be dum to use this or not?
No documentation found for the requested symbol.
!pypi reactionmenu
A library to create a discord.py 2.0+ paginator. Supports pagination with buttons, reactions, and category selection using selects.
😮
@wispy pasture ^^
thanks
just a quick question.... is this still valid:
https://gist.github.com/InterStella0/454cc51e05e60e63b81ea2e8490ef140
A walkthrough on action based pagination in discord.py - Pagination_walkthrough.md
discord-ext-menus exists
yeah this tutorial is for that
yep
discord-ext-menus u can use it
oh yes and that's what i primary use
i just make my own
works with buttons as well. although you just have to create a paginator view
https://pypi.org/project/discord-ext-menus/
there is no desc regarding on how to use it?
i have my view subclassed
https://github.com/Rapptz/RoboDanny/blob/rewrite/cogs/utils/paginator.py
R. Danny has a good example
for a bunch of custom utilities
it's not on pypi
i've been meaning to track down the owner of the pypi package (i did) and don't know much info about him
danny probably knows more
oof i am really hungry 10 more mins for class to get over 😔
anyways you'll have to install from git
np
its danny no?
no
Danny's account should be Rapptz
Rexum leads to an old friend of Danny
ok yeah
Hi, for a few days now I've been getting this error even though I haven't changed my code. Do you know why?
discord.app_commands.errors.CommandInvokeError: Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
For example if you are trying to respond to interaction when it's already expired
async def foo(interaction):
await asyncio.sleep(5)
await interaction.response.send_message('123')
would give this error
show code
when the button works is getting this normal?
try defering it
@app_commands.command(name="minecraft",description="Choose a minecraft server to manage")
async def minecraftserver(self, interaction : discord.Integration):
[code but no discord interaction]
await interaction.response.send_message(embed=embed, view=view) #crash here
...
welp it seems the code within block takes more than 3 sec to execute
You should respond to any interaction. Otherwise discord thinks that it failed
Either respond to it or defer the interaction response
: discord.Integration 
it's Interaction btw
No, because if I replace by await interaction.channel.send(.....) it's instant
Because that's not an interaction response
That's sending a seperate message into the same channel as interaction
You could either move the response earlier or defer it and send it later, it'll just say the bot is thinking for a second before sending the response
!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...
after this you will need to use followup to send the embed
Okay, so I use defer and followup instead and it works but I don't understand why it stopped working when it used to work so well.
You have some code that works different time depending on situation
For example sending requests
yes, ty
alrighty thanks
How do i make a working slash command in discord.py? i found online on "Stack Overflow" a way but it didnt work, can someone help?
My bot command doesn't want to work, this is what comes out:
discord.ext.commands.errors.CommandNotFound: command "generate_licanse" is not found```
And I'm typing the command correctly.
My code is:
characters = string.ascii_letters + string.digits
key = ''.join(random.choice(characters) for _ in range(32))
return key
# Функция за запазване на ключа в базата данни
def save_license_key(key):
conn = sqlite3.connect(db_file)
cursor = conn.cursor()
cursor.execute("INSERT INTO licenses (key) VALUES (?)", (key,))
conn.commit()
conn.close()
# Команда за бота
@bot.command()
async def generate_license(ctx, number: int, role: discord.Role):
if number <= 0:
await ctx.send("Моля, въведете валиден брой ключове (положително число).")
return
for _ in range(number):
key = generate_license_key()
save_license_key(key)
await ctx.send(f"Създаден лицензен ключ: `{key}` за роля {role.mention}.")```
You have generate_license but you are trying to call generate_licanse
And I'm typing the command correctly.
no?
discord.py 2.0+ slash command info and examples. GitHub Gist: instantly share code, notes, and snippets.
Here u go this contains almost all info u need regarding app_commands(slash commands)
thx man!
i did it, i am the best developer in the world
Can someone send me a example of using autocomplete in discordpy please i didnt learn nothing from the doc
interaction.message exists only if interaction was got from message, for example dropdown or button.
so in slash command it is None
doc has the example :/
!d discord.app_commands.autocomplete
@discord.app_commands.autocomplete(**parameters)```
Associates the given parameters with the given autocomplete callback.
Autocomplete is only supported on types that have [`str`](https://docs.python.org/3/library/stdtypes.html#str), [`int`](https://docs.python.org/3/library/functions.html#int), or [`float`](https://docs.python.org/3/library/functions.html#float) values.
[`Checks`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check) are supported, however they must be attached to the autocomplete callback in order to work. Checks attached to the command are ignored when invoking the autocomplete callback.
For more information, see the [`Command.autocomplete()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Command.autocomplete) documentation.
Warning
The choices returned from this coroutine are suggestions. The user may ignore them and input their own value...
Oh ok but i dont understand that explanation
I find use Enums easier
i don't see something about them in dpy docs
how are they used?
i guess you are talking about choices
because it'd be strange to do something dynamic with enums
Aren't they pretty similar to auto complete
autocomplete can change to anything while you are typing the value
and choices are always the same
Hmm i see
I thought they had same functionality
I might need to experiment with them later to get a better understanding
It's pretty simple
current is the current string the user typed in
The function then loops over fruits, and if current is in fruit it returns a value
so this is my code:
https://srcb.in/XrYfydEjM4
and i need to either differ the interaction response or just respond to it... but for some reason i cant figure out how
You already got an answer
You don't know how to respond to an interaction?
What was wrong with the answer you were given
i do know i have done it many times.... but for this part specifically i am confused for some reason
also why are you getting member by string instead of just getting the member?
if you typehint it as Member library will do the work for you
await defer(*, ephemeral=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Defers the interaction based contexts.
This is typically used when the interaction is acknowledged and a secondary action will be done later.
If this isn’t an interaction based context then it does nothing.
wdym?
member: discord.Member
and you will get a Member object or NotFound error
If you typehint member as Member discord.py will automatically convert it
- in slash command you will get a list of members to select or something like that
ie.... okay yeah thats a approach...
Does someone know how to do this
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...
!d discord.Interaction.edit_original_response
await edit_original_response(*, content=..., embeds=..., embed=..., attachments=..., view=..., allowed_mentions=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the original interaction response message.
This is a lower level interface to [`InteractionMessage.edit()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.edit) in case you do not want to fetch the message and save an HTTP request.
This method is also the only way to edit the original message if the message sent was ephemeral.
It’s been like that for a while
Would it be possible to use this in a select callback?
For editing response - sure
Cool, that solves my problem then
python
Lots of questions about deferring today
Is their any way to upload file to discord bot model?
Hi Can somone help me whit gettign server
@client.command()
@commands.has_any_role("Manager", "Admin som fan", "Mod som tusan")
async def ban(ctx, member : discord.Member, *, reason=None):
if member is None:
return await ctx.send("The provided member could not be found or you forgot to provide one.")
if reason is None:
return await ctx.send("Please provide a reason to ban this user.")
else:
server = client.get_guild(id=1148073800374693908)
channel = server.get_channel(id=1149013490523189359)
await ctx.message.delete()
await member.send(f"{member.mention} You got a Band for **{reason}**. by {ctx.author} in **Rash**")
embed=discord.Embed(title="Ban", description="Member Banned", color=0xff0000)
embed.set_thumbnail(url=member.avatar_url)
embed.add_field(name="User", value=f"{member.mention}", inline=False)
embed.add_field(name="User id", value=f"{member.id}", inline=False)
embed.add_field(name="Reason", value=f"{reason}", inline=False)
embed.add_field(name="Author", Value=f"{ctx.author.mention}")
await channel.send(embed=embed)
await member.ban(reason=reason)
use typing.Literal more easy
!d discord.ext.commands.has_any_role
@discord.ext.commands.has_any_role(*items)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check) that is added that checks if the member invoking the command has **any** of the roles specified. This means that if they have one out of the three roles specified, then this check will return `True`.
Similar to [`has_role()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.has_role), the names or IDs passed in must be exact.
This check raises one of two special exceptions, [`MissingAnyRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingAnyRole) if the user is missing all roles, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage) if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure).
Changed in version 1.1: Raise [`MissingAnyRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingAnyRole) or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage) instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure)
my discord bot gives error at : in this line invalid syntax
if i add @client.event,
everything looks properly indented
if __name__ == "__main__":
It is
!paste
Completed
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.
Paste your code and error to https://paste.pythondiscord.com and link it back here
indentation doesnt look proper
k
ah k in my editor is hard to see unless pasted
what editor is that then
Idk what editor it is bc it should have been throwing warnings about it
The problem is not indentation though
and not gonna lie looks like you are missing few intermediate topics like OOP and decorators
@commands.commands
cause you have random lines like py member = discord.Member or ```py
@client.commands
so i suggest looking up Python OOP learning it then coming back to this project
also prolly worth changing text editor too
maybe the latter is a feature request 😼
not a feature now :/
Feature request:
Make any code work as programmer wants to
thats still not the problem
^ ?
nor that
What's the new error
It would fix at least the syntaxerror
no wait i tested it wrong line 38 was the problem
Getting this error: 'NoneType' object has no attribute 'id'
It is orginating in the bot command: manage inside of the transfer option.
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.
!e None.id
@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 | None.id
004 | AttributeError: 'NoneType' object has no attribute 'id'
you didnt provide full traceback so i cant tell you on what line it happens but somewhere in your code you are trying to access id on None
I would be very interested why you are using the blocking stdlib SQLite library for your bot
Just use asqlite or aiosqlite
No idea how to use them, what is the difference.
!d aiosqlite
No documentation found for the requested symbol.
!pypi aiosqlite
I have an exception put down, would it help if I removed that to get the full traceback?
I will take a look.
yes full traceback will be helpful to locate issue
Okay, I will get that for you
Traceback (most recent call last):
File "C:\Users\kiera\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 235, in wrapped
ret = await coro(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\Users\kiera\Desktop\CDC Discord Bot\CDC-Discord-Bot\main.py", line 505, in manage
await userMsg.remove_roles(currentDivision)
File "C:\Users\kiera\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\member.py", line 1096, in remove_roles
await req(guild_id, user_id, role.id, reason=reason)
^^^^^^^
AttributeError: 'NoneType' object has no attribute 'id'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\kiera\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\kiera\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 1029, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\kiera\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 244, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'id'
It wil be somewhere around those lines as I removed the try statement.
yeah so
this line currentDivision = discord.utils.get(server.roles, name=currentDivisionProcess) returned None (didnt find the role)
and then else you passed it to .remove_roles() method
it tried accessing .id attribute and failed cause its None
also i see you are repeating code a bit here
I know
lines 481 - 492
Just getting the hang of everything still
What’s the best way to implement error handling and logging?
just to give you example how to shorten code ```py
if rAB == "Private":
rAB = "PVT"
elif rAB == "Private First Class":
rAB = "PFC"
elif rAB == "Lance Corporal":
rAB = "LCPL"
elif rAB == "Corporal":
rAB = "CPL"
elif rAB == "Sergeant":
rAB = "SGT"
elif rAB == "Company Sergeant Major":
rAB = "CSGT"
else:
await ctx.author.send("Rank cannot be defined.")
rAB = "OPEN"
can be shorten to this ```py
mapping = {"Private": "PVT", "Private First Class": "PFC", ...}
rAB = mapping.get(rAB)
if not rAB:
await ctx.author.send("Rank cannot be defined.")
rAB = "OPEN"
i guess its easier to expand it further on 👍
Thank you, I’ll keep that in consideration when I am scrubbing it down a bit
sure 👍
someone in here knows much stuff about discord.py and discord rate limits for fetching users
Im fetching every user id excluded its a dm autopinger
What's the purpose of it
A dm autopinger if a keyword is found
You should not make fetch user requests, but instead use the cache
So basically a dm version of highlight
But only to dm the users that have the keyword set I don’t know how to explain
Just why
Tbh that type of stuff is extremely annoying. All bots that just dm and auto ping with no actual purpose are just annoying
I will assume it is a scam
No
And it sounds like a scam
Anyways just use the get_user coros. They always look up the cache, which prevents rate limiting
there are not coros thats the point
Then probably methods
Gl I'm not helping with a sus bot
Sus because you're getting rate limited fetching users
It does the exact same thing though
If you are only needing to ping them and you have the user ID, no need to get/fetch the user object
If someone uses @ everyone but don't have permissions to ping everyone, would a bot detect it as a ping for moderation purposes?
depends on how the bot checks that, if its with the discord-provided mention* fields then no, it wont be detected
https://discord.com/developers/docs/resources/channel#message-object
Interesting
Just saw a raid attempt that wasn't stopped because either their bot didn't detect it or they just don't have anything set up
Can I disable a button based on a custom ID or something?
Trying to set up tic tac toe in discord buttons. Opponent is a minimax, maximin, or random AI algorithm. I can return which space it's selecting but I want to be able to disable that button
then just filter to ur liking
Right now it's set such that I click button 1, sends that position to the ai, ai selects button 5, returns the number 5, and I'd like to disable button 5 before updating the view
So you just want to disable a button once it's been clicked?
No I want to disable a button from a seperate button. I click button 1, gives the AI position 1, the AI makes its decision to pick 5, gives the button back the number 5, I want to disable "btn5" before I send the interaction response in "btn1" so buttons 1 and 5 are both disabled
Am I just going to have to do if x == 5: self.btn5.disabled = True or is there an easier way
Unless I can call a button from a coro?
I guess it doesn't matter I'd still have to check what number it selects 
Can't just insert the number into self.btnX.disabled
How should I go about disabling a select menu after a certain amount of time?
wait how do i make the / commands sync again
timeout iirc
I curated and created a pretty full-featured command for syncing your CommandTree, you can see it here:
arg?
Here is a short example of how to use discord.py's slash commands as well as general information on them:
https://gist.github.com/AbstractUmbra/a9c188797ae194e592efe05fa129c57f
This currently covers free commands and groups at the Bot level, as well as within Cog classes.
It also includes information and gotchas relating to syncing and whatnot.
NOTE: This will be migrating to https://about.abstractumbra.dev/ as soon as I can be bothered to finish it.
My site for random things and stuff. Including a custom pip index and walkthroughs, both for discord.py!
np
you can only respond to an interaction once
via await interaction.edit_original_response()
you effectively have it twice in your code
Alright, so I sort of found a solution to my problem. I made a seperate coro I can call from inside one button to disable whatever one the ai picks. However, I can't call that coro from inside the init of the button view. So if the ai makes the first move I can't call that to disable the button when the view is sent
Disregard, view children is the answer to all my problems.
Give button a custom id and then do
for child in self.children:
if child.custom_id == f"button_{i}":
child.disabled = True
break
Or could make a list and access the button by index
self.buttons[i].disabled = True
or ```py
getattr(self, f"btn{X}")
I got it working with just self.children[x-1].disabled = True
how do we send a local image as a embed thumbnail? in discord.py*
I tried this:
embed = discord.Embed(title="Item Info",
description=f"Query: {item_name}",
color=discord.Color.green())
embed.add_field(name="Name", value=Item_Name)
embed.add_field(name="Display_Name", value=display_name)
embed.add_field(name="StackSize", value=stackSize)
file = discord.File(f"data/item/{Item_Name}.png")
embed.set_thumbnail(url=f"attachment:data/item/{Item_Name}.png")```
:o
yes, but i dont get it, why we have to send the file as file
because how will discord know what is that attachment if it doesn't exist in discord
embed = discord.Embed(title="Item Info",
description=f"Query: {item_name}",
color=discord.Color.green())
embed.add_field(name="Name", value=Item_Name, inline=False)
embed.add_field(name="Display_Name", value=display_name, inline=False)
embed.add_field(name="StackSize", value=stackSize, inline=False)
file = discord.File(f"data/item/{Item_Name}.png")
embed.set_thumbnail(url=f"attachment://data/item/{Item_Name}.png")
await interaction.response.send_message(file=file, embed=embed)``` its not giving any errors but it doesn't show up on the thumbnail
:o
it just sends the image there
Set the filename as the docs says
I am not sure if it gives the same name as filename
Item_Name = "background"
embed = discord.Embed(title="Item Info", color=discord.Color.green())
embed.add_field(name="Name", value=Item_Name, inline=False)
file = discord.File(f"{Item_Name}.jpg", filename="image.jpg")
embed.set_thumbnail(url=f"attachment://image.jpg")
await interaction.response.send_message(file=file, embed=embed)
do slash commands have a default help command like command prefix
nope, not working
why would anyone need help command for slash commands
No. For that just command list exist
as it already shows every commands in the command list
Works on my machine 
whats the lowest size a embed thumbnail can be
if you loop through the commands can you get all of them
because my image is very small
no idea
There's no limit as far as I'm concerned
if people are too lazy to check what commands are available
sure
you can use the sync to get all the synced commands as a list
how
Doesn't it get compressed and resized automatically
sync = await bot.tree.sync()
print(sync)
!d discord.app_commands.CommandTree.walk_commands
for ... in walk_commands(*, guild=None, type=<AppCommandType.chat_input: 1>)```
An iterator that recursively walks through all application commands and child commands from the tree.
ah idk
As far as i know when we upload an image it gets compressed(unless we do open in browser) so i think that might apply to thumbnail too
no like, the image is very small
it sends it as a file attachment and not in thumbnail
are you sending it as a thumbnail?
yes
did you try set_image
Show your code
embed = discord.Embed(title="Item Info",
description=f"Query: {item_name}",
color=discord.Color.green())
embed.add_field(name="Name", value=Item_Name, inline=False)
embed.add_field(name="Display Name", value=display_name, inline=False)
embed.add_field(name="Stack Size", value=stackSize, inline=False)
file = discord.File(f"data/item/{Item_Name}.png", filename="image.png")
embed.set_thumbnail(url=f"attachment://data/item/{Item_Name}.png")
await interaction.response.send_message(file=file, embed=embed)```
Weird it should send it in embed
Remove the file path from the set_thumbnail
Keep just the image's name and extension
embed.set_thumbnail(url=f"attachment://image.png")```
like this?
Yeah try this
Yes
Nope
you can save it and change the size and re export
but that's a lot of work]
It might be possible in future updates
Why would it be
how do you define walk_commands
Tho u can resize the image using other lib like Pillow and then send it but that might cause a bit of a delay
its faster to just save it and crop it urself i think
Yeah that's faster
But I'm talking if u want to retain the original file
It's already defined. It's a method of the command tree
for commands in walk_commands():
NameError: name 'walk_commands' is not defined
It's a method
ok
||he will try to use it on just class now||
so like
and then tree.walk_commands
If you define a new command tree that has no commands attached to it, no
thats how i defined my tree
then yes
bot.tree.walk_commands
why not just get the synced commands through the bot.tree.sync() function, it returns a list of synced commands
he is using just client
oh
you can still get them from sync, but it's harder to save them
what is just client
why not to just get the commands when you need instead of making a global variable with them
does the just mean anything
this is my code:
pinned_messages = {}
@bot.event
async def on_message(message):
if message.pinned:
pinned_messages[message.channel.id] = message
@bot.event
async def on_message_delete(message):
if message.id in pinned_messages:
log_channel = bot.get_channel(COMMAND_LOG_CHANNEL_ID)
if log_channel:
current_date = datetime.datetime.now().strftime("%A, %B %d, %Y")
embed = discord.Embed(
title="Message Unpinned",
description=f"A pinned message in {message.channel.mention} was deleted by {message.author.mention}.",
color=discord.Color.red()
)
embed.set_footer(text=current_date)
await log_channel.send(embed=embed)
@bot.event
async def on_guild_channel_pins_update(channel, last_pin):
if last_pin:
if channel.id in pinned_messages and pinned_messages[channel.id].id != last_pin.id:
log_channel = bot.get_channel(COMMAND_LOG_CHANNEL_ID)
if log_channel:
current_date = datetime.datetime.now().strftime("%A, %B %d, %Y")
embed = discord.Embed(
title="Message Unpinned",
description=f"A pinned message in {channel.mention} was manually unpinned by {last_pin.author.mention}.",
color=discord.Color.red()
)
embed.set_footer(text=current_date)
await log_channel.send(embed=embed)
pinned_messages[channel.id] = last_pin
but when i pin or unpin a message it is not logging anything....
there are discord.Client and discord.ext.commands.Bot
Bot is subclass of client and has some added functionality like pre made slash commands tree and prefix commands
vitness, is that a husky in your pfp
is one better than the other
Is on_guild_channel_pins_update even a real event
!d discord.on_guild_channel_pins_update
discord.on_guild_channel_pins_update(channel, last_pin)```
Called whenever a message is pinned or unpinned from a guild channel.
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.guilds) to be enabled.
Should be a wolf i believe

oh

Add some debug
Check if function is called, if the if channel.id in pinned_messages and pinned_messages[channel.id].id != last_pin.id: works and so on..
I believe your pinned_messages is always empty (because when message is sent it is not pinned)
Also it's weird that your keys in pinned_messages are channel ids and then you are checking if message id is inside there
how do you get the name of the command
await interaction.followup.send(command.name)
```i did this but it didn't work, because of
**unknown webhook **
what's that mean
and how do i fix it
i think that is what causing the issue
should i not use followup
Did you send a response before?
interaction.followup exists only after you sent some response
ye
actually most libraries implement methods that send response if it was not sent and otherwise send followup.. but it seems discord.py doesn't have such as always
yes
or you can make your own send that will check and choose the needed one
!d discord.InteractionResponse.is_done
like
async def my_send(interaction):
if interaction.response.is_done():
interaction.followup.send
else:
interaction.response.send_message
is_done()```
[`bool`](https://docs.python.org/3/library/functions.html#bool): Indicates whether an interaction response has been done before.
An interaction can only be responded to once.
is it because if you run a /command it'll give the response in the same "message" instead of like !command where it'll send the response as a separate message
That’s how slash commands were designed
true
Hi can some one help me to make this unban command but its uset in a diffrent server
@client.command()
async def unban(ctx, Userid:discord.User, *, reason=None):
await ctx.message.delete()
server = client.get_guild(1148073800374693908)
await server.guild.unban(Userid, reason=reason)
await Userid.send(f"Memmber got Unbanned **User**: {Userid.mention} **UserId**: {Userid} **Reason**: {reason} unbanned by: {ctx.author.mention}")
await Userid.send("You got unband on Rash Join her -------------------")
Does anyone know any free websites where I can host my discord bot?
Hello, I was updating a open-sourced discord bot, It asked me to code the intents but as soon I coded the intents, this error is what I got after debugging. Thank you in advance.
!hosting
Using free hosting options like repl.it or Heroku for continuous 24/7 bot hosting is strongly discouraged.
Instead, opt for a virtual private server (VPS) or use your own spare hardware if you'd rather not pay for hosting.
See our Discord Bot Hosting Guide on our website that compares many hosting providers, both free and paid.
You may also use #965291480992321536 to discuss different discord bot hosting options.
Show the actual traceback
this is the console.
I don't know how to make it work actually. That's why i'm here, haha.
the first error says there is no loop that is currently running
and second says that the loop should be awaited
my guess is that you made a sync function for a task
You have to start the task while an event loop is running
If you're not using discord.py or other (if any) forks that have asynchronous extension and cog loading, you'd want to start the tasks in on_ready or similar events
the on_ready event could get called multiple times during the Bot life cycle so it would be better to start tasks in the setup_hook or in other functions where you're sure that gets called only once
so, speaking of this https://github.com/kegri/SurvivalHouseMaster/blob/main/mcstatus_cog.py
there is something like "await asyncio.sleep(15)" on every loop. When I research, there is always something with await thing. I tried adding "loop = asyncio.get_event_loop()" in the beginning of file, no luck there either.
I don't know much, but I don't think must forks have setup_hook
You can just check if the on_ready has been called once anyway
if you subclass the Bot class you can have something similar
calling your custom function in the start function and then doing await super().start()
If not, just use the on_ready 
it's a cog so using cog_load to start the task and cog_unload to stop it is also an option
Forgot those exist 
Pretty sure they have a form of it in one way or another
This is why you shouldn't be using the forks to begin with
Dpy already implements all of the latest features, and in pycord's case, you will have to rewrite your bot anyways, so why not migrate it back to dpy v2
When I run the mute command, the bot is supposed to give the user the role that is saved on the db but when I run the code, everything looks like being good but no roles are given to the user
await ctx.bot.rest.add_role_to_member(user=ctx.author, guild=ctx.guild_id, role=mute_role_id)
await ctx.respond(f"Muted {ctx.options.user.mention}.", flags=hikari.MessageFlag.EPHEMERAL)
await ctx.bot.rest.create_message(log_channel_id, embed=mute_embed)
hikari 
hikari's design decisions are quite questionable
just use timeouts, show the code you use to get mute_role_id
it's just the user's bad code 
you're adding the role to ctx.author, which is the person that used the command instead of the user who was provided in the argument
also guild user and role (in order) are not kwargs, so there's no need to provide them like that
ctx.bot.rest.add_role_to_member(ctx.guild_id, ctx.author.id, mute_role_id) ``` is enough for the callable
Making a command that sends information about a specified crypto currency.
The code was working fine until my editor crashed and now i keep getting the same response.
Code
@bot.tree.command(name='crypto', description='Crypto Currency Information')
@app_commands.describe(coin = 'coin')
async def crypto(ctx:discord.Interaction, coin: str):
# Define the CoinPaprika API URL
url = f'https://api.coinpaprika.com/v1/tickers/{coin.lower()}'
try:
# Fetch data from the CoinPaprika API
response = requests.get(url)
data = response.json()
# Check if the response contains data for the specified cryptocurrency
if 'error' not in data:
coin_name = data['name']
coin_symbol = data['symbol']
price_usd = data['quotes']['USD']['price']
market_cap = data['quotes']['USD']['market_cap']
volume_24h = data['quotes']['USD']['volume_24h']
change_24h = data['quotes']['USD']['percent_change_24h']
# Create an embed to format and display the data
embed = discord.Embed(title=f"{coin_name} ({coin_symbol.upper()})", description=f"Price p\Unit: ${price_usd:.2f}\nMarket Cap: ${market_cap:,.0f}\n24h Volume: ${volume_24h:,.0f}\nP/L (Last 24h): {change_24h:.2f}%", color=discord.Color.brand_red())
embed.set_thumbnail(url=f'https://static.coinpaprika.com/coin/{coin.lower()}/logo.png')
embed.set_footer(text=f'Requested ~ {formatted_datetime}')
# Send the embed as a message
await ctx.response.send_message(embed=embed)
else:
await ctx.response.send_message(f"No data found for {coin.upper()}. Make sure your format is correct and that the coin exists.\nExample: `btc-bitcoin`")
except Exception as e:
await ctx.response.send_message(f"An error occurred: {str(e)}")
Error response
Traceback (most recent call last):
File "C:\Users\jackf\AppData\Local\Programs\Python\Python39\lib\runpy.py", line 197, in _run_module_as_main
return _run_code(code, main_globals, None,
File "C:\Users\jackf\AppData\Local\Programs\Python\Python39\lib\runpy.py", line 87, in _run_code
exec(code, run_globals)
File "c:\Users\jackf\.vscode\extensions\ms-python.python-2023.14.0\pythonFiles\lib\python\debugpy\__main__.py", line 39, in <module>
cli.main()
File "c:\Users\jackf\.vscode\extensions\ms-python.python-2023.14.0\pythonFiles\lib\python\debugpy/..\debugpy\server\cli.py", line 430, in main
run()
File "c:\Users\jackf\.vscode\extensions\ms-python.python-2023.14.0\pythonFiles\lib\python\debugpy/..\debugpy\server\cli.py", line 284, in run_file
runpy.run_path(target, run_name="__main__")
File "c:\Users\jackf\.vscode\extensions\ms-python.python-2023.14.0\pythonFiles\lib\python\debugpy\_vendored\pydevd\_pydevd_bundle\pydevd_runpy.py", line 320, in run_path
code, fname = _get_code_from_file(run_name, path_name)
File "c:\Users\jackf\.vscode\extensions\ms-python.python-2023.14.0\pythonFiles\lib\python\debugpy\_vendored\pydevd\_pydevd_bundle\pydevd_runpy.py", line 294, in _get_code_from_file
code = compile(f.read(), fname, 'exec')
File "C:\Users\jackf\Documents\Crypto Bot\main.py", line 49
embed = discord.Embed(title=f"{coin_name} ({coin_symbol.upper()})", description=f"Price p\Unit: ${price_usd:.2f}\nMarket Cap: ${market_cap:,.0f}\n24h Volume: ${volume_24h:,.0f}\nP/L (Last 24h): {change_24h:.2f}%", color=discord.Color.brand_red())
^
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 7-8: truncated \UXXXXXXXX escape
(The arrow '^' is meant to be pointing at the comma before color)
Just please use aiohttp
bruh
if you put it like that, forks have many things that d.py doesn't have
just because "i don't feel like the library should implement this"
!e
"\U"
your string is invalid - there is no \U character
no idea how it worked before
@buoyant quail :x: Your 3.11 eval job has completed with return code 1.
001 | File "/home/main.py", line 1
002 | "\U"
003 | ^
004 | SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 0-1: truncated \UXXXXXXXX escape
You meant \n there maybe
Any solution?
What library is that?
If it's pycord, then you probably broken you installation. Uninstall all other libraries you have and install it again
If not, then there actually is no such attribute in all other forks as i remember
its discord.ext.commands.Bot unless you are trying to use py-cord
How do I solve it
@buoyant quail @slate swan
are you trying to use pycord??
If it's pycord - install it again. If not, Bot is located in discord.ext.commands and not in just discord. Use the correct one
How do I install it?
🤦
You did it somehow already
pip install -U py-cord
maybe you would need to pip uninstall discord.py or anything else you have that uses name discord
run this script
then run this commands
pip uninstall discord.py
pip install -U py-cord```
so you are using discord.py?
Ig
then uninstall py-cord and install discord.py ..
its discord.ext.commands.Bot
How do I solve that

I am new to this, sorry
discord bot is not a good project to learn python it requires many intermediate topics like OOP, decorators and async/await syntax knowledge so i advice you to learn basics before coming back to it
I kind of know about the stuff
How to code the bot
Just getting stuck on this shit
so you know such topics but you dont know how to install packages?
Correct..
nor you know how to change discord.Bot to discord.ext.commands.Bot?
lol
nor?
used before the second or further of two or more alternatives (the first being introduced by a negative such as ‘neither’ or ‘not’) to indicate that they are each untrue or each do not happen.
"they were neither cheap nor convenient"
2.
used to introduce a further negative statement.
"‘I don't see how.’ ‘Nor do I.’"

copypaste detected 
discord mods
bot = discord.Botbot = discord.ext.commands.Bot
??
that's all that you needed to change
to fix the first error
you will get intents error then
or maybe something else before it
!intents
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.
And what do I do twith these
firstly you need to read this
i need help
so ask the question?
I want to send a file through the discord API using the requests module
files = {'file': ('data.txt', <_io.BufferedReader name='\files\1140884481671188581\data.txt'>)}
requests.post(url, headers=headers, json=data, files=files)
print(files)
print(response.json())
But when I make the http request I get this
{'message': 'The request body contains invalid JSON.', 'code': 50109}
- What's inside data variable
- Why
fileshas a file object representation in it? That line will give just syntax error
!e
files = {'file': ('data.txt', <_io.BufferedReader name='\files\1140884481671188581\data.txt'>)}
The problem is not with the json, the json is valid and if I don't send the file there is no problem
@buoyant quail :x: Your 3.11 eval job has completed with return code 1.
001 | File "/home/main.py", line 1
002 | files = {'file': ('data.txt', <_io.BufferedReader name='\files\1140884481671188581\data.txt'>)}
003 | ^
004 | SyntaxError: invalid syntax
That's what happens when I do print() and the file
thats prolly representation of io.BytesIO
def send_private_message(user_id, message='', embeds=[], files=[]):
url = f"https://discord.com/api/v9/users/@me/channels"
data = {
"recipient_id": user_id
}
response = requests.post(url, headers=headers, json=data)
if response.status_code == 200:
channel_id = response.json().get("id")
url = f"https://discord.com/api/v9/channels/{channel_id}/messages"
data = {
"content":message,
"embeds": embeds,
}
response = requests.post(url, headers=headers, json=data, files=files)
print(files)
print(response.json())
with open(base_path + "data.txt", 'rb') as file:
files = {'file': ('data.txt', file)}
send_private_message(user_id=user_id, files=files)
!e ```py
import io
io.BytesIO()
print(io.BytesIO())
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
<_io.BytesIO object at 0x7fd04f6b4c70>
or maybe no
That's the code
open with wb ig
@slate swan
yeah prolly open return
It's giving me a different error hmm
{'message': 'Invalid Form Body', 'code': 50035, 'errors': {'channel_id': {'_errors': [{'code': 'NUMBER_TYPE_COERCE', 'message': 'Value "{channel_id}" is not snowflake.'}]}}}
i see, because it was replaced with %7B
works fine by me
what
bot sent me the file
mmm
import requests
headers = {
"Authorization": "Bot ..."
}
def send_private_message(user_id, message='', embeds=[], files=[]):
url = f"https://discord.com/api/v9/users/@me/channels"
data = {
"recipient_id": user_id
}
response = requests.post(url, headers=headers, json=data)
if response.status_code == 200:
channel_id = response.json().get("id")
url = f"https://discord.com/api/v9/channels/{channel_id}/messages"
data = {
"content": message,
"embeds": embeds,
}
response = requests.post(url, headers=headers, json=data, files=files)
print(files)
print(response.json())
user_id = 656919778572632094
with open("in.txt", 'rb') as file:
files = {'file': ('in.txt', file)}
send_private_message(user_id=user_id, files=files)
What could be the problem?
I don't really know
I don't use raw requests for discord api and i am not getting an error here
okok
Are you running just that code or you have something more? Maybe something else is breaking it, try just that part
I'm going to try right now
The code works fine...
Had something weird going on earlier. Was messing with some test code on my lunch break and it kept labeling my buttons as a view object, I threw in a print statement and it fixed it. 
I need a list of all discord.Embed colors
I don't know what the valid colours are, I just need a green, or light green
all colors are valid
what do I put for light green?
color=discord.Color()
color = 0x00FF00
can I use that for embed colors?
class discord.Colour(value)```
Represents a Discord role colour. This class is similar to a (red, green, blue) [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple).
There is an alias for this called Color...
import discord
intents = discord.Intents.default()
intents.typing = True
intents.presences = True
intents.members = True
client = discord.Client(intents=intents)
@client.event
async def on_ready():
print(f'Logged in as {client.user.name}')
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('hi '):
await message.channel.send('Hello!')
client.run('token')
my friend made this code, but its not working and im not sure why its not working either
its supposed to respond with Hello! when you say hi
!mc
» message-content-intent
» mcintent
» message_content
» message_content_intent
!mcintent
The Discord gateway only dispatches events you subscribe to, which you can configure by using "intents."
The message content intent is what determines if an app will receive the actual content of newly created messages. Without this intent, discord.py won't be able to detect prefix commands, so prefix commands won't respond.
Privileged intents, such as message content, have to be explicitly enabled from the Discord Developer Portal in addition to being enabled in the code:
intents = discord.Intents.default() # create a default Intents instance
intents.message_content = True # enable message content intents
bot = commands.Bot(command_prefix="!", intents=intents) # actually pass it into the constructor
For more information on intents, see /tag intents. If prefix commands are still not working, see /tag on-message-event.
oh, how would this be implemented into the code?
Try This @undone aurora
import discord
from discord.ext import commands
import asyncio
from discord import Activity, ActivityType
from datetime import datetime
from discord import ActionRow, Button, ButtonStyle
import random
intents = discord.Intents.all()
bot = commands.Bot(command_prefix='!', intents=intents)
# ========== On Ready / Status ==========
@bot.event
async def on_ready():
print(f'[+] Logged Into {bot.user}')
await update_status()
async def update_status():
while not bot.is_closed():
server_count = len(bot.guilds)
await bot.change_presence(activity=discord.Streaming(name="Under Maintainance", url='https://twitch.tv/Vaypt_rz'))
await asyncio.sleep(1)
print(f'[+] Logged Into {bot.user.name}')
bot.start_time = datetime.now()
bot.run('TOKEN HERE')```
this is the code for running a bot, with no commands
read it
@merry cliff why skull?
im not completely sure how to implement it
there's literally a code snippet
isnt there an unspoken rule not to do API stuff in on_ready?
not an unspoken rule
what you mean bru
you do not do api stuff there, use setup_hook
ok
yeah that
!d discord.on_ready
discord.on_ready()```
Called when the client is done preparing the data received from Discord. Usually after login is successful and the [`Client.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.guilds) and co. are filled up.
Warning
This function is not guaranteed to be the first event called. Likewise, this function is **not** guaranteed to only be called once. This library implements reconnection logic and thus will end up calling this event whenever a RESUME request fails.
I don't get what I did wrong in my code
basically on_ready might be rapidly called in quick succession so there is a chance for the bot to be rate limited from API spam
it is recommended to instead use setup_hook
Idk how to use that 💀
and that explains why I get API limited as soon as my bot is ran
while not bot.is_closed(): might be the reason
use tasks
instead of having it in on_ready that looks like something a task loop would do
💀
buttt, I do need help with bot = autoShardedBot
Why do you need that
It's really not important until you're in like 150+ servers
The documentation is pretty straight forward
let me do what I want jeez
in fine now
isn't it literally the same usage as Bot
!d discord.ext.commands.AutoShardedBot
class discord.ext.commands.AutoShardedBot(command_prefix, *, help_command=<default-help-command>, tree_cls=<class 'discord.app_commands.tree.CommandTree'>, description=None, intents, **options)```
This is similar to [`Bot`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot) except that it is inherited from [`discord.AutoShardedClient`](https://discordpy.readthedocs.io/en/latest/api.html#discord.AutoShardedClient) instead.
async with x Asynchronously initialises the bot and automatically cleans.
New in version 2.0.
bot = commands.AutoShardedBot(command_prefix='!', intents=intents, shard_count=5)

