#discord-bots
1 messages · Page 346 of 1
gyus?
you are supposed to typehint them with just str so e.g url: str
hi i was creating a bot and was making a -wheel command where the user spends 20 aces and can win prizes such as 50 aces, 100 aces, 1000 aces or nothing.
i was wondering if the bot could show an actual wheel spinning and the user can see what they won
yes, you can use a GIF.
now, generating such potentially complicated GIF- don't ask me 😅
hey! I've got an error regarding trying to delete a message, as the aforementioned script doesn't work.
await interaction.response.delete_original_response()```
simply does not exist according to VSC
update discord.py in the correct environment
wdym
[your python executable] -m pip install --upgrade discord.py
uhh I can't remember how you get the python executable that VSCode uses, but it should use the default so try py, or python, or python3
vsc's right, delete_original_response() is actually a method of Interaction and not the response
!d discord.Interaction.delete_original_response
await delete_original_response()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Deletes the original interaction response message.
This is a lower level interface to [`InteractionMessage.delete()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.delete) in case you do not want to fetch the message and save an HTTP request.
still didn't work?
did you respond before calling that method?
Yes.
then what error did you get?
@bot.tree.command(name="echo", description="Echoes a message.")
@app_commands.describe(message="The message to echo.")
async def echo(interaction: discord.Interaction, message: str) -> None:
await interaction.response.send_message("failed badly")
await interaction.followup.send(message)
await delete_original_response()
that's the code
er, you have to call it on the interaction object itself
huh
the codeblock shown in this documentation is just a shortened format, they assume you know how to call that method on whatever interaction object you have
could you explain how i would do that tho?
you know how you wrote interaction.response? that syntax means you're retrieving the attribute called "response" from the variable "interaction"
yh
"delete_original_response" is also an attribute of interaction so to access it, you would write interaction.delete_original_response
method 
of course, delete_original_response is a method that won't do anything until you () call and await it
additionally, is there any way for me to make the second message not be a reply? if so, how?
oh, that reply syntax appears because you responded to the interaction with send_message()
await interaction.followup.send(message)```
for this line
i forgot, does the followup have that same appearance or does it look like a regular message?
oh you are referring to that line
the followup
yh it replys to the message i get deleted
so for a /echo command which im using to test, it looks very weird
in that case you have to directly send a message to the channel rather than using the interaction's followup webhook which has that effect
!d discord.Interaction.channel
The channel the interaction was sent from.
Note that due to a Discord limitation, if sent from a DM channel recipient is None.
okay
retrieve the TextChannel from that and then .send() to it, basically the same way as followup.send()
so other than slash commands they are the same?
there are other changes but pycord is a fork of discord.py so most of the things are the same
oh alright
Hey, I have a problem with my discord bot.
I have tried to import this package but it doesn't seem to let me.
from discord.commands import Option
It says that it has been successfully installed, but it is still red underlined.
Could anybody help me with this problem?
cause it doesnt exist
What are you trying to make
perhaps you're referring to @discord.commands.option() which only exists in py-cord?
https://docs.pycord.dev/en/stable/api/application_commands.html#discord.commands.option
Hi, I'm having issues with one of my commands where I'm getting my container info output multiple times in my embed and I'm not sure why. You can find my code at the paste below along with an example entry from the containerslist variable
https://paste.pythondiscord.com/VOEY3FM2IBLHEENJMQS57DPHXI
I'm only getting each container entry once in the file so my duplicted fields in the embed must be cuased by one of my loops
this is probably the loop causing you issues, but its hard to tell what it does because the indentation's missing: py for field in fields: currentembed: discord.Embed = embed.copy() while len(currentembed.fields) < 5: currentembed.add_field(name=field.name, value=field.value, inline=False) embeds.append(currentembed)
personally i'd chunk each field into groups of 5, then create a new embed for each chunk
e.g. py for i in range(0, len(things), 5): chunk = things[i:i + 5] page = embed.copy() for item in chunk: ...
oh that's weird, I have 4 levels of indentation in my ide but the paste site has only put 1 in.
I had a feeling the while might not be the best choice. I think enumerate(things) might be better but I'll give your suggestion a go
im not sure how enumerate() would help here, the purpose is to have range() step in increments of 5 so it produces N chunks of at most 5 items each
oh as a sidenote, if you're using pycord's EmbedField, you can slightly simplify the code by passing it directly to Embed.append_field() instead of add_field()
oh okay thanks, I'll take a look at that
Hey, although this question is not exactly about coding using Discord.py it is related to discord.py documentation.
I want to download the entire documentation https://discordpy.readthedocs.io/ for discord.py as a PDF or whatever into my computer, this way I can easily access it while offline.
How can I accomplish this?
The downloads page on the website has outdated docs from 2017.
dpy's documentation is handled by the sphinx documentation generator so you probably could download the source code, install dpy with the docs extra, and then build the .html docs
github: https://github.com/Rapptz/discord.py/tree/v2.3.2
sphinx quickstart: https://www.sphinx-doc.org/en/master/usage/quickstart.html#running-the-build
their build workflow: https://github.com/Rapptz/discord.py/blob/v2.3.2/.github/workflows/build.yml
i just tried it myself and er, it was a bit of a pain because it would install sphinxcontrib dependencies that weren't compatible with Sphinx 4.4.0 used by dpy (at least when using python 3.11), but upgrading it to 5.3.0 seemed to be sufficient
for what it's worth:
git clone https://github.com/Rapptz/discord.py
cd discord.py
pip install .[docs]
cd docs
./make.bat html
built HTML files will be in /docs/_build/html
definitely worth using a venv given how many dependencies it requires

@pale zenith @hushed galleon Thanks for help, will look into it.
!find on_invite_create
!d discord.on_invite_create
discord.on_invite_create(invite)```
Called when an [`Invite`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Invite) is created. You must have [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels) to receive this.
New in version 1.3.
Note
There is a rare possibility that the [`Invite.guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Invite.guild) and [`Invite.channel`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Invite.channel) attributes will be of [`Object`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Object) rather than the respective models.
This requires [`Intents.invites`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.invites) to be enabled.
@commands.Cog.listener()
async def on_member_update(self, before, after):
if (before.premium_since is None and after.premium_since is not None) or \
(before.premium_since is not None and after.premium_since is not None and after.premium_since > before.premium_since):
server = after.guild
async with self.bot.db_connection.execute(
"SELECT boost_channel_id FROM server_configurations WHERE server_id = ?",
(server.id,)) as cursor:
boost_channel_data = await cursor.fetchone()
if boost_channel_data and boost_channel_data[0]:
boost_channel_id = boost_channel_data[0]
channel = self.bot.get_channel(boost_channel_id)
if channel:
embed = discord.Embed(
title=f"{after.display_name} has boosted the server!",
description=f"Thank you {after.mention} for boosting {server.name}!",
color=config.main_color,
timestamp=discord.utils.utcnow()
)
embed.set_footer(text=config.footer_text, icon_url=self.bot.user.avatar.url)
await channel.send(embed=embed)```
So here is my code for when someone boosts in a server n stuff like that.
Only issue is it detects the first boost, how can I make it detect each boost and add a count of how many boosts this user has done in the server n stuff like that?
You may want to listen for the system message that is sent when someone boosts the guild instead
!d discord.MessageType.premium_guild_subscription
The system message denoting that a member has “nitro boosted” a guild.
Wait... what if the server doesn't have system messages on?
There's no other way that I know of
Well this works with and without system messages on
But Idk how to track when they boost again is the only issue right now lol
The way you are talking about would require system messages to be on, and not all servers do that. So i have no clue how I could keep track unless I store it in a db, which I truly don't wanna do all of that lol
Hey im wondering if its possible to get a display banner? Like the banner that a person has on in the server, not global tho? Kinda like display avatars.
from discord.ext import commands
import discord
intents = discord.Intents.all()
bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())
@bot.event
async def on_ready():
print(f'We have logged in as {bot.user}')
@bot.command()
async def test(ctx):
await ctx.send("Test")
@bot.event
async def on_message(message):
if message.author == bot.user:
return
if "air force" in message.content.lower():
await message.channel.send('Did you mean: Chair Force?')
elif message.content.startswith(";1st_sgtlore"):
await message.channel.send("I can already feel the pushups")
elif message.content.startswith(";mcpolore"):
await message.channel.send("Real")
elif message.content.startswith(";cdrlore"):
await message.channel.send("Most chill NSI in ROTC")
bot.run("BOT_TOKEN")
why isnt this running the test command
i checked everywhere and i cant find out
i typed !title on chat but my bot doesn't respond
well show the code at the line its showing the error
its liune 53 isnt it?
yes but doesnt look like its this file
I got a question, dealing with discord bots what does it mean when you through a error and it say invalid intentions or define intentions
but when I do I do intentions = discord.Intentions.default
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.
yeah I tried that but it kept throwing the same error
maybe because i did intentions = discord.Intentions
then show this error
Exception has occurred: TypeError
Client.init() missing 1 required keyword-only argument: 'intents'
File "C:\Users\jonat\OneDrive\Documents\PythonDiscordBot\bot.py", line 22, in <module>
bot = discord.Client()
^^^^^^^^^^^^^^^^
you need to add intents
its all explained here
can anyone explain whats a token bot?
its what makes the bot yours
(for context, audit logs show that my friend banned ppl from server but when i ask him he says a token bot did it)
you want to know what it is and how it works or rather where it is and how to find it
uhh everything that might help me understand the given scenario
well then this is called self bot, it makes automated actions but on user accounts it is banned on discord to do that
most likely your friend got hacked (clicked something and allowed access to discord on his own)
hmm
alright dude thank you so much for the help
2024-03-17 05:40:39 INFO discord.client logging in using static token
Traceback (most recent call last):
File "c:\Users\jonat\OneDrive\Desktop\Bot\bot.py", line 18, in <module>
client.run(TOKEN)
File "C:\Users\jonat\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\client.py", line 860, in run
asyncio.run(runner())
File "C:\Users\jonat\AppData\Local\Programs\Python\Python312\Lib\asyncio\runners.py", line 194, in run
return runner.run(main)
^^^^^^^^^^^^^^^^
File "C:\Users\jonat\AppData\Local\Programs\Python\Python312\Lib\asyncio\runners.py", line 118, in run
return self._loop.run_until_complete(task)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\jonat\AppData\Local\Programs\Python\Python312\Lib\asyncio\base_events.py", line 685, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "C:\Users\jonat\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\client.py", line 849, in runner
await self.start(token, reconnect=reconnect)
File "C:\Users\jonat\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\client.py", line 777, in start
await self.login(token)
File "C:\Users\jonat\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\client.py", line 609, in login
raise TypeError(f'expected token to be a str, received {token.class.name} instead')
TypeError: expected token to be a str, received NoneType instead
This is a new error I am having
means your TOKEN is a None type
I have RuntimeWarning in https://gl.beaconborn.ru/bacon/discord_bot/-/blob/test/tests/test_lib_Cog.py?ref_type=heads#L8
After run pytest returns all passed but one warn
tests/test_lib_Cog.py::test_cog_list
/usr/local/lib/python3.12/asyncio/base_events.py:710: RuntimeWarning: coroutine 'InteractionBotBase._delayed_command_sync' was never awaited
self._ready.clear() ```
Why am I getting this error? It's all up to date
you need to await the method its telling you to
Run python -m pip show discord.py
make sure you installed latest version on python 3.10
Hey! May someone explain as to how I can send a message to a specfic channel using / commands with discord.py
get/fetch channel using bot.get_channel(id) / await bot.fetch_channel(id) and then use .send() method on it
Okay!
how exactly do i send it?
the get/fetch method returns a channel object on which you can use .send method
sorry, i think i am more confusing then i thought. what is this line of code exactly to send it, since I assume its await interaction.smth.send() but what do i put so i goes to the specfic channel
interaction.send is used to reply to an interaction, not to send a message to a specific channel
how do i send a message to a specfic channel, i have the ID but how do i send it to a channel
Do you eventually have pycord or something else like that installed, consider removing them
didnt i already tell you
They use the same import name as discord.py and may interfere
no, you told me how to get the channel ID, I'm confused on exactly how I need to send it to said channel ID
Some strange, that I don’t call IntegrationBotBase in this function
And code of lib
https://gl.beaconborn.ru/bacon/discord_bot/-/blob/test/lib/CogsPrep.py?ref_type=heads#L16
In the working bot I don’t see this warn
Sure
either you talked with someone else or idk cause i never told you how to get channel id
but i said this #discord-bots message
why is cog_list async?
First try to base understand how it works, but forget change back
Interesting, this warn was from another test (test_work_with_cogs)
But why shows in test_cog_list
Noticed just now
!Unindent does not match any outer indentation level
show output of python -m pip list
Package Version
aiohttp 3.9.3
aiosignal 1.3.1
asttokens 2.4.1
attrs 23.2.0
blinker 1.7.0
click 8.1.7
colorama 0.4.6
comm 0.2.1
comtypes 1.2.1
debugpy 1.8.1
decorator 5.1.1
discord 2.3.2
discord.py 2.4.0a4993+g56916f92
executing 2.0.1
Flask 3.0.1
frozenlist 1.4.1
idna 3.6
ipykernel 6.29.3
ipython 8.22.1
itsdangerous 2.1.2
jedi 0.19.1
Jinja2 3.1.3
jupyter_client 8.6.0
jupyter_core 5.7.1
MarkupSafe 2.1.4
matplotlib-inline 0.1.6
MouseInfo 0.1.3
multidict 6.0.5
nest-asyncio 1.6.0
packaging 23.2
parso 0.8.3
pip 24.0
platformdirs 4.2.0
prompt-toolkit 3.0.43
psutil 5.9.8
pure-eval 0.2.2
PyAutoGUI 0.9.54
pyfiglet 1.0.2
PyGetWindow 0.0.9
Pygments 2.17.2
PyMsgBox 1.0.9
pyperclip 1.8.2
pypiwin32 223
PyRect 0.2.0
PyScreeze 0.1.30
python-dateutil 2.9.0.post0
pyttsx3 2.90
pytweening 1.0.7
pywin32 306
pyzmq 25.1.2
six 1.16.0
stack-data 0.6.3
tornado 6.4
traitlets 5.14.1
wcwidth 0.2.13
Werkzeug 3.0.1
yarl 1.9.4]
uninstall discord
- its
pip uninstall - i said uninstall discord not discord.py
ok
done bro
next
try running it
tryed bro not running
\python codes\discord.py
your file name is conflicting with the discord library. It's trying to import from your file named discord.py, not the discord.py module.
rename your file to something else like main.py then rerun.
!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.
I want to add pagination to this embed I made (its a shop) does anyone have a good video on that? I couldn't find a good one to implement into my code
!pypi reactionmenu
A library to create a discord.py 2.0+ paginator. Supports pagination with buttons, reactions, and category selection using selects.
Released on <t:1701269523:D>.
its good for beginners ig
if you want to DIY it, i would suggest creating a view that takes a list of items you want to format, then keep track of the current page number which the user can change via buttons, and use the page number to determine which items you'll present to the user
async def ping(interaction: discord.Interaction):
await interaction.response.send_message(f"Pong {interaction.user.mention}")```
the slash command i have created does not show up, what can i do about it is there a solution for this?
have you synced your commands to discord?
if so, restarting your discord client should fix it
how to do that may i ask 😭
!d discord.app_commands.CommandTree.sync
await sync(*, guild=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Syncs the application commands to Discord.
This also runs the translator to get the translated strings necessary for feeding back into Discord.
This must be called for the application commands to show up.
the simplest you can do is add a setup hook to sync your commands when the bot first starts: py @bot.event async def setup_hook(): await bot.tree.sync() but if you want more control over it (particularly if you're hot-reloading new slash commands with the cogs/extensions system), you could also write a prefix command to do it instead
im sorry but i did not understand what am i supposed to do with that code
do you know how to define event handlers? they look similar to @bot.tree.command(), just that they are called based on what you named the function, for example on_ready gets run when discord finishes sending all the guild information to your bot:
https://github.com/Rapptz/discord.py/blob/v2.3.2/examples/basic_bot.py#L19-L22
examples/basic_bot.py lines 19 to 22
@bot.event
async def on_ready():
print(f'Logged in as {bot.user} (ID: {bot.user.id})')
print('------')```
(technically setup_hook isn't a normal event, but in this case the syntax works the same)
you mean @bot.event by event handler right
yes
how do i send a message to a specific channel btw? if anyone knows?
await channel.send(f"message")```
nps 🙂
is channel = channel id
since the bot's for a specific server so
put the channel id that you want the bot send message to there
async def setup_hook():
await bot.tree.sync()```
so should i do this
yep okay ty
it doesn't seem to be working
or maybe im dumb and have done it wrong, hold up
do you get an error
or is it just not working
lemme test rq
i want to make a discord bot that pulls data from a google sheet and imports the requested data into an embed, for example i do the command /gpu amd radeon rx 6800 and it comes back with an embed stating all the data on that specific gpu, any ideas?
.
better to use a proper db like postgresql or sqlite if its a small amount of data using gsheets as a db source goes againt google policy iirc
it's not small
it's a massive data set, it has every gpu made in it with all of their information
and how many gpus is that?
i'm guessing google still wouldn't like that
thousands
sqlite can easily handle hundreds of thousands
thousands is nothing in coding world terms
sizeable dbs contains millions to billions of records
ah okay
how would i put a csv file into sqlite?
i downloaded the csv file off of a reddit thread and scanned it on virus total
it seems to be safe
u could write a script to insert the data into ur db i suppose or there could already be some method for that lemme check
yeah u can just write a bunch of insert queries and execute them here u go https://vikborges.com/articles/simple-way-to-update-a-sqlite-database-table-from-a-csv-file-using-pandas/
Pandas.DataFrame.to_sql allows us to create tables into our sqlite database, tables can be newly created, appended, or overwritten. If we want to append data though, the function won’t handle duplicate items when adding new rows by default.
In order to update the tables without overwriting previous data and only adding new rows, we can use a mid...
thanks
Hey! How would I find the user of the command then reference i later?
I think it's ctx.author, e.g.
async def foo(ctx)
await ctx.respond(f"{ctx.author.name} used the `foo` command)
In a / command?
Since I don't use the ctx part with / commands anymore.
I think you have to have some kind of ctx, maybe it's interaction in this case but whatever your first arg is will be your ctx
poss interaction
What does the command definition look like?
idk what you mean now
Like the async def, what does yours say?
interaction
Okay checked the docs, its interaction.user.name.
ty
The user or member that sent the interaction.
just take whichever attribute u need from here
Does the docs command support pycords docs?
Doubt as it uses the same import as discord.py
!d discord.on_guild_join
discord.on_guild_join(guild)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild) is either created by the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) or when the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) joins a guild.
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.guilds) to be enabled.
discord.on_guild_join(guild)```
Called when a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild) is either created by the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) or when the [`Client`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client) joins a guild.
This requires [`Intents.guilds`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.guilds) to be enabled.
Honestly, anything was fine for that as it was simply for logging lol.
what is the best way to let user to add/remove a logging chanel, do i use a list for that or is there a better way
a table or relation sounds nice u could have a database for that
thanks
how do i check is a user has x role
has_role = member.get_role(role_id) is not None
could you give more info? I'm still just as confused
!d discord.Member.get_role
get_role(role_id, /)```
Returns a role with the given ID from roles which the member has.
New in version 2.0.
im not sure what is it that you're confused lol
how do i check if the user of the command has it?
prefix command or slash command?
slash
is it to only allow certain role to use the slash command?
yh
!d discord.app_commands.checks.has_role
@discord.app_commands.checks.has_role(item, /)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check) that is added that checks if the member invoking the command has the role specified via the name or ID specified.
If a string is specified, you must give the exact name of the role, including caps and spelling.
If an integer is specified, you must give the exact snowflake ID of the role.
This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.MissingRole) if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.NoPrivateMessage) if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure).
New in version 2.0...
just do ```py
@app_commands.command()
@app_commands.checks.has_role(role id here)
async def my_command(...):
Ok so free for use discord bot idea, just gimme credit. A PYTHON IDE IN DISCORD. Type your code in and it will run it.
Probably won't work with gui stuff tho
There's already one
!e
code
!eval [python_version] <code, ...>
Can also use: e
Run Python code and get the results.
This command supports multiple lines of code, including formatted code blocks. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.
The starting working directory /home, is a writeable temporary file system. Files created, excluding names with leading underscores, will be uploaded in the response.
If multiple codeblocks are in a message, all of them will be joined and evaluated, ignoring the text outside them.
Currently only 3.12 version is supported.
We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!
this command is almost an ide itself
I will definitely give you credit for a feature I implemented in my both verified bots thanks for idea
that's like saying to NASA: hey go on Mars but give me credit because the idea was mine
mfw ideas can’t be “pay for use”
nor be restricted/controlled
anyways I had that idea before so plz credit me thanks
i will be implementing this idea, however note that i will NOT be crediting you
they call me the law unabiding citizen
that's called a compiler buddy and there are already tons of bots that implement this in a variety of languages since ages
Anyone know why a discord bot would go offline randomly after a little while? And this happens regardless of being it being local hosted or on a VPS.
Not without an error
- how long is "a little while"?
- do you have logging enabled?
When I use a ctx.reply(msg, mention_author=False) in a hybrid command, in the prefixed one the command doesn't mention the author
But in the app command, the author is mentioned (what don't happen when I use ctx.send/interaction
response.send_message)
Is there a way to make neither one to mention the author?
There's no such thing as "reply" in a slash command invocation. The concept of mention_author doesn't really apply to them
or you mean to want to remove this portion of the command? https://it-looks-like-you.have-no-bra.in/C82BRA.png
well after idk 10-20mins it will go offline, I have a thing that makes it send a Im alive message in a channel just in case it doesn't like idling and it still sends even after the bot goes offline.
just then commands don;t work
I've got something I can try Ill see if it changes anything
where are you hosting your bot?
what is your bot's full code?
class MyButton(discord.ui.Button):
def __init__(self):
super().__init__(style=discord.ButtonStyle.green, label="Hi")
async def callback(self, interaction: discord.Interaction):
await interaction.response.send_message("Hi!", ephemeral=True)
@commands.command()
async def button(self, ctx):
view = discord.ui.View()
view.add_item(MyButton())
await ctx.send("Click!", view=view)```
Im trying to make a button however it isnt working, pycharm is showing that the class MyButton doesnt exist and response doesnt have "send_message" when im calling it in the command. When I run the command on discord there are no errors
but it doesnt work either
Are you defining the button class in a cog class? If so, you aren't supposed to do that
(also, consider subclassing discord.ui.View instead; it'd make your life easier)
You may have noticed that when doing arithmetic with floats in Python you sometimes get strange results, like this:
>>> 0.1 + 0.2
0.30000000000000004
Why this happens
Internally your computer stores floats as binary fractions. Many decimal values cannot be stored as exact binary fractions, which means an approximation has to be used.
How you can avoid this
You can use math.isclose to check if two floats are close, or to get an exact decimal representation, you can use the decimal or fractions module. Here are some examples:
>>> math.isclose(0.1 + 0.2, 0.3)
True
>>> decimal.Decimal('0.1') + decimal.Decimal('0.2')
Decimal('0.3')
Note that with decimal.Decimal we enter the number we want as a string so we don't pass on the imprecision from the float.
For more details on why this happens check out this page in the python docs or this Computerphile video.
If you have installed Python but forgot to check the Add Python to PATH option during the installation, you may still be able to access your installation with ease.
If you did not uncheck the option to install the py launcher, then you'll instead have a py command which can be used in the same way. If you want to be able to access your Python installation via the python command, then your best option is to re-install Python (remembering to tick the Add Python to PATH checkbox).
You can pass any options to the Python interpreter, e.g. to install the numpy module from PyPI you can run py -3 -m pip install numpy or python -m pip install numpy.
You can also access different versions of Python using the version flag of the py command, like so:
C:\Users\Username> py -3.7
... Python 3.7 starts ...
C:\Users\Username> py -3.6
... Python 3.6 starts ...
C:\Users\Username> py -2
... Python 2 (any version installed) starts ...
@sour saddle I think you confused this with #bot-commands 😅
this channel is for asking for help creating discord bots
noo, like
yk when you're replying to someone and can choose if your message gonna mention them (that yellow reply message) or not? I just want it to be normal reply in both prefixed and app command, but using the reply in prefixed
But replies aren't a thing in slash commands though
there's no "message" that you can "reply" to
the message is the invocation of the slash command. it is all contained into a single message. One cannot just reply to the message one is sending
like this doesn't conceptually make sense
I think I just confused myself 😭😭😭
sorry
Oo sorry 😨
what object has the attribute guild
this command is in a Cog
i tried so much stuff but it just doesnt work
ctx.guild.role?
ooh
🫶
it didny work
modcomms is the class in the cog
there was another issue which ignored the user
wait nvm
im sorry it was a different issue here
hi
I have got this so far
But when I run it, it says this
Which I don't understand
Ohhh
Ohmygod how did I forget, thank you
I forgot to include the class, beacuse now I am having issues with that
Im following a guide that someonse send cuz all videos really confused me and it said to type it like that so I do not know
u dont need to like that?
Wdym?
If I do it without the class I get this
check ur brackets lol
i really wouldnt recommed discord bots to a beginner u dont seem to have much experience with python i would suggest getting familiar with some basics of python before attemting bots
I have setup like the whole bot already
Made multiple embeds
Excactly like that
And they work, so i thought Id apply the same logic
same issue here as well
u should post code as text really makes it harder if u post as images
!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.
menu.add_page(embed = discord.Embed(
- title='Commands'),
description='Here are all my commands\n \u2063',
color=discord.Colour.pink(),
)
menu.add_page(embed = discord.Embed(
+ title='Commands',
description='Here are all my commands\n \u2063',
color=discord.Colour.pink(),
+ ))
Alr It did work but is now creating all other issues, thank you for your help though ill figure it out I don wanna be more emberassed in this server lol
Okay can someone explain how to use aiosqlite cus i was told it was a good way to store warnings but it's confusing me now
Okay so I have a question, how can I reload only a single cog? I can reload all at once, but I wanna do Unload n load n reload for only 1 cog at a time too. But I use a __init__.py to do all my cogs basically.
So I am just wondering how I can reload a certain cog, I am pretty sure @hushed galleon helped me last time, so maybe they can help again, or someone else can help.
In my setup hook I do await self.load_extension('commands') so it loads all cogs from __init__.py.
If you need access to my source, please let me know and I will just invite you to a github repo.
Picture:
Question, now this might be more related to sql than python but;
I'm trying to make something along the lines of "messages leaderboard" across multiple servers and I'm planning on using SQL for that. Should i store the counter as (guild_id, user_id, message_count) and i would basically fetch results with guild_id(+ user_id if one result) or should i consider other methods for this?
(guild_id, user_id, message_count) are the columns here
maybe go to #❓|how-to-get-help ?

well it would just be a simple answer along the lines of "yes" or "no, consider somethingelsewhichtheywouldnameorexplainidfk" and also this
so i dont see why i shouldnt ask it here
well
right idk database but i think there is many people know it better
are there alternatives youre thinking of?
tables per guild, but thats sound a lot more stupid in my head and since im using sqlite it would an entire different file because bald
You want to store message count per user right?
i want to store how many messages theyve sent in a guild yes
ah per guild as well
hence the guild_id
alright thank you very much
the question here is how are you going to retrieve the data
do you know both the guild and user id beforehand or is one sometimes unavailable?
Hello need help.
C:\Users\HP\Desktop\Discord bot>py bot.py
Traceback (most recent call last):
File "C:\Users\HP\Desktop\Discord bot\bot.py", line 38, in <module>
client = discord.Bot(intents = Intents.all())
^^^^^^^^^^^
AttributeError: module 'discord' has no attribute 'Bot'
Having a issue in running a bot.
guild id would be provided by ctx.guild and user id is either author or user provided
something like SELECT * from MessagesLeaderboard WHERE guild = ? AND user = ? should provide the user data and removing user = ? would give all data for that guild
what if the command is invoked in a dm channel?
@commands.guild_only or something?
that would work
i have it on all commands so thats...
check the documentation https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#bot
Error solved.
the Bot class is imported from discord.ext.commands
new came
Traceback (most recent call last):
File "C:\Users\HP\Desktop\Discord bot\bot.py", line 355, in <module>
client.run(secret["discord_bot_token"])
File "C:\Users\HP\AppData\Roaming\Python\Python312\site-packages\discord\client.py", line 766, in run
return future.result()
^^^^^^^^^^^^^^^
File "C:\Users\HP\AppData\Roaming\Python\Python312\site-packages\discord\client.py", line 745, in runner
await self.start(*args, **kwargs)
File "C:\Users\HP\AppData\Roaming\Python\Python312\site-packages\discord\client.py", line 709, in start
await self.connect(reconnect=reconnect)
File "C:\Users\HP\AppData\Roaming\Python\Python312\site-packages\discord\client.py", line 646, in connect
raise PrivilegedIntentsRequired(exc.shard_id) from None
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
Here you go
Solve it please
youre trying to use intents youre not eligible for or dont have
the error message tells you how to solve it
please read the error
@fair hinge has provided a screenshot of the instructions
Okat fixed.
I came back to my bot crashed with this message being the last one in the log:
[2024-03-13 18:51:07] [DEBUG ] discord.gateway: Received WSMessage(type=<WSMsgType.ERROR: 258>, data=WebSocketError(<WSCloseCode.PROTOCOL_ERROR: 1002>, 'Received fragmented control frame'), extra=None)
Is this a framework issue, discord issue or an issue with my server?
Using discord.py
Probably some network issue
Networks are not reliable 100% of time, so it's okay if a connection drops from time to time
I am self-hosting it on a local computer, so the issue is most likely my internet might have crashed for a bit there?
Hello is there any one
It could be an issue with your internet, with discord's networking, or maybe Discord was just restarting a server before it finished sending you all the data
if it doesn't persist I'd just ignore it
Ah okay. Because the WSCloseCode does seem to indicate that I didn't receive data from Discord, so it would be a discord issue more than a me issue. But that's something at least.
went from this...
to this
it randomly absorbs messages in chat into a text file and randomly spits out a message that it learned
you could probably hack it with some clever escape character nonsense but i mostly trust my friends
I don't think thats true. If its having quotes around it, then you should mainly be fine... I could be wrong tho.
i dont see why that would be an issue unless youre executing the text file. What I’d be more worried about is someone using characters you dont expect that cause your bot to crash
This is an outdated library don't use it anyways
How would you "hack" it if it doesn't accept any input
At least from your description
I forgot it actually saves messages
Wouldn't personally write them to text file, db would still be better imho
Because how would you separate messages in text files? Only via some text. Messages can contain whatever text so yeah they can break the file
Hey, i am running a code from my phone
The bot sometimes goes online, but doesnt log reactions like it should
On pc it worked fine and im using the same code in pydroid
guys, why my database is not working like intended? Like, my bot is not responding and i don't get any traceback
i'm using SQLite here
What's wrong with it? Please be more specific
i have no idea, when i try to execute a command that involves database my bot don't respond
and i get no traceback
before putting my bot to work with SQLite
the commands was working
but now, the new database is not working properly, like, it's like the database querry is not executing and i get no traceback to know the error
and you can see i get no traceback
Can you show the command's code?
nice pfp 
make sure u have an error handler for ur tree its pretty useful for debugging and handling errors especially unknown ones
here
you mean this?
:x: failed to apply.
File "C:\Users\ALEX\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "main.py", line 297, in on_message
await channel.edit(user,overwrites=overwrites)
TypeError: edit() takes 1 positional argument but 2 were given
eroor on middle man bot
while iam adding person
That's Like a crypto scram that we wont help with due to rule 5
Remember to:
Ask your Python question, not if you can ask or if there's an expert who can help.
Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
Explain what you expect to happen and what actually happens.
Having this error.
@slate swan
- you most likely leaked your api key
- KeyError means you are trying to access a key in a dictionary but its not there
Wdym..
!e ```py
d = {"a": 1, "b": 2}
print(d["c"])
@slate swan :x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 2, in <module>
003 | print(d["c"])
004 | ~^^^^^
005 | KeyError: 'c'
..
help me out.
i showed you why you get the error
Where.
there
I didn't got it., I runned the bot, but the other slash commands are not working on.
you try to access thing that is not defined in dictionary
Ah.
Yes it is truth., How can i access it then?
!e
code
!eval [python_version] <code, ...>
Can also use: e
Run Python code and get the results.
This command supports multiple lines of code, including formatted code blocks. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.
The starting working directory /home, is a writeable temporary file system. Files created, excluding names with leading underscores, will be uploaded in the response.
If multiple codeblocks are in a message, all of them will be joined and evaluated, ignoring the text outside them.
Currently only 3.12 version is supported.
We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!
!e w
@slate swan :x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | w
004 | NameError: name 'w' is not defined
!s
the lower part isnt being executed, it should send an error message that i cant be afk twice
bro what extensions u use
what do you mean?
ahhh yes i use vscode ahah thanks
tell extensions
actually i forgot which one, how can i check?
go to ur
i just use newlines \n
Yeah anyone can write multiline message and bot will consider each line as separate message
shrug lmao
if someone has the gall to attempt to break my private joke bot, they're either a close friend and dicking around, or they're an imposter and i will destroy them
Np, as long as it suits your usecase
and if a message is causing an issue i can just delete it myself
now if this were intended to be a PUBLIC bot i would definitely want to trim off the newlines, but i wouldn't dare
someone would teach it slurs, and i don't want to have to deal with making a filter for that
Problem with fetching members I assume
aeyo anyone, any recommendation of a good discord.py CC on yt or a website?
https://fallendeity.github.io/discord.py-masterclass/
Idk what you mean CC but this is a good discord.py guide
A hands-on guide to Discord.py
Hello guys,
I somehow cannot install LibreTranslate.
I am following tutorial from https://www.youtube.com/watch?v=SJ8lNcn4cjE&list=PLx9e6Ldz3n4m5dpRyQnZnTC86ubnib87h&index=2.
I try to use
cd LibreTranslate
pip install -e .```
Clonned properly.
But then displays some Torch dependency missing.
When trying next step from the tutorial:
```python install_models.py```
There is no such file..
Please tell me what am I doing wrong.
If you any need help, join my Discord server SUNNYGANG:
https://discord.gg/FhuwPSNBdj
webdock VPS affiliate link:
https://webdock.io/en?maff=wdaff--156 - Hey guys, today we are checking out LibreTranslate. This is a free and open source project that offers a machine translation api for self hosting.
In this video we will go over downloadin...
unrelated to discord bots, try asking in #1035199133436354600
I did- #1219758756074881147 - closed and i don't know why
And I'm trying to make a Discord bot using this even gave a link to tutorial I follow so how is it not related to discord bots? xD
The problem itself is not a discord bot problem
Is there a way to validate modal input before submitting it in discord.py?
Let's say I have a text input field that should only accept numbers. Far as I know, Discord does not have this type of input, so I was thinking "Well what if I just validated the input before submitting?" but I'm not sure if that's possible either.
No
Use the interaction you get from the on_submit
That's what I thought, but then I tried like this
await interaction.response.send_modal(ErrorModal(error=error_msg, modal=self))
And I got an error message back from discord saying:
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In type: Value must be one of {4, 5, 6, 7, 10}.
class ErrorModal(discord.ui.Modal, title='Error'):
error_msg = ''
modal = None
def __init__(self, error, modal):
self.error_msg = error
self.modal = modal
super().__init__()
message = discord.ui.TextInput(
label='Error Message',
default=error_msg,
style=discord.TextStyle.long
)
async def on_submit(self, interaction: discord.Interaction):
await interaction.response.send_modal(self.modal)
async def on_error(self, interaction: discord.Interaction, error: Exception) -> None:
await interaction.response.send_message('Oops! Something went wrong with an Error Modal.', ephemeral=True)
traceback.print_exception(type(error), error, error.__traceback__)
I have no idea 🫠
sadness
modals cant chain other modals so you'll have to send an intermediary button or something to show the next modal
https://discord.com/developers/docs/interactions/receiving-and-responding#interaction-response-object-interaction-callback-type
How does one use SelectOption from discord.py?
This is what I tried, but that's not valid discord.ui.select.components.SelectOption(
!d discord.SelectOption is how you want to access it
class discord.SelectOption(*, label, value=..., description=None, emoji=None, default=False)```
Represents a select menu’s option.
These can be created by users.
New in version 2.0.
Oh. I see.
create a few of those in a list, then pass them to the discord.ui.Select(options=) parameter
Hmm, I tried that now. It gives me an error about an invalid form.
group_mode = discord.ui.Select(
min_values=1,
max_values=1,
options=[
discord.SelectOption(
label='test',
value='',
description='',
default=True
),
discord.SelectOption(
label='test2',
value='',
description='',
default=False
)
],
disabled=False
)
HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components.4.components.0: Value of field "type" must be one of (4,).
oh, is this for a modal? they only let you use text inputs for it, sadly
did we can't use youtube dl anymore ?
!pypi yt_dlp
Never legally could
Any good
devplover of discord bots python Please dm me i have a big project
Some issues i am facing
u can fix so please dm me
I am very big devplover
Can help you with code review
Ohhhh okay 👍
How does your members look like when you print it
Post your project on github and give me access, I will review it
what is it about
Haha funni 669 commits

