#discord-bots

1 messages · Page 346 of 1

slate swan
leaden olive
#

gyus?

glad cradle
gritty mantle
#

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

pale zenith
#

now, generating such potentially complicated GIF- don't ask me 😅

gritty mantle
#

thank you so much

abstract fox
abstract fox
pale zenith
#

[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

abstract fox
#

it's py

#

in my case at least

hushed galleon
#

!d discord.Interaction.delete_original_response

unkempt canyonBOT
#

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.
hushed galleon
#

did you respond before calling that method?

abstract fox
#

Yes.

hushed galleon
#

then what error did you get?

abstract fox
#
@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

hushed galleon
#

er, you have to call it on the interaction object itself

abstract fox
#

huh

hushed galleon
# unkempt canyon

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

abstract fox
hushed galleon
#

you know how you wrote interaction.response? that syntax means you're retrieving the attribute called "response" from the variable "interaction"

abstract fox
#

yh

hushed galleon
#

"delete_original_response" is also an attribute of interaction so to access it, you would write interaction.delete_original_response

abstract fox
#

okay! that makes sense!

#

thank you so much!

slate swan
#

method joeshush2

hushed galleon
#

of course, delete_original_response is a method that won't do anything until you () call and await it

abstract fox
#

additionally, is there any way for me to make the second message not be a reply? if so, how?

hushed galleon
#

oh, that reply syntax appears because you responded to the interaction with send_message()

abstract fox
#
await interaction.followup.send(message)```
for this line
hushed galleon
#

i forgot, does the followup have that same appearance or does it look like a regular message?

#

oh you are referring to that line

abstract fox
#

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

hushed galleon
#

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

unkempt canyonBOT
abstract fox
#

okay

hushed galleon
#

retrieve the TextChannel from that and then .send() to it, basically the same way as followup.send()

copper nacelle
#

the docs are the exact same

slate swan
#

they differ in terms of slash commands

#

of how they are designed

copper nacelle
#

so other than slash commands they are the same?

slate swan
#

there are other changes but pycord is a fork of discord.py so most of the things are the same

copper nacelle
#

oh alright

near rain
#

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?

slate swan
#

cause it doesnt exist

hushed galleon
flat solstice
#

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

hushed galleon
#

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: ...

flat solstice
hushed galleon
#

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()

flat solstice
faint echo
#

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.

hushed galleon
# faint echo Hey, although this question is not exactly about coding using Discord.py it is r...

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

pale zenith
#

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

hushed galleon
#

definitely worth using a venv given how many dependencies it requires

pale zenith
faint echo
#

@pale zenith @hushed galleon Thanks for help, will look into it.

proper egret
#

!find on_invite_create

slate swan
unkempt canyonBOT
#

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.
vapid parcel
#
    @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?
naive briar
#

!d discord.MessageType.premium_guild_subscription

unkempt canyonBOT
vapid parcel
naive briar
#

There's no other way that I know of

vapid parcel
#

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

vapid parcel
#

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.

https://paste.pythondiscord.com/MKPQ

ivory moth
#
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

leaden olive
slate swan
leaden olive
slate swan
#

yes but doesnt look like its this file

opaque jacinth
#

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

slate swan
#

its Intents

#

!intents

unkempt canyonBOT
#
Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

bot = commands.Bot(command_prefix="!", intents=intents)

For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.

opaque jacinth
#

yeah I tried that but it kept throwing the same error

#

maybe because i did intentions = discord.Intentions

slate swan
#

then show this error

opaque jacinth
#

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()
^^^^^^^^^^^^^^^^

slate swan
boreal sage
#

can anyone explain whats a token bot?

opaque jacinth
boreal sage
#

(for context, audit logs show that my friend banned ppl from server but when i ask him he says a token bot did it)

slate swan
boreal sage
slate swan
#

most likely your friend got hacked (clicked something and allowed access to discord on his own)

boreal sage
#

alright dude thank you so much for the help

opaque jacinth
#

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

golden portal
#

means your TOKEN is a None type

azure rain
gray socket
#

Why am I getting this error? It's all up to date

slate swan
slate swan
slate swan
abstract fox
#

Hey! May someone explain as to how I can send a message to a specfic channel using / commands with discord.py

slate swan
abstract fox
#

Okay!

slate swan
#

the get/fetch method returns a channel object on which you can use .send method

abstract fox
slate swan
#

interaction.send is used to reply to an interaction, not to send a message to a specific channel

gray socket
abstract fox
slate swan
# gray socket

Do you eventually have pycord or something else like that installed, consider removing them

slate swan
#

They use the same import name as discord.py and may interfere

abstract fox
azure rain
slate swan
azure rain
azure rain
#

Interesting, this warn was from another test (test_work_with_cogs)
But why shows in test_cog_list
Noticed just now

bleak summit
simple copper
#

!Unindent does not match any outer indentation level

slate swan
bleak summit
# slate swan 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]

slate swan
#

uninstall discord

bleak summit
slate swan
#
  1. its pip uninstall
  2. i said uninstall discord not discord.py
bleak summit
#

ok

slate swan
#

try running it

bleak summit
#

tryed bro not running

pale zenith
# bleak summit

\python codes\discord.py
wires 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.

slate swan
#

!intents

unkempt canyonBOT
#
Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

bot = commands.Bot(command_prefix="!", intents=intents)

For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.

slate swan
#

how do i delete help command

#

nvm its bot.remove_command('help')

frosty roost
#

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

unkempt canyonBOT
#

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>.

shrewd apex
#

its good for beginners ig

hushed galleon
#

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

ivory falcon
#
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?
hushed galleon
#

if so, restarting your discord client should fix it

ivory falcon
hushed galleon
#

!d discord.app_commands.CommandTree.sync

unkempt canyonBOT
#

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.
hushed galleon
#

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

ivory falcon
hushed galleon
unkempt canyonBOT
#

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('------')```
hushed galleon
#

(technically setup_hook isn't a normal event, but in this case the syntax works the same)

ivory falcon
hushed galleon
#

yes

abstract fox
#

how do i send a message to a specific channel btw? if anyone knows?

ivory falcon
abstract fox
#

okay t

#

ty

ivory falcon
#

nps 🙂

abstract fox
#

since the bot's for a specific server so

ivory falcon
ivory falcon
#

so should i do this

abstract fox
#

or maybe im dumb and have done it wrong, hold up

ivory falcon
#

or is it just not working

abstract fox
#

lemme test rq

left mantle
#

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?

slate swan
#

.

shrewd apex
left mantle
#

it's a massive data set, it has every gpu made in it with all of their information

left mantle
#

i'm guessing google still wouldn't like that

left mantle
shrewd apex
#

sqlite can easily handle hundreds of thousands

#

thousands is nothing in coding world terms

#

sizeable dbs contains millions to billions of records

left mantle
#

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

shrewd apex
#

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/

left mantle
#

thanks

abstract fox
#

Hey! How would I find the user of the command then reference i later?

slate swan
#

!embeds

#

!embed

#

What pithink huh

flat solstice
abstract fox
#

Since I don't use the ctx part with / commands anymore.

flat solstice
# abstract fox In a / command?

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

flat solstice
abstract fox
#

idk what you mean now

flat solstice
#

Like the async def, what does yours say?

abstract fox
#

interaction

flat solstice
abstract fox
#

ty

shrewd apex
#

u want the id generally

#

!d discord.Interaction.user

unkempt canyonBOT
shrewd apex
#

just take whichever attribute u need from here

flat solstice
#

Does the docs command support pycords docs?

slate swan
proper egret
#

!ddiscord.on_guild_join

#

!d discord.on_guild_join

slate swan
unkempt canyonBOT
#

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.
abstract fox
grand bobcat
#

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

shrewd apex
grand bobcat
#

thanks

abstract fox
#

how do i check is a user has x role

golden portal
#

has_role = member.get_role(role_id) is not None

abstract fox
golden portal
#

!d discord.Member.get_role

unkempt canyonBOT
#

get_role(role_id, /)```
Returns a role with the given ID from roles which the member has.

New in version 2.0.
golden portal
#

im not sure what is it that you're confused lol

abstract fox
golden portal
#

prefix command or slash command?

abstract fox
#

slash

golden portal
#

is it to only allow certain role to use the slash command?

abstract fox
#

yh

golden portal
#

!d discord.app_commands.checks.has_role

unkempt canyonBOT
#

@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...
golden portal
#

just do ```py
@app_commands.command()
@app_commands.checks.has_role(role id here)
async def my_command(...):

remote reef
#

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

naive briar
#

There's already one

vestal acorn
#

!e

unkempt canyonBOT
#
Missing required argument

code

#
Command Help

!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!

vestal acorn
#

this command is almost an ide itself

vale wing
glad cradle
#

that's like saying to NASA: hey go on Mars but give me credit because the idea was mine

granite rapids
#

nor be restricted/controlled

#

anyways I had that idea before so plz credit me thanks

rugged shadow
#

they call me the law unabiding citizen

split vessel
blazing lance
#

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.

pale zenith
#
  1. how long is "a little while"?
  2. do you have logging enabled?
dense topaz
#

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?

pale zenith
blazing lance
#

just then commands don;t work

#

I've got something I can try Ill see if it changes anything

pale zenith
untold bear
#
    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

naive briar
#

(also, consider subclassing discord.ui.View instead; it'd make your life easier)

untold bear
#

Ohhh thanks

#

It's working perfectly fine now 👍

unkempt canyonBOT
#
Floating point arithmetic

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.

#
PATH on Windows

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 ...
pale zenith
#

@sour saddle I think you confused this with #bot-commands 😅

#

this channel is for asking for help creating discord bots

dense topaz
pale zenith
#

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

dense topaz
#

sorry

umbral carbon
#

what object has the attribute guild

#

this command is in a Cog

#

i tried so much stuff but it just doesnt work

dense topaz
umbral carbon
#

istg i tried that but it didnt work before

#

it worked now

dense topaz
#

ooh

umbral carbon
#

i love you though

#

thxx

dense topaz
#

🫶

umbral carbon
#

it didny work

#

modcomms is the class in the cog

#

there was another issue which ignored the user

#

wait nvm

umbral carbon
vast fiber
#

hi

frosty roost
#

But when I run it, it says this

#

Which I don't understand

shrewd apex
#

u forgot to close the bracket

#

.add_page(embed=discord.Embed()
^~~~~ missing bracket

frosty roost
#

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

shrewd apex
frosty roost
#

If I do it without the class I get this

shrewd apex
#

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

frosty roost
#

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

shrewd apex
#

same issue here as well

#

u should post code as text really makes it harder if u post as images

#

!paste

unkempt canyonBOT
#
Pasting large amounts of code

If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the 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.

frosty roost
#

The 2nd one is from an embed that works

#

But its without pagination

shrewd apex
#
 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(),
+    ))
frosty roost
#

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

abstract fox
#

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

vapid parcel
#

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:

fair hinge
#

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

fair hinge
#

so i dont see why i shouldnt ask it here

lament siren
#

well
right idk database but i think there is many people know it better

mild lava
fair hinge
mild lava
#

You want to store message count per user right?

fair hinge
mild lava
#

ah per guild as well

fair hinge
#

hence the guild_id

mild lava
#

i dont see a reason why the first idea is bad

#

so i would just go ahead with it

fair hinge
#

alright thank you very much

mild lava
#

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?

slate swan
#

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.

fair hinge
#

something like SELECT * from MessagesLeaderboard WHERE guild = ? AND user = ? should provide the user data and removing user = ? would give all data for that guild

mild lava
#

what if the command is invoked in a dm channel?

fair hinge
mild lava
#

that would work

fair hinge
#

i have it on all commands so thats...

mild lava
#

the Bot class is imported from discord.ext.commands

slate swan
#

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.

Discord Developer Portal

Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.

#

Here you go

#

Solve it please

fair hinge
#

youre trying to use intents youre not eligible for or dont have

mild lava
slate swan
#

:V

mild lava
#

please read the error

slate swan
#

Idk

#

How to solve that bro

mild lava
#

@fair hinge has provided a screenshot of the instructions

slate swan
#

Okat fixed.

fallow python
#

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?

tight obsidian
#

Networks are not reliable 100% of time, so it's okay if a connection drops from time to time

fallow python
#

I am self-hosting it on a local computer, so the issue is most likely my internet might have crashed for a bit there?

stark flower
#

Hello is there any one

tight obsidian
#

if it doesn't persist I'd just ignore it

fallow python
errant niche
#

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

vapid parcel
mild lava
misty widget
#

discord _compnents no moduel foud error

#

how do i fix this

#

i am using replit

upbeat otter
vale wing
#

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

snow bane
#

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

severe sonnet
#

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

naive briar
#

What's wrong with it? Please be more specific

severe sonnet
#

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

naive briar
#

Can you show the command's code?

shrewd apex
#

nice pfp lemon_eyes

shrewd apex
severe sonnet
#

here

#

you mean this?

unkempt canyonBOT
#

:x: failed to apply.

slate swan
#

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

slate swan
#

That's Like a crypto scram that we wont help with due to rule 5

slate swan
#

hi

#

need help..

slate swan
# slate swan need help..

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

#
  1. you most likely leaked your api key
  2. KeyError means you are trying to access a key in a dictionary but its not there
slate swan
#

!e ```py
d = {"a": 1, "b": 2}
print(d["c"])

unkempt canyonBOT
#

@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'
slate swan
#

..

slate swan
#

i showed you why you get the error

#

Where.

slate swan
#

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

slate swan
#

Yes it is truth., How can i access it then?

#

!e

unkempt canyonBOT
#
Missing required argument

code

#
Command Help

!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!

slate swan
#

!e w

unkempt canyonBOT
#

@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
slate swan
#

!s

leaden olive
#

the lower part isnt being executed, it should send an error message that i cant be afk twice

leaden olive
#

what do you mean?

slate swan
#

colors

leaden olive
#

ahhh yes i use vscode ahah thanks

slate swan
leaden olive
#

actually i forgot which one, how can i check?

slate swan
vale wing
errant niche
#

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

vale wing
#

Np, as long as it suits your usecase

errant niche
#

and if a message is causing an issue i can just delete it myself

errant niche
# vale wing Np, as long as it suits your usecase

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

vale wing
misty cloak
#

aeyo anyone, any recommendation of a good discord.py CC on yt or a website?

drowsy sand
#

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...

▶ Play video
golden portal
drowsy sand
#

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

slate swan
#

The problem itself is not a discord bot problem

fallow python
#

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.

fallow python
#

Damn.

#

Is there a way to send a modal as a response to a modal submit?

naive briar
#

Use the interaction you get from the on_submit

fallow python
#

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}.

naive briar
#

What's wrong with it?

#

Can you show ErrorModal's code?

fallow python
#
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__)
naive briar
#

I have no idea 🫠

fallow python
#

sadness

hushed galleon
fallow python
#

Yeah I see that's impossible

#

A shame

fallow python
#

How does one use SelectOption from discord.py?
This is what I tried, but that's not valid discord.ui.select.components.SelectOption(

hushed galleon
unkempt canyonBOT
#

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.
fallow python
#

Oh. I see.

hushed galleon
#

create a few of those in a list, then pass them to the discord.ui.Select(options=) parameter

fallow python
#

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,).

hushed galleon
#

oh, is this for a modal? they only let you use text inputs for it, sadly

fallow python
#

Aww

#

Yeah it was a for a modal

dapper summit
#

did we can't use youtube dl anymore ?

pale zenith
unkempt canyonBOT
#

A youtube-dl fork with additional features and patches

Released on <t:1710100091:D>.

vale wing
slate swan
#

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

vale wing
#

Can help you with code review

leaden olive
vale wing
#

How does your members look like when you print it

slate swan
#

thanks a lot man

vale wing
#

Post your project on github and give me access, I will review it

split vessel
vale wing
#

Haha funni 669 commits

slate swan
glad cradle
vale wing
glad cradle
#

should i send help?

split vessel
glad cradle
#

why so much hate, perhaps a white mode user

mossy jacinth
#

is it possible to add a button/select field inside modals?

slate swan
#

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

dull orbit
#

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

vale wing
supple jacinth
#

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

shadow vigil
#

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?

pale zenith
#

!pypi emoji

unkempt canyonBOT
pale zenith
#

see: emoji.emoji_list(text) or emoji.distinct_emoji_list(text)

lyric solar
#

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}")```
shrewd apex
shrewd apex
shrewd apex
lyric solar
#

how do i fix this

#

oh wait you mean switch try and async with aiohttp.ClientSession() as session:?

shrewd apex
#

u need to define some sort of command specific error handler and reset the command cooldown and invoke the command

lyric solar
#

switch these i mean

shrewd apex
#

no

lyric solar
#

im using discord.ext's cooldown

shrewd apex
#

ur command is never called in case of cooldown error

#

its never executing the function

lyric solar
slate swan
lyric solar
shrewd apex
#
@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
shrewd apex
lyric solar
#

uhh give me a second

slate swan
#

and make sure to reraise the error if not handled in if ❗

shrewd apex
#

discord.py performs checks like cooldown before executing the command if the checks fail the command is not executed and an error is raised

shrewd apex
#

!d discord.ext.commands.Command.error

unkempt canyonBOT
#

@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.
lyric solar
#
    @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?

vale wing
lyric solar
#

vsc doesn't give me an error 🤨

shrewd apex
#

self, ctx, error

vale wing
#

Use guard clauses 😭

lyric solar
#

shi i forgotr

#

great this means i have an indent error somewhere

vale wing
#

No

shrewd apex
#

dont think reinvoke is a thing either

vale wing
#

No indents syntax error there's just too many of them and it's bad

shrewd apex
#

just call it

vale wing
#

Nasty nesting

lyric solar
vale wing
shrewd apex
#

!d discord.ext.commands.Context.invoke

unkempt canyonBOT
#

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...
shrewd apex
#

or just call it manually

shrewd apex
#

like await cat(ctx)

lyric solar
#

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

vale wing
#

Me when the

lyric solar
#

me when the

supple jacinth
#

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

slate swan
#

anyone know how i can host my bot 24/7?

cursive spear
supple jacinth
golden portal
#

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

vapid parcel
#

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..

edgy tundra
#

how can i fix it

slate swan
unkempt canyonBOT
#

@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
slate swan
#

Your list does not have enough items

edgy tundra
slate swan
#

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

vale wing
tender bobcat
#

Have anyone already learned how to use embedded app SDK?

severe sonnet
novel sleet
#

Print("hellow world")

vale wing
tender bobcat
#

A custom activity

#

E.g. a game

vale wing
#

I just read their docs and it still doesn't make sense

#

I'd imagine activities would have some engine

#

Like WebGL

tender bobcat
#

That count as web development part already?lol

steel steppe
#

embedded applications is an extension to web applications

tender bobcat
#

Well, I am still investigating about it

#

So that's why I have no idea yet

steel steppe
#

anyway

steel steppe
#

i supply where there is demand

#

ya know what i mean

tender bobcat
#

Nah, just curious anyone already learn it after 3d of release

#

I just remember it's released today

steel steppe
#

bro it was released a month ago wdym

slate swan
#

anyone know any free hosting sites?

tender bobcat
steel steppe
tender bobcat
#

Yeah

#

I know that before it released

#

And just remember it is actually released 3d ago today

steel steppe
tender bobcat
#

I am learning it

steel steppe
vale wing
#

I'd rather use unity and build it as webgl

lyric solar
#

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.")```
shrewd apex
lyric solar
#

maybe who knows

shrewd apex
#

¯_(ツ)_/¯

lyric solar
lyric solar
#

tell me one reason why i shouldn't use it

#

i'm not returning everything

#

i'm used to globals

steel steppe
#

just use chatgpt

#

and u get tons of reasons

lyric solar
shrewd apex
#

i agree that u shouldn't use globals but if you're suggesting someone something you should have some justification yorself too 😂

shadow vigil
cloud dawn
lyric solar
#
  • its a discord bot why shouldnt i use globals
shrewd apex
#

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

shrewd apex
#

cogs views etc yeah

lyric solar
#

the interwebs doesnt help

#

like in a slash command

cloud dawn
lyric solar
leaden olive
#

when creating an Checklist, the ID is none, i didnt find any problems in the code, is it normal that the collum is "NULL"?

carmine crag
#

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

cursive spear
cursive spear
# slate swan any free ones?

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

carmine crag
cursive spear
lyric solar
#

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]

slate swan
#

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

cursive spear
lyric solar
lyric solar
#

it doesn't check the commands author id

#

i want to completely get rid of ctx and use interaction: discord.Interaction instead

lyric solar
slate swan
#

to restrict commands to only users you want

#

so others cant use them

lyric solar
#

should i make a function for it

slate swan
#

ill show you how but is that what you are looking for

lyric solar
#

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

slate swan
#

no, answer my question

lyric solar
lyric solar
#

i don't understand what ur trying to say 💀

slate swan
#

this is how to do it

#

you add a decorator above a command

#

in the example i sent it is @is_owner()

lyric solar
#

oh okay,
is_owner is for the bot owner or guild owner?

#

oh alr

slate swan
#

the is_owner is just a name

#

you define the logic

cursive spear
slate swan
#
def is_owner():
    async def predicate(inter: discord.Interaction) -> bool:
        return inter.user.id == 1234567890
    return app_commands.check(predicate)
slate swan
lyric solar
slate swan
lyric solar
#

can i also do it like this?

return inter.user.id == [1234567890, 0987654321]```
slate swan
#

if you want to check if user id is inside a list you use in operator

#

return id in [...]

lyric solar
slate swan
lyric solar
#

🙏

#

what does return app_commands.check(predicate) do

slate swan
#

it returns a check so when using decorator you dont have to do @app_commands.check(is_owner) you can just do @is_owner()

lyric solar
#

alright

#

so you're saying i can do it like this? or can i remove the ()

slate swan
#

you keep the ()

#

as in example

lyric solar
#

👍

#

and if the person doesnt match is_owner(), do i just make an else statement?

cursive spear
#
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

lyric solar
slate swan
cursive spear
slate swan
#

better to read it

lyric solar
cursive spear
lyric solar
slate swan
#

copy pasting doesnt make him learn

lyric solar
#

i've never worked with decorators

cursive spear
lyric solar
#
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

slate swan
#

yeah thats fine, you can even optimise it a bit

slate swan
#

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

lyric solar
#

so i can just strip away the else:

slate swan
#

since you are using return in an if, you can yes

lyric solar
#

👍 thanks

#

@slate swan this is gonna be annoying, can i make the decorator "try" to get an exception?

slate swan
#

so there are two ways

lyric solar
#

wait

#

i have an idea

slate swan
#

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)

slate swan
lyric solar
slate swan
#

cause check is not the place where error is thrown

lyric solar
#

okay

#

so how do i do the second one

slate swan
#
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

lyric solar
#

i don't want to make a error handler for every damn command 😭

slate swan
#

if it is we send error message

slate swan
lyric solar
slate swan
#

then

#

ok let me set up an example for you

lyric solar
#

thanks

slate swan
#
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
lyric solar
slate swan
lyric solar
slate swan
#

doesnt have to be

#

you can get rid of the annotations also

lyric solar
#

where is message defined

slate swan
#

error message?

lyric solar
#

yes

slate swan
#
        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
lyric solar
slate swan
#

ah

#

yea my bad i copied it

lyric solar
#

💀

slate swan
#

replace the text that is being sent

#

to like Not in whitelist

lyric solar
#

oh okay

#

thanks this really helped me

slate swan
#

no problem

lyric solar
#

one more thing

slate swan
#

also i really recommend the guide i linked few times it covers most of the discord.py content, worth looking into

lyric solar
#

what do i do with this then

slate swan
#

you go back to the old version without sending a message

lyric solar
#

do i change it from "not in" to "in"

#

oh alright

#

so basically just returning True

slate swan
lyric solar
#

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)```
slate swan
#

well not really, it has to return True or False, when the if evaluates to False nothing will be returned

slate swan
lyric solar
#

👍

autumn pewter
#

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

slate swan
#

what is not working

#

the hello command?

lyric solar
#

client = commands.Bot(command_prefix = '!', intents=discord.Intents.default())

slate swan
#

yeah you are missing intents

lyric solar
#

should work

slate swan
#

!intents

unkempt canyonBOT
#
Using intents in discord.py

Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.

There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.

Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:

from discord import Intents
from discord.ext import commands

# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True

bot = commands.Bot(command_prefix="!", intents=intents)

For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.

slate swan
#

enable message_content for prefix commands

#

otherwise it wont work

lyric solar
#

what did i do wrong here 💀

slate swan
#

what python version are you using

lyric solar
#

3.9

slate swan
#

explains

lyric solar
#

uh oh

slate swan
#

just remove the annotations

lyric solar
#

what are annotations 🥺

slate swan
#

in your case its this: : app_commands.AppCommandError | Exception

lyric solar
#

removing | Exception fixed it

slate swan
#

send the code

#

the handler

lyric solar
#

async def on_error(interaction: discord.Interaction, error: app_commands.AppCommandError) -> None:

#

should i just upgrade my python version 💀

slate swan
#

async def on_error(interaction, error):

autumn pewter
lyric solar
#

my vps uses 3.11.2 i think it would be much appreciated

lyric solar
autumn pewter
#

i know

lyric solar
#

does it give u an error

autumn pewter
#

just didnt wanna make python bot post smt

slate swan
#

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

unkempt canyonBOT
#
Discord Message Content Intent

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.

lyric solar
slate swan
#

nah you can just remove the annoations

lyric solar
slate swan
#

then upgrade pensive_bread

lyric solar
#

yeah i dont think im upgrading python versions ever again

slate swan
#

xd whats the warning about

lyric solar
slate swan
#

eh you just missing deps

lyric solar
#

i noticed

slate swan
lyric solar
#

pip is working just had to restart terminal

slate swan
#

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

lyric solar
#

it is

slate swan
#

then nvm

lyric solar
# slate swan 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

slate swan
lyric solar
#

do i have to change the error handler

slate swan
#

Show code cause i dont get it

lyric solar
#

did this, anyone can run the command

flat pier
#

can you show the check and how you're calling it

lyric solar
#

no matter if decorator is applied or not

slate swan
#

Those checks are for slash commands

lyric solar
#

oh.

slate swan
#

You here have a prefix command

lyric solar
#

yeah to sync

#

how do i uhhh

#

apply the decorator for the prefix command fr

slate swan
#

To check for bot owner there is built in one

lyric solar
slate swan
#

Yea

lyric solar
#

right

flat pier
#

and other than that you need to also check for context or interactions depending on whatever commands you have

lyric solar
#

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")

slate swan
#

You Can modify the one you currently have

lyric solar
slate swan
#

Add another if statement to it

lyric solar
#

what

#

to the error handler?

slate swan
#

if isinstance(error, commands.NotOwner):
# send message

slate swan
#

Wait no

#

I'm talking bs

#

Dont modify the error handler

#

It wont work

lyric solar
#

i should

#

uhh wait

slate swan
#

Cause its for slash commands

#

You need one for prefix ones

lyric solar
#

should i do @bot.error

#

or @bot.event

slate swan
#

add this py @bot.event async def on_command_error(ctx, error): if isinstance(error, commands.NotOwner): # send message else: raise error

lyric solar
#

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

slate swan
#

To achieve that you would need to remove that raise error but i highly dont recommend doing that, instead handle other errors too

slate swan
#

By removing that you are muffling all errors so if something happens, you wont know

slate swan
slate swan
#

Why you dont want other errors

#

What are those

lyric solar
#

wait shit u kinda right i need the errors

slate swan
lyric solar
next garden
#

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?

pale zenith
next garden
#

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?

pale zenith
#

They should I suppose

#

Unless discord has restrictions on that??? Idk never messed with rich presences much.

next garden
#

Wow hm, now I see Discord RPC has been deprecated for Discord GameSDK lol

#

anyways thanks leo for your answer :)

