#Basic Pycord Help
1 messages Ā· Page 37 of 1
and if you want a dynamic list, then you'd be better off with autocomplete instead of choices
update botrolelist
oh
okay then ill just not implement this command as a slash command (im porting a discord.py bot lol) cuz its a mod command anyway
yea im not even sure if custom choices support roles tbfh
they don't, but you could implement RoleConverter for convenience
if it's a mod command and you're fine with all roles showing instead of a specific list, you could make it a discord.Role option
depends on your goals i suppose
nah its a specific list
im just gonna make it a string input and check if theres a role in the list with that name :/
this really just shows the stupid limits and weaknesses that slash commands STILL have
oh well
meh one day the command team will wake up
is it a problem with the PyCord implementation or a problem with discord API itself?
discord
discord made slash commands and then forgot to ever touch them again
same with stuff like modals
I'm sure they're dead
soon: Nitro only options!
Only nitro users will be able to use these optional command options in your bot!
real
nah discord's too busy accidentally breaking youtube's TOS on april fools day and ignoring support tickets
its hard work pressing the "deny ticket" button all the time
oki
seperate question
ephemeral=True as a perameter in my ctx.respond just doesn't seem to work, any reason for that?
it does?
are you deferring?
?
do you use ctx.defer()?
I'm about to get laughed out of the room but idk what that is lol
show your code
I'm brand new to PyCord :/
oh no
oh yes
please just tell me what it does I'm scared š
no, if you dont know what it is it doesnt matter for this
why are you scared and of what?
ya'll seeing my garbage beginner code lol
just show it
what do you wanna see of it?
this is literally a channel for help
the respond mainly
ctx.respond("placeholder", ephemeral=True) š¤Æ
its not in my code anymore ive removed it bc it didnt work
no offense, just, people tend to change minor stuff and that ends up being the issue
I just typed it out there
well the way you did there is right
can you show your whole code then, maybe i can see the issue
the command
wtf
it worked now
:/
I dunno what I was doing wrong b4
maybe I put ephemeral in my command permaters or something like a dumbass lol
or you typed ephemereal
I would never
you wanna send a message into the channel, right?
idk im confused lol
yeah
yea then its this
never heard of ctx.send as a shortcut so idk
Looks like it's not for ApplicationContext
https://docs.pycord.dev/en/master/api/application_commands.html#discord.ApplicationContext
Command Permission Decorators: Commands: Shortcut Decorators: Objects: Attributes full_parent_name, qualified_id, qualified_name. Methods@ after_invoke,@ before_invoke,@ error, def get_cooldown_ret...
bruh what raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'TextChannel' object has no attribute 'respond'
?
what do you want to do? 
ctx.respond
Hypothetically speaking, what if I want a button to be timed out and disabled after 60 seconds, but within this 60 second duration the user can click it how much ever time and the bot would respond with something or something else. Is that possible? I don't want the button to be one-time only, nor do I want the button to expire once the user has clicked it.
Would there be limitations?
that works fine
don't need to do anything special either, just make the button as normal
doesnt timeout reset every time a user clicks the button?
it does reset ^
Learn basic python....
I have a problem I have a slashcomamndgroup there everything works but as soon as I add it comes the
\ [ERROR] Extension 'cogs.xenority' raised an error: AttributeError: 'SlashCommand' object has no attribute 'Cog'
When I add this
async def commands(self, ctx):
...```
show the slash command group definition
this are all commands and the def
I'm on phone lol I can't check a whole text file rn
update_cmd = SlashCommandGroup(name="update", description="Update Channel Messages", guilds=[625285230823211031], guild_only=True ,default_member_permissions=discord.Permissions(administrator=True))
and all other command works fine ?
yeah wehen i remove this one its work
can you try changing the name ?
I think it's because of the name then tbh
instead of commands you put test_command for example
@update_cmd.command(name="commands")
async def commands_test(self, ctx):
...
like that
oh its ture thx but cringe
Yeah exactly, I want the button to be disabled within exactly 60 seconds, not shorter, not longer, but then if the timeout resets everytime the button gets clicked then I assume the timeout would be extended for longer periods of time.
Button to be disabled within 60 seconds, no matter what the user clicked or hasn't clicked, button isn't one time, do not want it to be disabled until the 60 second mark.
Hmm, I'll see.
I'll try making the button normal, if it doesn't work but it's functional to my needs then I'll just keep using that.
Then you'll have to handle the timeout yourself with asyncio.sleep
Yeah something like
Right after sending the view, just sleep 60 and then view.stop
Or edit the message to disable
is there a way to prevent discord from caching a image resource that changes? I have updated my image on the backend where it's hosted but discord still shows the old one in the Embed
edit the embed ?
i did edit it
and you replace the url = ?
it's the same url, do I need to somehow change the url each time?
i think in order to be edit the embed need to be different
so like if you edit the url= and its still the same maybe it wikl not edit
it does change from two different inherited Embed classes
Yeah that's what I thought too, thanks @lofty parcel & you ofc!
reset ur cache on ur client
and try to see if the embed has chanegd
no like
maybe ur discord
cache the embed
so if ur reset the cache of ur discord
you will see the updated image
you can try
can you try to also update the description
just to troubleshoot a little bit mor
okay, i'll see if that helps
How can I fix
class Help(commands.HelpCommand):
^^^^^^^^^^^^^^^^^^^^
AttributeError: 'list' object has no attribute 'HelpCommand'
I was just copy-pasting the examples of help command classes from the pycord guide
which pycord guide?
Pycord's commands extension comes with a built-in help command. In this guide, we will take a look at them as well as learn how to create your own. Let's dive in!
can you show ur import ?
is that the file the help class is in?
check if you have no commands =
its possible that u have overwrite the commands form this file
they maybe have in the file commands =
and so it chage that
yes I placed the class into that file
Did you check if you donāt have any commands =
Well I didn't specify any help commands or setup my own
I let the defaults do its thing, until I needed to customize it so I copied examples from the guide and copied it to the main script which includes necessary modules
Can you send ur whole file ?
here is ur issue
as i said you are overwritting the variable commands
you need to use something else than commands for this variable name
for the timeout property while creating buttons, will it disable the button right after that seconds, or starts that timer only if no activity is there?
It will disable it after second even with activity
(From what Nelo said)
lemme actually test it and check
which is what nelo said
ye it works like resets the timer when an interaction happened
Ok thanks
is there a way to make the bot "listen" when a user send a message but in the dms?
the bot is always listening
do you mean in a specific process ("waiting" for a message), or should it do something for every message
no i mean like on_dm_message
Does anyone know why the new lines are causing errors? Iām transferring the bot to a hosting provider and it worked fine on my pc, but now Iām getting this error
upgrade to python 3.12
dont crosspost pls
Quick question, in bot.slash_command, what dtype is ctx?
discord.ApplicationContext
discord.ApplicationContext.author
discord.ApplicationContext.bot
discord.ApplicationContext.channel
discord.ApplicationContext.channel_id
discord.ApplicationContext.cog
discord.ApplicationContext.command
discord.ApplicationContext.defer
discord.ApplicationContext.delete
discord.ApplicationContext.edit
discord.ApplicationContext.followup
discord.ApplicationContext.guild
discord.ApplicationContext.guild_id
discord.ApplicationContext.guild_locale
discord.ApplicationContext.interaction
the first one at that what Squid send
tysm
so if I wanna do ctx.respond, how can I make that ephermal?
add ephemeral=True to it
hi, I just have a simple question :
In a slash command option, is it possible to do a select option that accepts multiple choices ?
Something like this :
| [x] Cyan |
| [ ] Yellow |
| [ ] White |
| [x] Purple |
| [x] Green |
| [x] Red |
| [ ] Blue |
/set favcolours colours:[Cyan, Purple, Green, Red]
(ping me if you have an answer)
I don't think so, maybe with a select menu it's possible to accept multiple choices
the current solution i found is to use a modal with a select menu that has a max_value different than 1
would be great to have multiple choice parameters
yep
i really dont understand why it is not possible
i cant find anything about multiple choices in slash commands options
maybe you can set a parameter to the user to write the list of colors like: green, violet, blue
py-cord would have it at the commands if it would be possible
you have to use for something like that a select menu
and use an auto complete of colors followed by commas to select multiple colors, idk
mb it's impossible x) i'll have to find another solution
or use buttons to click an emoji of the color to select, it's more intuitive
you mean, applying the autocomplete on the part after the last comma ?
(i never used autocomplete btw)
(i used the color select as an example, actually i have a lot of options and it won't fit in the button amount limit)
yes, the user writes "blue" and the auto complete shows possible following colors like "blue, red" "blue, violet" "blue, yellow"
that's not very intuitive
hm... let me do some research on autocomplete
You use a select menu.
That's the way to do it.
that's the best solution
so i have to use a message. okay.
And i still dont understand why discord does not allow select menus in modals, and ticks options for slash command options.
thank you anyways
if i do that, the number of possibilities will be exponential with the amount of options
3 options and its 3^(3) = 9
9 options and it goes 387,420,489
could be fun to do XDDDD
They were planned. But discord forgets about actually updating stuff.
You might want to check out autocomplete
.rtfm autocomplete
discord.AutocompleteContext
discord.AutocompleteContext.bot
discord.AutocompleteContext.cog
discord.AutocompleteContext.command
discord.AutocompleteContext.focused
discord.AutocompleteContext.interaction
discord.AutocompleteContext.options
discord.AutocompleteContext.value
discord.utils.basic_autocomplete
discord.AutoShardedBot.get_autocomplete_context
discord.ext.bridge.Bot.get_autocomplete_context
discord.ext.commands.Bot.get_autocomplete_context
discord.Bot.get_autocomplete_context
discord.ext.commands.AutoShardedBot.get_autocomplete_context
discord.ext.bridge.AutoShardedBot.get_autocomplete_context
discord.SlashCommandGroup.invoke_autocomplete_callback
discord.InteractionResponse.send_autocomplete_result
discord.SlashCommand.invoke_autocomplete_callback
discord.ext.bridge.BridgeSlashGroup.invoke_autocomplete_callback
discord.ext.bridge.BridgeSlashCommand.invoke_autocomplete_callback
Is it possible to change the help command description like this
I want to add some introductory of my bot within the minimal help command apart from its default one
remove the dfault help command and do the new one
That's not the recommended way
why ?
I will use those default help subclasses thank you
yea, that is
not in a mood for like updating help everytime I changed params or add new commands
no but you dont need to do that
how
Luma, subclassing the help command is the way you're supposed to do it
fom command in self.bot.commands
and so you can remove the old one and create the subclass
hmm makes sense
sigh
something like that :
class HelpCog(commands.HelpCommand):
def __init__(self):
super().__init__(command_attrs={"hidden": True})
async def send_command_help(self, command: commands.Command):
embed = discord.Embed(title="Command Help", description=f"```{command.short_doc}```")
embed.add_field(name="Usage :", value=f"```{self.context.prefix}{command.qualified_name} {command.signature}```")
await add_embed(embed)
await self.context.message.reply(embed=embed)
async def send_bot_help(self, mapping):
for command in self.bot.commands:
embed.description +=
def setup(bot):
bot.help_command = HelpCog()
markdown is a little bit broken but you understand what i mean
if ur planning on using slash commands this will not work however
Yeah for slash I get this... error
and I just used this sample help command, which your example is fairly similar from the guide
yeah I'm using bridges
i dont hink you can use bridge for that
use default help command in bridge
well thats exactly why I was using minimal help subclassing
since im using bridge too i have made a real command help
ok maybe I should omit the signature instead should work
you can do if ctx.app add the signature, else you dont
on the default help command
will maybe work
Heyy does anyone have some examples of subclassing ApplicationContext?
there is no need, ever, to do that
I might be wrong but i remember seeing some example of that in the docs or somewhere tho
yeah here
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - Pycord-Development/pycord
If decorate your function
like let's say I need to load a guild from the db and i'm lazy I can do something like @load_guild and it will put it in ctx.db_guild
or smth
well i guess you can use it for that then, yea
Keep in mind that that'll cause a db action for every application command though
so if your bot gets a lot of use, you will also get a lot of DB traffic
what are you trying to do ?
(just wanna learn some new tricks so no idea for how to help u)
a geniune question is it overall normal for the bot not update commands everytime i turn it on?
restart your discord
Discord is slow to actually sync commands to the client
The bot syncs commands as soon as it starts
Actually my idea was different, I would do @load_guild decorator, and the ctx subclass would be just for typehinting. To set ctx.guild_data: MyModel | None basically. Then I use a decorator that I created, and that would set ctx.guild_data, check if the guild exists, and if not even return.
@fresh sierra ā¬ļø
So it loads the db data only if I ask for it with @load_guild, because I know the command needs it
Ill send an example
Thats a good idea, rn Iām using a function from each of my class to do translator = get_translator(ctx), I can use ur thing to automatically have ctx.translator
def load_guild_or_return():
async def predicate(ctx):
# Check if the guild data has been loaded already
if not hasattr(ctx, 'guild_obj'):
ctx.guild_obj = GuildAdapter(ctx.guild.id)
await ctx.guild_obj.load()
if not ctx.guild_obj.exists:
raise GuildNotSet(
translations.errors.bot_not_set_up.get(
ctx.locale, translations.errors.bot_not_set_up["en-US"]
).format(
command=commands_utils.mention("mod config start", bot=ctx.bot)
)
)
return True
return commands.check(predicate)
Thanks for the explanation man
And that entire hasattr thing allows to only load the guild once from the db avoiding double calls
What will be the use of ur guild_data ?
Translation ?
I just called guild_data guild_obj in the example
it's the database data
Yes but to do what ?
To check if the guild has all the row required insert for ur game ?
in my case it's to load mod settings and stuff
Ok, well thatās smart !
hello. I have more of a question about voice recording rather than necessarily a bug. I would like to record the stream in chunks no larger than 3 or 5 minutes for example. Each time it gets a new audio chunk, it will perform processing on that audio in the background while immediately starting a new audio recording... I'm hoping I can do this without making the bot exit and enter the voice channel each time it has to restart a new recording. I'm not sure where to start on this as far as the pycord library, any direction on where I can get hacking would be great. Thanks.
no one?
ok
@slash_command(name="help", description="When you know, you know (WIP)")
async def help(self, ctx):
print(self.bot.application_commands)
commands = self.bot.application_commands
for i in commands:
if isinstance(i, UserCommand):
print(f"``{i.name}`` - {i.description}, usercommand\n")
elif isinstance(i, SlashCommand):
print(f"``{i.name}`` - {i.description}, slashcommand\n")
elif isinstance(i, MessageCommand):
print(f"``{i.name}`` - {i.description}, messagecommand\n")
elif isinstance(i, SlashCommandGroup):
print(f"``{i.name}`` - {i.description}, slashcommandgroup\n")```
just a quick thing, did i miss a command group here?