who tf uses github in white mode
That's phone
you're the one here who's "weird" with your pathetic stupid shit jokes
why so much hate, perhaps a white mode user
is it possible to add a button/select field inside modals?
2024-03-20 16:34:52 ERROR discord.ext.commands.bot Ignoring exception in command help
Traceback (most recent call last):
File "/home/runner/NaiveExtrasmallSales/.pythonlibs/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/NaiveExtrasmallSales/.pythonlibs/lib/python3.10/site-packages/discord/ext/commands/core.py", line 1021, in invoke
await self.prepare(ctx)
File "/home/runner/NaiveExtrasmallSales/.pythonlibs/lib/python3.10/site-packages/discord/ext/commands/core.py", line 926, in prepare
raise CheckFailure(f'The check functions for command {self.qualified_name} failed.')
discord.ext.commands.errors.CheckFailure: The check functions for command help failed.
2024-03-20 16:34:54 ERROR discord.ext.commands.bot Ignoring exception in command script
any help?
how to install button_panginator
hello, im new to discord bot development,
ive been trying to setup slash commands and was wondering if anyone knew the workaround to having "spaces" in the command name?
tried using unicode invis character but that doesn't work
We know each other, he's just joking around ☺️
Hello! I'm learning to make a discord bot again. I used to make them all the time back in 2020. But stopped for some reason. Anyways, I was wondering what is the best way to organise all my code and commands. Guilty of asking ChatGPT about it but it said cogs and groups? Yet i'm not sure if there is a more up-to date method. If there is any best solution, please tell me haha
hello, i have regex that checks for emojis but due raw messages having unicode instead of the emoji in text form, it doesnt match so how do I match if there is any emojis?
create a regex that matches for every unicode emoji and keep it updated every time unicode releases an update
!pypi emoji
thanks
hi can some1 help
im getting this
discord.ext.commands.errors.CommandOnCooldown: You are on cooldown. Try again in 0.04s```
but i'm literally excepting it
```py
except CommandOnCooldown as e:
await context.send(f"You're on cooldown! Try again in {e.retry_after:.2f} seconds")```
here's the code:
@commands.hybrid_command(name="cat", description="Sends an image of a cat.")
@cooldown(1, 3, BucketType.user)
async def cat(self, context: Context) -> None:
async with aiohttp.ClientSession() as session:
try:
async with session.get("https://some-random-api.com/animal/cat") as resp:
if resp.status == 200:
data = await resp.json()
image_url = data.get("image")
if image_url:
time.sleep(1)
fact = data.get("fact", "No fact available")
embed = discord.Embed(
title=fact
)
embed.set_image(url=image_url)
await context.send(embed=embed)
else:
await context.send("Failed to fetch image.")
except CommandOnCooldown as e:
await context.send(f"You're on cooldown! Try again in {e.retry_after:.2f} seconds")
except Exception as e:
await context.send(f"An error occurred: {e}")```
nope closest u can get is creating subcommands for a group command
yeah cogs and groups are probably the best ways altho methods of declaring and usage has changed over time or past year or so hence chatgpt is not updated syntactically ig
cooldown error gets triggered before u enter the function or command body
what
how do i fix this
oh wait you mean switch try and async with aiohttp.ClientSession() as session:?
u need to define some sort of command specific error handler and reset the command cooldown and invoke the command
switch these i mean
no
ur command is never called in case of cooldown error
its never executing the function
stop talking fancy i just want a fix 😭
i did tell u