golden bane
keen sorrel
pale zenith
#

Cool but why ping me?

pale zenith
golden bane
#

how do i put 2 token

def send_messages(messages):
token = ''
headers = {
'authorization': token,
'Content-Type': 'application/json'
}

pale zenith
#

That's not how authorisation works.... You make two requests.

golden bane
#

but i want 2

golden bane
pale zenith
#

You make two requests, one with each token

golden bane
#

but i have
import requests

golden bane
pale zenith
#

You can't use two tokens in one request, that's nonsensical

golden bane
#

i see

#

thanks bro

lyric solar
golden bane
#

when u can run a free bot 24/7

lyric solar
lyric solar
#

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

pale zenith
# lyric solar can someone help me here? did this ```py @bot.tree.command(name="yesban", descr...

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)
ivory falcon
#

i dont want to keep using the same main file for every command

golden portal
leaden olive
#

how do you mention a command again?

ivory falcon
golden portal
ivory falcon
#

what i was trying to say was i dont want to use the same main file for the slash and normal commands

naive briar
leaden olive
#

ahh thanks!

golden portal
#

then just load the extension via await bot.load_extension('folder.filename'),
example cogs/admin.py => cogs.admin

ivory falcon
golden portal
ivory falcon
#

it would be much easier to understand

lyric solar
#

there is

unkempt canyonBOT
#

@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
pale zenith
#

@slate swan seems like you confused #discord-bots with #bot-commands catblep