The sub sub groub
But you will need a fonction that is recursive to get this one
(Command group => sub command groups => command)
Example of how to do it ?
Or about that : /group subgroup command
ok, so its a command group within a command group?
damn
na how to do it is a thing ill get from the docs somehow
Yes
I donāt think there is something
Like you just need to do the same thing again for ur subgroup that u does from ur group
(A subgroup is considered as a slash command group like a normal group
Yes
Here it is
async def num_commands(bot: Lumabot):
sorted_commands = []
for cog in bot.cogs.values():
for command in cog.get_commands():
if isinstance(command, discord.SlashCommandGroup):
for subcommand in command.walk_commands():
if isinstance(subcommand, discord.SlashCommandGroup):
for sub_subcommand in subcommand.walk_commands():
sorted_commands.append(sub_subcommand)
else:
sorted_commands.append(subcommand)
else:
sorted_commands.append(command)
unique_sorted_commands = []
for command in sorted_commands:
if command not in unique_sorted_commands:
unique_sorted_commands.append(command)
return len(unique_sorted_commands)
Im on phone
I canāt put the codeblock sorry
Also strange behavior but you need to check 2 times because it count more than 1 time the commands
(If you have better idea of what I did or you have some idea how to improve it tell me ;)
(And Iām using cog to count because and not the self.bot.application_commands because of the issue with unloading cog that donāt remove command)
ill find a way, thank you :D
My pleasure
Hi, is it possible to display custom emojis in field names ?
P sure no
no like for mention and eveyrthing else
the value should support anything
ok maybe i did something wrong
emojis are a little weird to put in text imo
?
you said you was pretty sure it was not possible but it is
usualy when I ask questions here it's you who answers me
nvm
oh is that the field name?
yes !
you also made me learn something thanks ;)
you're welcome ;)
yes
allowed_mentions=[discord.AllowedMentions.replied_user= false, discord.AllowedMentions.everyone])
something like so
no
its one allowedmentions object
Some classes are just there to be data containers, this lists them. Unlike models you are allowed to create most of these yourself, even if they can also be used to hold attributes. Nearly all clas...
can you give me an example of how should i do ?
allowed_mentions=discord.AllowedMentions(replied_user=False, everyone=True)
ok thanks you
does role should be like so :
allowed_mentions=discord.AllowedMentions(users=True, roles=False, everyone=False, replied_user=False))
yea
because of the list snowflake
and if i want to specify some role
i can do
roles=[role_id 1, role_id2]
you can leave out users tho, everything is true by default
yea
yeak ik, im still not sure what i will let on and what i will let off bby default
everyone should most certainly always be off if you have any commands that take direct user input
or disable that in each send specifically depending on the command
yes for everyone yes
more for role that im thinking
since for example at the opening of ticket it will open, but in other case no
i think i will let it by default to false
and in specific case passing to true, just to be sure that it never ping because of an exploit in my bot
how can I create a task that runs every day at exactly 0:00 O'Clock in my time zone?
Here's the background task example.
can someone tell me how to @mention to a guild nick instead of the user's global name? i'm using ApplicationContext.user.mention and it's not the guild nick when it's rendered.
ApplicationContext.guild.get_member(context.user.id) is also not yielding a the guild nick either.
in python, if that matters.
the rendering is a discord app thing and there's nothing you can do about the physical mention itself
boo, i was afraid that was the problem given what i've (not) been able to find about this. thank you.
wait, but, mentions always use the display name
as in, guild nickname if set
or what am I missing
it's different between web/desktop, andriod, and ios/ios/ios
I'm also very certain that's not true
I've never seen a ping that doesn't directly reflect the name I see in chat
Yes, on mobile it'll show the pomelo username in the message preview, but that's the only place I know of that does it that way
How can I actually have a min_values of 0 in a string select menu? I set the min_values property to 0 but I have to select an option (I can't select an option and then deselect it). Does 0 even work?
nvm I think I did something wrong.
Min value is 1 by default, and I think 0 is unlimited choice
0 makes no sense lol
what is this? didnt understand at all about the error, i cant use send_modal
modal can only have 5 input text
noo
wondering if discord will ever change that xD
Soon maybe
pff
never
can i send message like this ?
i mean ephemeral message after interaction is already responded ?
sure
yes
https://github.com/Pycord-Development/pycord/blob/master/examples/background_task.py
is any example available for cogs of tasks?
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - Pycord-Development/pycord
why do you need an example for a cog?
tasks really dont work differently in cogs i think
alright! i thought tasks decorator won't work in cogs
thanks
eh what?

i mean fair, cogs do change the way you need to use the slash decorator
eh not really
I use the one from discord.commands
yea
that is how I use my slash commands ;3
the @config is just my command builder for the names and descriptions at the command and options
Wie ist das eigentlich, wenn man so'n default perm decorator nimmt?
Wirft das dann Fehler, wenn jemand ohne passende Berechtigung loslegt oder ist der Befehl nur für Leuten mit passender Berechtigung sichtbar?
nicht sichtbar für unbefugte
deswegen immer den nehmen
und kann in den servereinstellungen überschrieben werden
as expected. I think for my nieche case the self built thing is better.
suddenly german
man das stƤndige sprachen wechseln macht mich noch bekloppt! š
Ich finde es nicht so schlimm
Immer diese Deutsche hier
One of the most common operations when making a bot is having a loop run in the background at a specified interval. This pattern is very common but has a lot of things you need to look out for: How...
I usually don't mind, just had a long day, that's all
how i can make this in bot description?
discord adds them automatically and you can't do anything
thanks for answer
hi! switching over from dpy, trying to get a basic example together:
#main.py
import discord
bot = discord.Bot()
@bot.event
async def on_ready():
print(f"We have logged in as {bot.user}")
@bot.slash_command()
async def reload(ctx):
bot.reload_extension("cog")
await ctx.send("Reloaded cog.py")
bot.load_extension("cog")
bot.run('X.X.X')
#cog.py
from discord import Embed, Color
from discord.ext import commands
@commands.command()
async def search(ctx):
await ctx.send('hello')
def setup(bot):
bot.add_command(search)
But I get an error,
discord.errors.ExtensionFailed: Extension 'cog' raised an error: AttributeError: 'Bot' object has no attribute 'add_command'
Where have I gone wrong? Thanks in advance!
I've installed pycord via
pip install git+https://github.com/Pycord-Development/pycord
I've also tried install it from pypi, with the same result
uninstall discord.py
and reinstall pycord after, the pypi version
oh wait, no
def setup(bot):
bot.add_command(search)
that isnt how you do it in pycord
There comes a time in the bot development when you want to extend the bot functionality at run-time and quickly unload and reload code (also called hot-reloading). The command framework comes with ...
I'm just reading the documentation, must be in need of an update
it's bot.add_cog
wait you forgot to make the cog class lol
There comes a point in your botās development when you want to organize a collection of commands, listeners, and some state into one class. Cogs allow you to do just that. The gist: Each cog is a P...
I've just copied this exactly, I didn't know you had to do anything else
https://guide.pycord.dev/popular-topics/cogs here's the proper guide
Cogs, often known as modules or extensions, are used to organize commands into groups. This is useful
Will take a look now, thanks
bot.add_command should still exist tho
so if you didnt already, uninstall discord.py and reinstall pycord
py-cord is the package name on pypi
yep, my apologises
not sure where I got pycoord from, totally different š
PS C:\Users\Jacob\Downloads\gcpdiscord> python .\main.py
Traceback (most recent call last):
File "C:\Users\Jacob\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\cog.py", line 790, in _load_from_module_spec
setup(self)
File "C:\Users\Jacob\Downloads\gcpdiscord\cog.py", line 18, in setup
bot.add_command(search)
^^^^^^^^^^^^^^^
AttributeError: 'Bot' object has no attribute 'add_command'. Did you mean: 'all_commands'?
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Jacob\Downloads\gcpdiscord\main.py", line 21, in <module>
bot.load_extension("cog")
File "C:\Users\Jacob\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\cog.py", line 912, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Users\Jacob\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\cog.py", line 795, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.errors.ExtensionFailed: Extension 'cog' raised an error: AttributeError: 'Bot' object has no attribute 'add_command'
still get the error with add_command having ran pip install py-coord and discord.py is uninstalled afaik
yep, just ran pip freeze - no sign of dpy
yep, just wanted to test this
yea not sure
I can't use cogs either...
Traceback (most recent call last):
File "C:\Users\Jacob\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\cog.py", line 790, in _load_from_module_spec
setup(self)
File "C:\Users\Jacob\Downloads\gcpdiscord\cog.py", line 26, in setup
bot.add_cog(Greetings(bot))
File "C:\Users\Jacob\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\cog.py", line 660, in add_cog
cog = cog._inject(self)
^^^^^^^^^^^^^^^^^
File "C:\Users\Jacob\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\cog.py", line 568, in _inject
raise e
File "C:\Users\Jacob\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\cog.py", line 562, in _inject
bot.add_command(command)
^^^^^^^^^^^^^^^
AttributeError: 'Bot' object has no attribute 'add_command'. Did you mean: 'all_commands'?
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Jacob\Downloads\gcpdiscord\main.py", line 21, in <module>
bot.load_extension("cog")
File "C:\Users\Jacob\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\cog.py", line 912, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Users\Jacob\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\cog.py", line 795, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.errors.ExtensionFailed: Extension 'cog' raised an error: AttributeError: 'Bot' object has no attribute 'add_command'
As it relies on add_command
hm
you did reinstall it?
yep
can you show your current code in the cog
PS C:\Users\Jacob\Downloads\gcpdiscord> pip uninstall py-cord
Found existing installation: py-cord 2.5.0
Uninstalling py-cord-2.5.0:
Would remove:
c:\users\jacob\appdata\local\programs\python\python312\lib\site-packages\discord\*
c:\users\jacob\appdata\local\programs\python\python312\lib\site-packages\py_cord-2.5.0.dist-info\*
Proceed (Y/n)? Y
Successfully uninstalled py-cord-2.5.0
PS C:\Users\Jacob\Downloads\gcpdiscord> pip install py-cord
Collecting py-cord
Obtaining dependency information for py-cord from https://files.pythonhosted.org/packages/da/64/058eb4fdc8fcb80623903afa37ab25ad7315c9245c1c3b1276b311384500/py_cord-2.5.0-py3-none-any.whl.metadata
Using cached py_cord-2.5.0-py3-none-any.whl.metadata (6.5 kB)
Requirement already satisfied: aiohttp<4.0,>=3.6.0 in c:\users\jacob\appdata\local\programs\python\python312\lib\site-packages (from py-cord) (3.9.3)
Requirement already satisfied: aiosignal>=1.1.2 in c:\users\jacob\appdata\local\programs\python\python312\lib\site-packages (from aiohttp<4.0,>=3.6.0->py-cord) (1.3.1)
Requirement already satisfied: attrs>=17.3.0 in c:\users\jacob\appdata\local\programs\python\python312\lib\site-packages (from aiohttp<4.0,>=3.6.0->py-cord) (23.2.0)
Requirement already satisfied: frozenlist>=1.1.1 in c:\users\jacob\appdata\local\programs\python\python312\lib\site-packages (from aiohttp<4.0,>=3.6.0->py-cord) (1.4.1)
Requirement already satisfied: multidict<7.0,>=4.5 in c:\users\jacob\appdata\local\programs\python\python312\lib\site-packages (from ...
c:\users\jacob\appdata\local\programs\python\python312\lib\site-packages (from yarl<2.0,>=1.0->aiohttp<4.0,>=3.6.0->py-cord) (3.6)
Using cached py_cord-2.5.0-py3-none-any.whl (1.1 MB)
Installing collected packages: py-cord
Successfully installed py-cord-2.5.0
import discord
from discord.ext import commands
class Greetings(commands.Cog):
def __init__(self, bot):
self.bot = bot
self._last_member = None
@commands.Cog.listener()
async def on_member_join(self, member):
channel = member.guild.system_channel
if channel is not None:
await channel.send(f'Welcome {member.mention}.')
@commands.command()
async def hello(self, ctx, *, member: discord.Member = None):
"""Says hello"""
member = member or ctx.author
if self._last_member is None or self._last_member.id != member.id:
await ctx.send(f'Hello {member.name}~')
else:
await ctx.send(f'Hello {member.name}... This feels familiar.')
self._last_member = member
def setup(bot):
bot.add_cog(Greetings(bot))
is it to do with the 2 discord package imports maybe?
no
can you remove the entire hello command
its a prefix command and that wont work with discord.Bot because thats slash only
yep! that fixed it!
yea, you need to use @discord.slash_command() for slash commands
i mean the docs have both a prefix and a slash command in there, its kind of just an example of everything
right, but directly copying the quick example would give that error
and look at https://guide.pycord.dev/interactions/application-commands/slash-commands as well, very helpful
Learn all about Slash Commands and how to implement them into your Discord Bot with Pycord!
only when using discord.Bot() but yea
I think that example only works out of the box with a bridgebot
same with this page
okay cool
#faq
I must be blind, cant see anything related to this issue
I mean its for the docs and other stuff for the examples
And at the Installation it also says that you have to uninstall all the other librarys if you want to use py-cord
I read the documentation lol, its actually what gave me the error that meant I had to come here
i do agree tho, there should probably be 3 guide parts for prefix, bridge and slash only bots
yes, exactly
i think prefix and bridge should be "hidden" anyway in the guide
every sensible person uses slash only, bridge and especially prefix-only are the minority by far
import discord
from discord.ext import commands
class Greetings(commands.Cog):
def __init__(self, bot):
self.bot = bot
self._last_member = None
@commands.Cog.listener()
async def on_member_join(self, member):
channel = member.guild.system_channel
if channel is not None:
await channel.send(f'Welcome {member.mention}.')
@discord.slash_command()
async def hello(self, ctx, *, member: discord.Member = None):
"""Says hello"""
member = member or ctx.author
if self._last_member is None or self._last_member.id != member.id:
await ctx.send(f'Hello {member.name}~')
else:
await ctx.send(f'Hello {member.name}... This feels familiar.')
self._last_member = member
def setup(bot):
bot.add_cog(Greetings(bot))
okay, thats the code right now
from curseforge import CurseForge
import discord
bot = discord.Bot()
@bot.event
async def on_ready():
print(f"We have logged in as {bot.user}")
@bot.slash_command()
async def reload(ctx):
bot.reload_extension("cog")
await ctx.send("Reloaded cog.py")
bot.load_extension("cog")
bot.run('X.X.X')
it says "We have logged in". but the reload or hello commands don't show up, neither does the bot respond to any mentions
did you restart your discord?
no, no clue you had to do that
wow that's super weird lol - some sort of caching issue?
also in the hello command, you can remove the * parameter
and in slash commands, you need to use ctx.respond to actually respond to the interaction
discord is just slow
they dont wanna sync commands to the client every 2 seconds
also i dont think it makes a big difference but you can change commands.Cog to discord.Cog too
more consistent, cool
yea commands.* is mostly prefix stuff, discord.* is mostly slash stuff
but some stuff like listeners are still in commands
ah...one last thing sorry, when I run bot.reload_extension it gives me a recursive error for loading the cog lol
ngl never heard of that
....and that's because I'm an idiot
i think i remember something about unloading cogs being broken on 2.5 tho
or something not qutie working right
so it might be that
yep, imported another class that had the same name as my cog
Its kinda working
For the cogs you have to
- get the commands if you have some in there and if its a slash command
- reload the cog
- sync the slash_command and add a empty guild list to it else you gonna break it
Unloading with slash has never worked because it's a pain
Is there some kind of once event listener for cogs?
I can only find discord.Cog.listener() which listens on but not once...
So why did discord.py get it to work >~<
They have a completely different structure to us
I'm not saying it's impossible, I'm saying we didn't design it like that
I see-
Idk if it's on 2.5 or master, but we did add the once arg to listeners
Should read https://github.com/Pycord-Development/pycord/pull/2403 because there's some caveats
thx
Do you recommend implementing unit tests in py-cord?
how ?
is there a constant somewhere for max message length?

In 5.options.0.choices: Must be 25 or fewer in length.
what can i do if i want to add autocomplete choices for more than 25
choices != autocomplete
and they're limited at 25
@commands.slash_command(description="Create a shop alert for desired skins.")
@option(
"skin",
autocomplete=discord.utils.basic_autocomplete(
skin_lists
)
)
async def alert(
self,
ctx,
skin: Option(str, "Select the skins", required=True), # type: ignore
):
can i do something like this?
this will like autocomplete from skin_lists
sure, but it won't be validated
also, don't use the typehint if you already use the decorator
thanks!
is it possible to take multiple values in skin like :
@commands.slash_command(description="Create a shop alert for desired skins.", guild_ids=[864779702554984458])
@option(
"skin",
description="Choose a skin from the list",
autocomplete=discord.utils.basic_autocomplete(
skin_lists
)
)
async def alert(
self,
ctx,
**skin
):
like skin can have multiple user inputs :
skin : [item1, item1 ...]
like, if user select one of the thing it will automatically recommend other things, and user can add multiple values in it
Not possible
alright!
You have to use a select menu for it
oh okay! thanks!
Is it possible to have slash command input parameter to be multi-line instead of single line?
wdym?
Like
This
the length limit is generous, you can type well enough
and if you need multiple lines probably either make multiple options or just make the user type \n or whatever, depending on your use case
but p sure options are always single line
Couldn't find any results
I did a line break there but I can't see whether it's an actual line break or line wrap because I'm on mobile
like the modal updates I suppose
Oh I guess it works anyway
You can force it on mobile for some reason
Doesn't work in the fancy command menu or desktop
lol
since when is ctx a command option?
wdym?
I was doing at my command builder and I tried to apply the stuff to the command and its saying that ctx is a command option
can you show lol
are you sure you didnt mess up your code
is that in a cog for sure?
its not my first time writing a bot
:>
hey even i, perfection on earth, make mistakes
ye
yea but not sure
maybe its considered an option within the library but that "option" is automatically filled yknow
I updated py-cord from 2.4.1 to 2.5 today and now my bot crashes at this line during load
it's discord.ApplicationContext
then fix that
which one?
idk
it has been more than a year since I installed it
fixed this crash
had to replace over 80 of these instances
lol
I just checked, 2.3.1
for slash commands always use discord.ApplicationContext at py-cord
always
Update
I fixed it.
I was looking for role_name: Str in a list of discord roles.
I used discord.utilis to find the role using the name and it worked! š
I'm wondering, how I could check if a user has a role?
I know I can use:
user.roles
to get a list of roles. But the format it returns isn't exactly very useful for checking if the use has a role:
[<Role id=name='@everyone'>, <Role id=name='Founders'>, <Role id=name='Astral Dynamics Member'>, <Role id=name='Board Members'>, <Role id=name='Human Resources'>, <Role id=name='Marketing'>, <Role id=name='Executive'>, <Role id=name='CEO'>]
Ideally I would like to do something like:
if role not in user.roles:
But it doesn't seem to pick up that the role is there.. š¤
This sped up my role updating massivley cause I think discord rate limits the amount of updates you can do after a while
You do realize you can use
[role.name for role in user.roles] and that will give a list of strings
Oo
I did not
roles = user.roles
rank = rank_list[user_membership_info["stars"]]
current_rank_role = discord.utils.get(
guild.roles,
name=rank
)
if current_rank_role not in roles:
roles = [role.name for role in user.roles]
rank =
if rank not in roles:
That makes it significatntly shorter
I approve š
has anyone sent hyper links through a welcome message? I just found out that mee6 has put that feature behind a paywall, so I want to add it to my bot
and the hyperlinks would just be to channels on the server
Yeah! I think you have to do it using an embed
hmm, it doesnt appear that Mee6 is sending an embedded message
š¤
You mean this?
From mee6s
get the channel by ID, and then use channel.mention
yea
something like:
async def on_member_join(self, member):
welcome_chnl = bot.get_channel(welcome_channel)
mention_chnl = bot.get_channel(mentioned_channel)
await welcome_chnl.send(f"Welcome {member.mention} Go see this channel {mention_chnl.mention}")
Try that ^^
I'm not too familiar with writing a bot it's my first time x) So lemme know if that works š
ill give it a try, looks like ill need the channel id per to documention
Yeah! Forgot to put _id at the end š
You can just hardcode the channel mention if it's always going to be the same.
yea it shouldnt change
has anyone created a discord.Guild to use the .get_role funtion? Note sure what the data and state parameters are that are needed for creation. The documentation isn't super helpful
You don't create a discord.Guild by yourself
discord..Guild.get_role() needs role ID to get the role from the server I think
99% of the cases, you never instantiate those classes by yourself.
i thought it was the same as instantiating discord.Bot(intents...)
Most of the times the objects you have, contain a guild attribute which contains a discord.Guild object
that makes more sense
But:
guild = bot.get_guild(GUILD_ID)
role = guild.get_role(ROLE_ID)
Is how I would get the role š
Assuming you're using this event Ziggi provided here.
member has a guild attribute
There is also discord.utils.get()
member.guild would return a discord.Guild object
In commands, your ctx also has a guild attribute.
If you need to get a specific guild, you'd use bot.get_guild()
Reminds me of the spiderman gif
thank you, you've all been super helpful
any reason why when i use channel.mention, its also including the server?
Because its outside the server
rip
It's just how discord formats mentions
must be a newer feature then, because when i set it up way back when that didnt inlcude that
It's kinda new
so another stupid question, i am mentioning a role in the message, however is appears as @role-deleted . If i just call the role it calls the correct role, but if I use role.mention then i get the above. I read somewhere that the id value if using an int could cause it to snowflake but that was on a forum using js
my dropdown callback stops sometime into my bots running (ive noticed it ~ an hour after) and just returns "an error occured... blah blah)
any reason it would do this?
Show your code
Show ur error
Views only last for 15m max unless they're made persistent
no, interaction tokens only last for 15 minutes
The library's default view timeout is 3 minutes; setting timeout=None will make it last indefinitely, but this technically isn't "persistent".
What the library calls "persistent" views are simply how we restart callbacks after the bot restarts, in reality it's just an on_interaction listener that checks the custom_id (and message id if you want better filtering); strictly speaking the add_view design is completely unnecessary, but this was done presumably to model it in line with other aspects of the library
(regardless, you do want persistence in the long run)
oh right, sorry, mixed it up
Do I need the members intent when I want to get the member roles or fetch a member in an interaction?
i don't think so
i do think so
just access ctx.author
I'm adding roles to the member and then fetch the member again to have the updated roles. I guess the fetching needs the intent
why would you need to fetch them again
you dont have members cached without members intent though (?)
it's because add/remove roles doesn't return anything
oh, that may have been the problem.
I just used default.
But why was I able to fetch them then?
so there's no in-place edit
only when you don't have the intent, yes
fetching a single member doesn't require the intent
only Guild.fetch_members and Guild.get_member do, but not Guild.fetch_member
because the first two access the cache?
well
fetch_members requires it because it's getting several members
get_member doesn't require it, but obviously since it relies on cache it can't get members that aren't cached
(even without the intent, the library attempts to cache members through commands and some other instances)
singular fetch_member does not require the intent
so if the members flag is not set in the intents object, the members cache is basically disabled?
no, there's a separate setting for the members cache
It's not disabled, it's just never properly populated
So that's why the roles didn't get updated?
if you care just read https://docs.pycord.dev/en/master/api/data_classes.html#discord.MemberCacheFlags
roles can't be updated locally without the intent
That's what I did not, but I want to understand it xD
without the intent set in the code or without it enabled in the application (dev portal)?
well you just tell the API to update the member but at no point does your bot ever know about the updated member
that would only happen if the user did another command or, well, you fetched them
that's the information I was missing, thanks š
Is it possible to add a new slash command and immediately use it on the server when the bot is already running (without rebooting the bot)? According to the experiment, the load_extension function does not register the new command in the list of slash commands.
no
it will be possible in a future pycord version
Oh, okay. I'm looking forward to the update! :D
i dont see much use in that tbh
being able to manage commands without restarting is significantly more convenient than the current system
for what use case
...not having to restart your bot
no?
you can reload cogs and the callbacks update, you just can't do it for command metadata
hm
wait we have to restart the whole bot to add new slash command ?
am I right, that I set all commands as global commands when I don't specify any debug guilds and that this would take up to 1h?
yeah @sage tendon what's that thing where people say it's 1h? Where does that come from?
Because that was the initial timeframe discord said it might take all the way back when slash commands released
and even then it never took more than a few minutes max
Hello!
I get this error all the time
Traceback (most recent call last):
File "/Users/dmitryvelykyi/Work/BotReport/test.py", line 2, in <module>
from discord.ui import TextInput
ImportError: cannot import name 'TextInput' from 'discord.ui' (/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/discord/ui/init.py)
My test code
import discord
from discord.ui import TextInput
text_input = TextInput(label="Test", style=discord.TextInputStyle.short)
print(text_input)
Reinstalled pycord several times, cleaned cache, no other libraries installed.
pycord uses InputText, TextInput is from discord.py
ngl weird name
Thanksšš» Its works!
Take a look at the docs next time ;3
.rtfm create_scheduled_event
@stable yarrow
okay thnx
it is #app-commands ;3
#app-commands :)
:p
import topgg
import sys
# Top.gg Stats Poster
TOPGG_TOKEN = os.getenv("TOPGG_TOKEN")
if not TOPGG_TOKEN:
print("Error: TOPGG_TOKEN not found in .env file.")
sys.exit(1)
def on_autopost_success():
print("TopGG Stats succesfully posted.")
def on_autopost_error(exception: Exception):
print("Failed to post:", exception, file=sys.stderr)
async def post_stats():
try:
wrapper = topgg.StatsWrapper(bot, TOPGG_TOKEN)
await wrapper.post_stats()
except Exception as e:
on_autopost_error(e)
else:
on_autopost_success()
def stats(client: discord.Client = topgg.data(discord.Client)):
return topgg.StatsWrapper(guild_count=len(client.guilds))
@bot.event
async def on_ready():
await post_stats()
File "c:\Users\Max\Documents\Programmieren\Discord-Bots\Aktive Bots\Vysion\main.py", line 67, in <module>
def stats(client: discord.Client = topgg.data(discord.Client)):
^^^^^^^^^^
AttributeError: module 'topgg' has no attribute 'data'
A simple API wrapper for top.gg written in Python. Contribute to Top-gg-Community/python-sdk development by creating an account on GitHub.
Do you use discord.py or py-cord?
regardless, this would be a topgg issue, not one for here
and i heard their SDK is quite shit
pycord
well, their example is for discord.py, but judging by the error i think its just an SDK issue
because if topgg.data doesnt even exist, somethings wrong
I cant install pycord, I get an error that pip==20.3.4 is required, I have pip 24.0. Do I have to downgrade pip or what is going on?
did you do pycord or py-cord
py-cord
can you show the console output
I also tried different versions as in #library-updates
hmm
the line isn't there if i sudo it, but the error is the same
whats the command you're doing
pip install py-cord
when you're installing in console, does it not go through the active packages? it might be because of a dependency... but very odd version to pin on
ah apparently it's a common issue if you installed through sudo to force update system-wide pip https://github.com/pypa/pip/issues/5599#issuecomment-414157896
you'd be better off setting up a venv too
I just tried to install requests and I get the same error, so no pycord issue. I tried uninstalling this pip and now there is none xD
yeah i tried that but got permission errors and i didn't want to invest too much time in it. I've never really used venvs and so far not really a problem
not just quite it is incredibely shit
request is syncronous you should not use it anyways in your discord bot
use aiohttp instead
import discord
import aiohttp
from discord.ext import commands, tasks
from ..config import settings
BASE_URL = "https://top[dot]gg/api" # replace [dot] with a dot
class Topgg(commands.Cog):
def __init__(self, bot: discord.Bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
self.update_count_loop.start()
def cog_unload(self):
self.update_count_loop.cancel()
@tasks.loop(minutes=30)
async def update_count_loop(self):
try:
await self.update_count()
except Exception as e:
# catch all exceptions to prevent the loop from stopping
print(e)
async def update_count(self):
headers = {"Authorization": settings.TOPGG_TOKEN}
payload = {"server_count": len(self.bot.guilds)}
url = f"{BASE_URL}/bots/{self.bot.user.id}/stats"
try:
async with aiohttp.ClientSession() as session:
async with session.post(url, headers=headers, json=payload) as resp:
# raise the eventual status code
resp.raise_for_status()
# if 401 unauthorized
except aiohttp.ClientResponseError as e:
if e.status == 401:
print("Invalid Top.gg token")
else:
print(e)
except Exception as e:
print(e)
this is how I do it without the sdk @obsidian elm that's a bit more code but way cleaner
yeah you're probably better off just writing your own file for specific requests, seeing how old the official library is
Hhm okay. I asked the question also on the top.gg server now.
Hi!
For some reason I always get a Somethig went wrong error when I click Submit
`class ReviewModal(discord.ui.Modal):
def init(self):
super().init(title="Review Submission")
self.score = discord.ui.InputText(label="Score", placeholder="Enter the score out of 10", style=discord.InputTextStyle.short)
self.comments = discord.ui.InputText(label="Comments", placeholder="Enter any comments", style=discord.InputTextStyle.paragraph)
self.add_item(self.score)
self.add_item(self.comments)
async def on_submit(self, interaction: discord.Interaction):
score = self.score.value
comments = self.comments.value
last_entry = data_storage[interaction.user.id][-1]
updated_entry = (last_entry[0], last_entry[1], last_entry[2], score, comments)
data_storage[interaction.user.id][-1] = updated_entry
await interaction.response.send_message(f'Review completed with score: {score} and comments: {comments}', ephemeral=True)
reports_channel = discord.utils.get(interaction.guild.channels, name='ambassador-reports')
if reports_channel:
await reports_channel.send(f'{interaction.user.mention} has completed a review. Score: {score}, Comments: {comments}')`
anything in your console?
Nothing
so only in discord?
It works, thanks againšš»
thats when @Override would've helped :)
is this how you still override intents? it gives a warning and I'm not happy about that
and i forgor to change the intents= in dsicord.Bot
ignore that
yea
huh, this line causes a circular import
your download was corrupted one way or the other
bit flip
ok now it works, I redid .venv
that flipped like at least 17 bits then
is there a way to find easily which command is concerned ?
Ignoring exception in on_connect
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In 1.options.0.options.0.options.0.name: Command name is invalid
In 1.options.0.options.0.options.0.name_localizations.fr: Command name is invalid
In 1.options.0.options.0.options.0.name_localizations.en-US: Command name is invalid
In 1.options.0.options.0.options.0.name_localizations.en-GB: Command name is invalid
the second command
?
like what is the second command ;)
can i print every command until that error ?
walk it to find out
ok so using that it will be the second command each time
thanks i will try
can a bot stream a video in a voice ?, i didnt find anything about it in the doc
No
ok thanks, also thank for ur reponse on github
Oh that was you? Allgood
Ignoring exception in on_connect
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/client.py", line 400, in _run_event
await coro(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/bot.py", line 1178, in on_connect
await self.sync_commands()
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/bot.py", line 735, in sync_commands
registered_commands = await self.register_commands(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/bot.py", line 599, in register_commands
registered = await register("bulk", data, _log=False)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/http.py", line 373, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In 7: Application command names must be unique
Been getting this error. I've double checked my entire code base for any commands with same names or any buttons/select menus with the same custom ids but nothing. This error comes up every time I start the bot yet every single command works perfectly fine.
command names must be unique
read the error
Been getting this error. I've double checked my entire code base for any commands with same names or any buttons/select menus with the same custom ids but nothing. This error comes up every time I start the bot yet every single command works perfectly fine.
are you manually syncing commands anywhere in your code
Nope.
could you show your main file
sure
import discord
import os
from discord.ext import commands
from configparser import ConfigParser
config = ConfigParser()
config.read("configuration/bot.ini")
intents = discord.Intents.default()
intents.message_content = True
intents.guilds = True
intents.members = True
bot = commands.Bot(intents=intents, help_command=None)
path = "."
folders = sorted([name for name in os.listdir(path) if os.path.isdir(os.path.join(path, name))])
for folder in folders:
for filename in os.listdir(f"{os.getcwd()}/{folder}"):
if filename.endswith('.py'):
try:
filename = filename.replace(".py", "")
bot.load_extension(f"{folder}.{filename}")
print(f"[ā
] {folder}.{filename} loaded")
except discord.errors.ExtensionAlreadyLoaded:
print(f"[ā
] {folder}.{filename} already loaded")
bot.run(config["BOT"]["token"])
looks fine
how many cogs do you have?
is this a new error you're getting?
yes
perhaps a bit much, but you could narrow it down by disabling cogs one by one per restart
(or conversely, start with 1 cog and go up)
I might try with my newest cogs I've recently added, one of them might be the problematic one.
the error you're showing when not "legitimate" (i.e. the user has fully unique commands) is typically only when you run sync_commands after the bot has connected, but in your case it's showing on startup which is quite odd
oh actually
do you have something like a restart cog?
you can narrow it down by printing bot.pending_application_commands[8]
nope, nothing to od with that
alright
okay it's this one, but it seems to be working perfectly fine
well, what happens if you disable it (i.e. remove the command decorator)
oh wait
my bad, it's 7 not 8
okay
"pings"
interesting
ok so I will remove this since this was an old command I had, must have forgotten to remove the actual command group
isee
Still getting the error
what does it say at the bottom
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In 17: Application command names must be unique
to elaborate, your original error was In 7: Application command names must be unique which reveals the index
Oh right
I will check 17 then
Oh so it was that pings command group
It must of been when I duplicated a cog and forgot to remove that line of code from the new one
yeah sometimes you miss stuff like that
the error is gone now, ty @errant trout @little cobalt
allgood
Done with your help thread?
Please close your own help thread by using </close:1009144375709814897> with @rugged lodge.
Backup bot: </solved:1109625445990793246> (or
.solved) with @sly karma.
well
LOL
I really should get some sleep
Yes.
is this a good way to check if particular exception occurred in specific command?
I couldn't seem to use isinstance this way, with different exceptions that is not part of discord.DiscordException object
you need to unpack it; getattr(error, 'original', error)
then you can use isinstance
also its not for exceptions in expections ? without the s since you are itinarating in it
Oh shoot right
also im doing like that if that maybe can help you
its for prefix but you understand
I have a bot that saves user sent image url and sends it to a different channel but instead of showing the image preview, it displays this:
Why does that happen? I tried doing this manually and it only shows preview in a channel where the image was originally sent
did you send it as a url and not as a file?
Yes
I can sent urls as files in pycord?
send*
Initial image is sent by user in a channel. Then I check message attachments and grab a url
And then I'm pasting this url in other channels which leads to this
message = await interaction.response.send_message(embed=embed)
print(message.id)
why this is isn't printing the message id ?
printing something else's id (maybe interaction)
This return interaction
To get message you need to use interaction.get_original_message()
Or something like that
thanks
How do I make a datetime as an option
alright
you can take str as arg and then use the datetime.sfrtime
I'll make them input days or hours
or use humanize package
since it's always in the future
thats useful
wow that's very nice
Quick question, whats the difference betwen @default_permissions() and @has_guild_permissions()
.rtfm default_permissions
.rtfm has_guild_permissions
default does default permissions for members with certain permissions
For example only someone who can view audit log may use command
has guild permissions checks that the user has permissions guild wide
Unlike has permissions that only checks it for the current channel
As you may or may not know there's an entire permission hierarchy;
where channels overrides category's and categories override roles default permissions
there's also just has_permissions i think
has_permissions is for current channel, has_guild_permissions is guild wide
yes... is stated under guild has permissions
*has guild permissions
I need more context of what I am looking at
import discord
from discord.ext import commands
from discord.ui import Modal, InputText, View, Button
import traceback
intents = discord.Intents.default()
intents.messages = True
intents.message_content = True
intents.guilds = True
bot = commands.Bot(command_prefix="!", intents=intents)
class FormModal(Modal):
def __init__(self):
super().__init__(title="Data Form")
self.add_item(InputText(label="Name", placeholder="Enter your name"))
self.add_item(InputText(label="Age", placeholder="Enter your age"))
async def on_submit(self, interaction: discord.Interaction):
try:
if interaction and interaction.channel:
name = self.children[0].value
age = self.children[1].value
await interaction.channel.send(f"**{name}** has submitted the form:\nName: {name}\nAge: {age}")
await interaction.response.send_message(f"Thank you for your submission, **{name}**!", ephemeral=True)
else:
await interaction.response.send_message("Something went wrong. Please try again.", ephemeral=True)
except Exception as e:
await interaction.response.send_message(f"An error occurred: {e}", ephemeral=True)
print(f"Error: {traceback.format_exc()}")
class ButtonView(View):
def __init__(self):
super().__init__()
@discord.ui.button(label="Open Form", style=discord.ButtonStyle.primary)
async def button_callback(self, button: Button, interaction: discord.Interaction):
if interaction and interaction.response:
await interaction.response.send_modal(FormModal())
@bot.event
async def on_ready():
print(f"Bot is ready. Logged in as {bot.user}")
@bot.command()
async def form(ctx):
view = ButtonView()
await ctx.send(f"Click the button to open the form:", view=view)
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandNotFound):
await ctx.send("Command not found.")
elif isinstance(error, commands.MissingPermissions):
await ctx.send("You don't have the necessary permissions to use this command.")
else:
await ctx.send("An error occurred.")
print(f"Error: {traceback.format_exc()}")```
@mild trout (pinged you so your answer won't go under in chat)
Don't you get any errors printed out, because I see you're using an error handler?
not a single on just for once Error: NoneType: None
well that's unfortunate and tricky...
can you create one and test it like in one of you bots and share it with me?
difficult for me atm not going to be home anytime soon, but im sure someone smarter than me might figure out your issue
Remove your try/except in the modal and let it error normally
now even the modal is not oping
class FormModal(Modal):
def __init__(self):
super().__init__(title="Data Form")
self.add_item(InputText(label="Name", placeholder="Enter your name"))
self.add_item(InputText(label="Age", placeholder="Enter your age"))
async def on_submit(self, interaction: discord.Interaction):
if interaction and interaction.channel:
name = self.children[0].value
age = self.children[1].value
print(f"Submitted Name: {name}, Age: {age}")
await interaction.channel.send(f"**{name}** has submitted the form:\nName: {name}\nAge: {age}")
await interaction.response.send_message(f"Thank you for your submission, **{name}**!", ephemeral=True)
else:
await interaction.response.send_message("Interaction or channel is None. Please try again.", ephemeral=True)
print(f"Error: {traceback.format_exc()}")```
no no it was a glitsh it opend but the same
'-'
Do you get any error in the console
nah
What if you implement logging
import logging
logging.basicConfig(level=logging.INFO)
Does your bot have some other error handler that handles the errors even now that you removed the extra error handler of the try except
yes py @bot.event async def on_command_error(ctx, error): if isinstance(error, commands.CommandNotFound): await ctx.send("Command not found.") elif isinstance(error, commands.MissingPermissions): await ctx.send("You don't have the necessary permissions to use this command.") else: await ctx.send("An error occurred.") print(f"Error: {traceback.format_exc()}")
still the same now imp thing
huh oh
damn bro thanks
Told you he smarter than me xD
rep for both of you guys thanks alot
thanx you
is it possible to pass variables to cog, let's say I have variable in my main.py but I want to access it inside the cog which is written to another py
For what do you need it?
Thanks ;
Other file.py :
from main import variable
holy.... this is exactly what I need
well no
Extension 'cogs.genai' raised an error: ImportError: cannot import name 'ai_allowlist' from partially initialized module 'main' (most likely due to a circular import) (/workspaces/SGBOT/main.py)
this is from main.py
code?
You have a circular import
not necessarily
Basically you import a from file 1 and in file 1 you import b from form 2, so it import each time
Itās written due to a circular import so
"most likely"
And in every instance i encountered that error, it was NOT a circular import
No tag past found.
?tag paste
Please copy and paste your code here. This makes it easier for everyone helping you.
its just the generic error when an import fails
@clear lark can you show ur code here ?
See, Luma, it also doesnt make sense to be a circular import
You import 1 variable from another file, there is no way that can turn into a circular import unless that line itself is an import somehow, if thats even possible
Circular imports can only really happen with complete imports
Im not sure about that but in my memory when you import something it still read the whole file and do the import in the whole file too
( i think i run into an error because of that back then)
So like
cog import var from main
main import var from cog
Read each file each time and so do a circular import
I see
Not a circular import
Ur ai whitelist is only defined in the on_ready
Toothy was right
You should move ur code to get the ai wl outside the event
I don't think you can do it within on ready anyway
I'm not entirely sure how imports in python work, but on_ready is only called after everything is done, at which point all the cogs are already loaded
So if you just define it outside of on_ready but still fill it inside of it, you will get an empty dict while importing (before on_ready)
oh wait you just open a file
yea then just open the file outside of on_ready lol, no reason for it to be in there
Yeah you need to move everything outside event
Because even if you change the var after
It will not change in ur cog file until the main is reloaded
Which is not possible since itās the main
How to automatically restart discord bot if one of the code files change?
I heard that I can use nodemon for this but are there any other alternatives? I just don't want to download both nodejs and python to the docker container that hosts the bot
Why restart if you can reload cogs?
Not convenient If I have to type something to bot on every tiny code change
It's for my development container, not production one. On production I use extensions of course
and restarting the entire thing is more convenient...?