i told u to not talk fancy 😔
@cat.error
async def cat_error(ctx, error): # might wanna recheck the function params thats passed i am not sure
if isinstance(error, cooldown):
reset cooldown here
and reinvoke the command
return
raise error
i meant what i said its nothing fancy just discord.py jargon
uhh give me a second
and make sure to reraise the error if not handled in if ❗
discord.py performs checks like cooldown before executing the command if the checks fail the command is not executed and an error is raised
that too btw
!d discord.ext.commands.Command.error
@error```
A decorator that registers a coroutine as a local error handler.
A local error handler is an [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error) event limited to a single command. However, the [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error) is still invoked afterwards as the catch-all.
Changed in version 2.0: `coro` parameter is now positional-only.
@commands.hybrid_command(name="cat", description="Sends an image of a cat.")
@cooldown(1, 3, BucketType.user)
async def cat(self, context: Context) -> None:
async with aiohttp.ClientSession() as session:
try:
async with session.get("https://some-random-api.com/animal/cat") as resp:
if resp.status == 200:
data = await resp.json()
image_url = data.get("image")
if image_url:
time.sleep(1)
fact = data.get("fact", "No fact available")
embed = discord.Embed(
title=fact
)
embed.set_image(url=image_url)
await context.send(embed=embed)
else:
await context.send("Failed to fetch image.")
except Exception as e:
await context.send(f"An error occurred: {e}")
@cat.error
async def cat_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
await ctx.send(f"You're on cooldown! Try again in {error.retry_after:.2f} seconds")
await ctx.command.reset_cooldown(ctx)
await ctx.command.reinvoke(ctx)```
like this?
Who cares let's just ignore it and wonder why command doesn't work (I divided by 0 somewhere) 😈

Indents damn them
vsc doesn't give me an error 🤨
self, ctx, error
Use guard clauses 😭
No
dont think reinvoke is a thing either
No indents syntax error there's just too many of them and it's bad
just call it
Nasty nesting
well my base is bad, so i have to cope w/ it
You sure that command is in cog
!d discord.ext.commands.Context.invoke
await invoke(command, /, *args, **kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Calls a command with the arguments given.
This is useful if you want to just call the callback that a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command) holds internally.
Note
This does not handle converters, checks, cooldowns, pre-invoke, or after-invoke hooks in any matter. It calls the internal callback directly as-if it was a regular function.
You must take care in passing the proper arguments when using this function...
or just call it manually
Ahh alright, thank you
like await cat(ctx)
yes
for some reason this fixed it:
commenting fixed it idk why + i'm not on cooldown after it expired
so i just had to make an error handler
Me when the
me when the
I'm getting 2 errors here.
discord.ext.commands.bot Ignoring exception in command tfr request and
raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: request_details is a required argument that is missing.
And i am purposefully not doing the command correctly so i can do correct error handling
https://pastebin.com/pmP10F5j
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.
anyone know how i can host my bot 24/7?
replit : user keep alive
hereku
pylex
also glitch but I think it's not good anymore
watch tutorials to hide your token
Well i use a raspberry pi rn, in fact im talking on it. So it's pretty good lol
most machine that can run python is able to host your bot, i used my old android phone to host one bot and it works fine
Can someone show me how to make auto mod features inside of discord using my bot?
I can't figure it out properly. Its supposed to make an auto mod rule inside of discord, but I am not understanding it..
!e ```py
l = [1]
print(l[-2])```
@slate swan :x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 3, in <module>
003 | print(l[-2])
004 | ~^^^^
005 | IndexError: list index out of range
Your list does not have enough items
so how can I fix it
Looks Like regex did not match this many elements as you expect
You are trying to Access penultimate element but there is not this many
Any VPS service
#965291480992321536 has some pins
https://www.pythondiscord.com/pages/guides/python-guides/docker-hosting-guide/ guide for actually running it
This guide shows how to host a bot with Docker and GitHub Actions on Ubuntu VPS
Have anyone already learned how to use embedded app SDK?
about this please
Print("hellow world")
guys, please help
I'm not even sure what that thing is supposed to do
I just read their docs and it still doesn't make sense
I'd imagine activities would have some engine
Like WebGL
That count as web development part already?lol
bro
embedded applications is an extension to web applications
any free ones?
bro its server-client communication
anyway
want my help
i supply where there is demand
ya know what i mean
Nah, just curious anyone already learn it after 3d of release
I just remember it's released today
bro it was released a month ago wdym
anyone know any free hosting sites?
It was officially released at March 18
idk the milestones of history but i heard of it months ago bro
Yeah
I know that before it released
And just remember it is actually released 3d ago today
bro im literally doing it
I am learning it
btw why
I'd rather use unity and build it as webgl
hi can someone tell me what i did wrong here its not sending the missing permission message lol
@bot.tree.command(name="start", description="Start bot.")
async def start(ctx):
interaction = ctx
allowed_user_ids = [488172488208023562, 1184953547066978414]
if (interaction.guild.owner_id == interaction.user.id
or interaction.user.id in allowed_user_ids):
global task_lol
await ctx.response.send_message("Starting the bot.")
if not task_lol or task_lol.done():
try:
task_lol = asyncio.create_task(main())
except discord.Forbidden:
await ctx.response.send_message("Error: 403 Forbidden (error code: 50013): Missing Permissions")
else:
await ctx.response.send_message("Only the guild owner can start the bot in this server.")```
does fuction main() raise Forbidden anywhere?
i don't know
maybe who knows
¯_(ツ)_/¯
yes
bro
dont use globals
why not
tell me one reason why i shouldn't use it
i'm not returning everything
i'm used to globals
bro
just use chatgpt
and u get tons of reasons
no
i agree that u shouldn't use globals but if you're suggesting someone something you should have some justification yorself too 😂
In large projects or in collaboration projects it's easy to overwrite a global making behaviour unpredictable and it could be confusing as to where the variable is coming from. Other than that it's perfectly fine.
yeah well i don’t have a large project or a collaboration project
- its a discord bot why shouldnt i use globals
well for starters its still fine to manage under a single filed scope but makes it way harder in sharing across multiple files or places a better way would be to make it an attribute of the bot instance which grants u access to that in all sorts of places like cogs, interactions etc
Your mean cogs?
cogs views etc yeah
how do i make an optional option 💀
the interwebs doesnt help
like in a slash command
In the function assign a default variable.
what
when creating an Checklist, the ID is none, i didnt find any problems in the code, is it normal that the collum is "NULL"?
Hi! I'm using discord.py and trying to setup a basic bot, however, when I try to modify the intents, the code stops running
When I include the lines modifying the intents I get an error, however when I delete them I don't
Although I obviously the bot won't be able to answer messages
intents = discord.Intents.all()
all the ones I've mentioned are free,
try replit , and then pylex, actually i just started using the pylex , idk if it has problems or not, but it hosts without going offline
Thanks
👋
what's the most efficient way to check if the person is the guild owner and if a person matches a certain user id in an array?
such as
allowed_users = [12345678910, 10987654321]
you want to restrict some commands to for example only guild owner / person whos id is in list?
or you just want to check inside a command logic
for example
allowed_user = [762476539664400444]
@bot.commands()
async def allowedTest(ctx):
if allowed_user == True:
await ctx.send('you can use this command ')
else :
await ctx.send('you don't have permissions')
guild owner and a person whos id is in the list inside of a command (or all commands if possible to do it with few lines)
this wont work
it doesn't check the commands author id
i want to completely get rid of ctx and use interaction: discord.Interaction instead
you can create a check
how?
should i make a function for it
ill show you how but is that what you are looking for
and in a command i use it like
@bot.command()
async def hi(interaction: discord.Interaction)
if check_if_list():
pass # will be replaced
else:
pass
no, answer my question
pretty much
A hands-on guide to Discord.py
i don't understand what ur trying to say 💀
this is how to do it
you add a decorator above a command
in the example i sent it is @is_owner()
I just typed the code you can replace the ctx with interactions
def is_owner():
async def predicate(inter: discord.Interaction) -> bool:
return inter.user.id == 1234567890
return app_commands.check(predicate)
the code you sent makes 0 sense
ill look forward to it, thanks!
👍
can i also do it like this?
return inter.user.id == [1234567890, 0987654321]```
if you want to check if user id is inside a list you use in operator
return id in [...]
return inter.user.id in [1234567890, 0987654321]?

it returns a check so when using decorator you dont have to do @app_commands.check(is_owner) you can just do @is_owner()
ownerID = [id]
@bot.command()
async .......
if ctx.author.id in owenerID:
await ctx.send/ intercation # your response
else:
await [send you don't have perms]
@lyric solar
i don't want to use ctx at all, i'm gonna start using interaction: discord.Interaction
no, if the person doesnt match the check it is "rejected" and command is not invoked
it's not a problem just replace it lol
https://fallendeity.github.io/discord.py-masterclass/checks/#checks more about checks here
A hands-on guide to Discord.py
better to read it
and if a person isn't whitelisted, how can i send a message that they're not whitelisted, by this?
def is_owner():
async def predicate(inter: discord.Interaction) -> bool:
return inter.user.id in [123, 321]
return app_commands.check(predicate)```
A hands-on guide to Discord.py
analyse the code and the responses
ask if you dont get it
I think he just wanna copy paste

copy pasting doesnt make him learn
i've never worked with decorators
there're many ways to make checks. you can even create a function by yourself, but you have to read/learn docs
def is_owner():
async def predicate(inter: discord.Interaction) -> bool:
if inter.user.id not in [321, 123]:
await inter.response.send_message("No permission.")
return False
else:
return True
return app_commands.check(predicate)
did i do it right
yeah thats fine, you can even optimise it a bit
how
like this ```py
def is_owner():
async def predicate(inter: discord.Interaction) -> bool:
if inter.user.id not in [321, 123]:
await inter.response.send_message("No permission.")
return False
return True
return app_commands.check(predicate)
but your version will obviously work too
so i can just strip away the else:
since you are using return in an if, you can yes
👍 thanks
@slate swan this is gonna be annoying, can i make the decorator "try" to get an exception?
so there are two ways
either you ignore ignore those errors in error handler (not prefered)
or you change the logic of sending the error message to error handler (prefered)
nope that wont work
why wouldn't it
cause check is not the place where error is thrown
class CustomException(commands.CommandError): ...
async def check(ctx: commands.Context):
if "1" in ctx.message.content:
raise CustomException()
if "2" in ctx.message.content:
return False
return True
@commands.check(check)
@bot.command()
async def foo(ctx: commands.Context):
await ctx.send("Success!")
@foo.error
async def handler(ctx: commands.Context, error: commands.CommandError):
if isinstance(error, CustomException):
await ctx.send("CustomException was raised inside check!")
elif isinstance(error, commands.CheckFailure):
await ctx.send("Check has failed!")
else:
await ctx.send(f"Got unexpected error: {error}")
check this example, we have command foo and error handler for it decorated with @foo.error
inside the handler we check if the error is CheckFailure
i don't want to make a error handler for every damn command 😭
if it is we send error message
you can create a global one
would be nice
thanks
def is_owner():
async def predicate(inter: discord.Interaction) -> bool:
return inter.user.id == 1234567890
return app_commands.check(predicate)
@bot.tree.command()
@is_owner()
async def foo(ctx: commands.Context):
await ctx.send("Success!")
@bot.tree.error
async def on_error(interaction: discord.Interaction[discord.Client], error: app_commands.AppCommandError | Exception) -> None:
if isinstance(error, app_commands.CheckFailure):
try:
await interaction.response.send_message(f"An error occurred: {message}")
except discord.InteractionResponded:
await interaction.followup.send(f"An error occurred: {message}")
else:
raise error
that looks really complicated for absolutely no reason
thankfully its a global one and has to be made once
should bot.tree.error be at the complete bottom
where is message defined
error message?
yes
try:
await interaction.response.send_message(f"An error occurred: {message}")
except discord.InteractionResponded:
await interaction.followup.send(f"An error occurred: {message}")
``` its sent here
\
💀
no problem
one more thing
also i really recommend the guide i linked few times it covers most of the discord.py content, worth looking into
what do i do with this then
you go back to the old version without sending a message
which is here i belive
i can do this tho right
def is_whitelisted():
async def predicate(inter: discord.Interaction) -> bool:
if inter.user.id in [1184953547066978414, 488172488208023562]:
return True
return app_commands.check(predicate)```
well not really, it has to return True or False, when the if evaluates to False nothing will be returned
just stick with this
👍
i just started discord bots and watched a tutorials and this is not working when i run it
import discord
from discord.ext import commands
client = commands.Bot(command_prefix = '!')
@client.event
async def on_ready():
print("I'm ready to wreak havoc!")
print("-------------------------")
@client.command()
async def hello(ctx):
await ctx.send("Hello, I'm here to wreak havoc")
client.run('')
i blended out the token
intents=discord.Intents.default()
in ur client = commands.Bot(...)
client = commands.Bot(command_prefix = '!', intents=discord.Intents.default())
yeah you are missing intents
should work
!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.
what did i do wrong here 💀
what python version are you using
3.9
explains
uh oh
just remove the annotations
tysm
what are annotations 🥺
in your case its this: : app_commands.AppCommandError | Exception
whar
removing | Exception fixed it
async def on_error(interaction: discord.Interaction, error: app_commands.AppCommandError) -> None:
should i just upgrade my python version 💀
async def on_error(interaction, error):
the bot is now on and running but ! hello not working
my vps uses 3.11.2 i think it would be much appreciated
!hello is supposed to work not ! hello
i know
does it give u an error
just didnt wanna make python bot post smt
or if you wish to keep the annotations and keep using 3.9 use old style annotations like this async def on_error(interaction: discord.Interaction, error: Union[app_commands.AppCommandError, Exception]) -> None: but this would require importing Union from typing blah blah pretty much dont needed
!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.
ok so upgrade python version, got it
nah you can just remove the annoations
No!
then upgrade 
done 
yeah i dont think im upgrading python versions ever again
nvm.
xd whats the warning about
wtf
eh you just missing deps
i noticed
how did you upgrade python
did you check the checkbox saying add python to path
oh ok
make sure pip is pointing to right python version
but if you only have one
it is
then nvm
thanks for this, my permission check was really scuffed before and i sometimes forgot to add permission check to some insane commands, like sync and stuff
it was crazy, but now thank you for this

one more thing
i made a new decorator called
@is_owner()
the people with is_whitelisted have access to is_owner()
how can i fix this 😭
do i have to change the error handler
Show code cause i dont get it
infact anyone can run it
did this, anyone can run the command
can you show the check and how you're calling it
Those checks are for slash commands
oh.
You here have a prefix command
To check for bot owner there is built in one
@commands.is_owner()
Yea
right
and other than that you need to also check for context or interactions depending on whatever commands you have
ok ty
@slate swan can u make an error handler for @commands.is_owner() 💀
or should i just do
else:
await ctx.send("No permission")
You Can modify the one you currently have
how
Add another if statement to it
if isinstance(error, commands.NotOwner):
# send message
Ye
Wait no
I'm talking bs
Dont modify the error handler
It wont work
add this py @bot.event async def on_command_error(ctx, error): if isinstance(error, commands.NotOwner): # send message else: raise error
ok
thanks
how can i completely trash out other prefix command errors
i only want the NotOwner error to care, i don't want others printing a traceback in the console
To achieve that you would need to remove that raise error but i highly dont recommend doing that, instead handle other errors too
ok thanks 
so
else:
pass
By removing that you are muffling all errors so if something happens, you wont know
Dont even need the else
i will know
i don't want to get commandnotfound errors or don't want to wake up to 1000000 errors
wait shit u kinda right i need the errors
Then ignore only those and not all
yeah ur right
Not really a discord bot question but how does discord rich presence work? Why do I have to keep my discord pc version on just to use it?
Your application (script) connects to your discord client (desktop app) (locally), and sets a presence
But why locally? And if let's say I have a binary of my DRP app and send it to someone and they run the thing as well, then will they get the same DRP?
They should I suppose
Unless discord has restrictions on that??? Idk never messed with rich presences much.
Wow hm, now I see Discord RPC has been deprecated for Discord GameSDK lol
anyways thanks leo for your answer :)
where do u run ur bot?
Hello Guys I would like to inform you that I am currently working on the development of Discord Bot, I will develop this bot Insha-Allah very soon I need your feedback that How can I make discord bot viral. Plus I also have the expertise to build advance web scraping softwares in python through AI.
Cool but why ping me?
Oh I see. Yeah guess my knowledge was way outdated lmao
I've never had the reason to do rich presence so I only knew details from other people
how do i put 2 token
def send_messages(messages):
token = ''
headers = {
'authorization': token,
'Content-Type': 'application/json'
}
You don't
That's not how authorisation works.... You make two requests.
it worked if only one token
but i want 2
it is just a sample code
You make two requests, one with each token
but i have
import requests
oo
You can't use two tokens in one request, that's nonsensical
i bought a vps
because i didnt wanna overcomplicate things + i got other things to run aswell
can someone help me here?
did this
@bot.tree.command(name="yesban", description="Sets people on the yes word ban list.")
async def yesban(context: Context):
if context.invoked_subcommand is None:
await context.send("Please specify a subcommand. Subcommands: \n`add` - Adds a person to the yes word ban list \n`remove` - Removes a person from yes word ban list.")
@yesban.command(name="add", description="yes")
@app_commands.describe(user="The user that should be added")
async def yesban_add(context: Context, user: discord.User) -> None:```
im trying to do something like this
basically a subcommand
Since parent commands are not invokable, defining them this way doesn't make sense.
Also, app commands take Interaction objects, not Context.
group = app_commands.Group(name="import", description="...")
@group.command()
async def spotify(interaction: discord.Interaction):
await interaction.response.send_message("You just invoked a subcommand!")
subgroup = app_commands.Group(name='child-example', description='...', parent=group)
# @subgroup.command()
# ...
# etc, then:
bot.tree.add_command(group)
i got it but thanks ❤️
does discord.py has command handling?
i dont want to keep using the same main file for every command
2 types, prefix command handling: ext.commands, slash command handling: app_commands
how do you mention a command again?
how to use the slash command handling i didnt understand a single thing on that
So basically, create slash command
@bot.tree.command()
async def my_command(interaction: discord.Interaction):
await interaction.response.send_message("Hello from my command!")
Then register to discord
await bot.tree.sync() # global
# OR
guild_id = <your guild id>
await bot.tree.sync(guild=discord.Object(guild_id)) # guild specific
More details for creating slash
More details for syncing
that was not what i was asking i think i explanied it wrong
what i was trying to say was i dont want to use the same main file for the slash and normal commands
</name:id>
ahh thanks!
then just load the extension via await bot.load_extension('folder.filename'),
example cogs/admin.py => cogs.admin
do i have to make it file per file or can ı just use it for the folder and make all the commands load
extension are per file, but each extension can hold multiple commands by a single Cog
is there a youtube tutorial for this
it would be much easier to understand
@slate swan :x: Your 3.12 eval job has completed with return code 1.
001 | File "/home/main.py", line 10
002 | print('I'm too lazy to do the rest')
003 | ^
004 | SyntaxError: unterminated string literal (detected at line 10)
@slate swan :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | ABC
002 | DEF
003 | HIJ
004 | KLM
005 | NOP
006 | Im too lazy to do the rest
@slate swan seems like you confused #discord-bots with #bot-commands 
your file name is conflicting with the discord library. It's trying to import from your file named
