#Basic Pycord Help

1 messages Ā· Page 37 of 1

elfin inlet
#

oh okay

errant trout
#

and if you want a dynamic list, then you'd be better off with autocomplete instead of choices

elfin inlet
#

update botrolelist

little cobalt
#

choices it not gonna update without a bot restart

#

and it got a limit of 25 str

elfin inlet
#

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

sage tendon
#

yea im not even sure if custom choices support roles tbfh

elfin inlet
#

ignore all the hassle

#

ignore my awful spelling

errant trout
#

they don't, but you could implement RoleConverter for convenience

errant trout
#

depends on your goals i suppose

elfin inlet
#

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

sage tendon
#

this really just shows the stupid limits and weaknesses that slash commands STILL have

errant trout
#

meh one day the command team will wake up

elfin inlet
sage tendon
#

discord

#

discord made slash commands and then forgot to ever touch them again

#

same with stuff like modals

lofty parcel
sage tendon
#

soon: Nitro only options!
Only nitro users will be able to use these optional command options in your bot!

elfin inlet
#

real

#

nah discord's too busy accidentally breaking youtube's TOS on april fools day and ignoring support tickets

sage tendon
#

Not "child safety" support tickets, mind you

#

ahem anyway back to the topic

elfin inlet
#

its hard work pressing the "deny ticket" button all the time

elfin inlet
#

seperate question

#

ephemeral=True as a perameter in my ctx.respond just doesn't seem to work, any reason for that?

sage tendon
#

are you deferring?

elfin inlet
sage tendon
#

do you use ctx.defer()?

elfin inlet
#

I'm about to get laughed out of the room but idk what that is lol

sage tendon
#

show your code

elfin inlet
#

I'm brand new to PyCord :/

elfin inlet
sage tendon
#

oh yes

elfin inlet
sage tendon
#

no, if you dont know what it is it doesnt matter for this

little cobalt
#

why are you scared and of what?

elfin inlet
sage tendon
#

just show it

elfin inlet
#

what do you wanna see of it?

sage tendon
#

people show their chatgpt 1:1 copy pasted garbage here daily

#

it cannot get worse

errant trout
#

this is literally a channel for help

sage tendon
elfin inlet
#

ctx.respond("placeholder", ephemeral=True) 🤯

sage tendon
#

screenshot it

#

i have long lost trust in people copy pasting correctly :>

elfin inlet
#

its not in my code anymore ive removed it bc it didnt work

sage tendon
#

no offense, just, people tend to change minor stuff and that ends up being the issue

elfin inlet
#

I just typed it out there

sage tendon
#

well the way you did there is right

#

can you show your whole code then, maybe i can see the issue

#

the command

elfin inlet
#

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

sage tendon
#

or you typed ephemereal

elfin inlet
#

I would never

elfin inlet
#

uh what

#

dont mind my ide being pink xD

sage tendon
#

ctx.channel.send, most likely

#

if thats what you wana do

elfin inlet
#

okay ig

#

it worked everywhere else tho

sage tendon
#

you wanna send a message into the channel, right?

elfin inlet
#

idk im confused lol

sage tendon
sage tendon
errant trout
#

what

#

ctx.send has always been a shortcut

sage tendon
#

:>

#

never known of it then

#

then i do wonder why it doesnt work for them

lofty parcel
errant trout
#

it is because ApplicationContext is Messageable

#

thus inherited

lofty parcel
#

Eh

#

Then idk

elfin inlet
#

bruh what raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'TextChannel' object has no attribute 'respond'

tidal vessel
cerulean sable
#

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?

errant trout
#

don't need to do anything special either, just make the button as normal

lofty parcel
#

it does reset ^

little cobalt
#

Learn basic python....

lethal loom
#

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):
        ...```
sage tendon
#

show the slash command group definition

lethal loom
sage tendon
#

I'm on phone lol I can't check a whole text file rn

lethal loom
fresh sierra
lethal loom
#

yeah wehen i remove this one its work

fresh sierra
sage tendon
#

I think it's because of the name then tbh

fresh sierra
#

instead of commands you put test_command for example

#
    @update_cmd.command(name="commands")
    async def commands_test(self, ctx):
        ...
#

like that

lethal loom
#

oh its ture thx but cringe

cerulean sable
# lofty parcel doesnt timeout reset every time a user clicks the button?

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.

cerulean sable
#

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.

lofty parcel
errant trout
#

Yeah something like

#

Right after sending the view, just sleep 60 and then view.stop

#

Or edit the message to disable

solemn finch
#

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

solemn finch
#

i did edit it

fresh sierra
#

and you replace the url = ?

solemn finch
#

it's the same url, do I need to somehow change the url each time?

fresh sierra
#

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

solemn finch
#

it does change from two different inherited Embed classes

cerulean sable
fresh sierra
#

and try to see if the embed has chanegd

solemn finch
#

client in this case being the bot or the image provider?

#

(I am dum)

fresh sierra
#

maybe ur discord

#

cache the embed

#

so if ur reset the cache of ur discord

#

you will see the updated image

#

you can try

solemn finch
#

alright, worth a shot

#

nope, it isn't that

fresh sierra
#

are you only updating the image ?

#

or also the description etc

solemn finch
#

I am just adding a image in the new embed

#

so it might be that?

fresh sierra
#

just to troubleshoot a little bit mor

solemn finch
#

okay, i'll see if that helps

clear lark
#

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

clear lark
fresh sierra
clear lark
sage tendon
fresh sierra
#

its possible that u have overwrite the commands form this file

sage tendon
#

I'm just confused why it says that commands is a list

#

that shouldn't be

fresh sierra
#

and so it chage that

clear lark
fresh sierra
clear lark
#

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

fresh sierra
#

Can you send ur whole file ?

clear lark
#

ok hold on

fresh sierra
#

as i said you are overwritting the variable commands

#

you need to use something else than commands for this variable name

clear lark
#

oof, oh yeah

#

thanks

cobalt comet
#

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?

fresh sierra
#

(From what Nelo said)

cobalt comet
#

lemme actually test it and check

sage tendon
#

which is what nelo said

cobalt comet
#

ye it works like resets the timer when an interaction happened

deft kestrel
#

is there a way to make the bot "listen" when a user send a message but in the dms?

errant trout
#

do you mean in a specific process ("waiting" for a message), or should it do something for every message

deft kestrel
#

no i mean like on_dm_message

errant trout
#

that's just on_message

#

then check if message.guild is None

deft kestrel
#

oh ok

#

thanks

halcyon hearth
#

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

sage tendon
#

upgrade to python 3.12

fresh sierra
#

dont crosspost pls

quartz umbra
#

Quick question, in bot.slash_command, what dtype is ctx?

little cobalt
quartz umbra
#

so if I wanna do ctx.respond, how can I make that ephermal?

sage tendon
#

add ephemeral=True to it

languid hazel
#

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)

young skiff
languid hazel
young skiff
#

would be great to have multiple choice parameters

languid hazel
#

yep

#

i really dont understand why it is not possible

#

i cant find anything about multiple choices in slash commands options

young skiff
#

maybe you can set a parameter to the user to write the list of colors like: green, violet, blue

little cobalt
#

py-cord would have it at the commands if it would be possible

little cobalt
young skiff
languid hazel
young skiff
languid hazel
languid hazel
young skiff
#

that's not very intuitive

languid hazel
#

hm... let me do some research on autocomplete

lofty parcel
#

That's the way to do it.

young skiff
languid hazel
#

And i still dont understand why discord does not allow select menus in modals, and ticks options for slash command options.

#

thank you anyways

languid hazel
#

3 options and its 3^(3) = 9

#

9 options and it goes 387,420,489

#

could be fun to do XDDDD

lofty parcel
red mist
#

.rtfm autocomplete

clear lark
#

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

fresh sierra
sage tendon
#

That's not the recommended way

fresh sierra
#

why ?

clear lark
#

I will use those default help subclasses thank you

sage tendon
#

yea, that is

clear lark
#

not in a mood for like updating help everytime I changed params or add new commands

fresh sierra
#

no but you dont need to do that

clear lark
#

how

fresh sierra
#

you can create a command

#

that itinerate from every command in ur bot

sage tendon
#

Luma, subclassing the help command is the way you're supposed to do it

fresh sierra
#

fom command in self.bot.commands

fresh sierra
clear lark
#

hmm makes sense

sage tendon
#

sigh

fresh sierra
# clear lark hmm makes sense

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

clear lark
#

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

fresh sierra
#

use default help command in bridge

clear lark
#

well thats exactly why I was using minimal help subclassing

fresh sierra
#

since im using bridge too i have made a real command help

clear lark
#

right

#

ill try to make my own ig

fresh sierra
#

and then it will work for both

#

good luck

clear lark
#

ok maybe I should omit the signature instead should work

fresh sierra
#

on the default help command

#

will maybe work

echo wraith
#

Heyy does anyone have some examples of subclassing ApplicationContext?

sage tendon
#

there is no need, ever, to do that

echo wraith
sage tendon
#

no

#

you never create applicationcontext manually, so subclassing it has no point

sage tendon
#

ok, wtf

#

thats very new to me then

echo wraith
#

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

sage tendon
#

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

fresh sierra
#

(just wanna learn some new tricks so no idea for how to help u)

deft kestrel
#

a geniune question is it overall normal for the bot not update commands everytime i turn it on?

sage tendon
#

restart your discord

#

Discord is slow to actually sync commands to the client

#

The bot syncs commands as soon as it starts

echo wraith
#

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

fresh sierra
echo wraith
#
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)
fresh sierra
#

Thanks for the explanation man

echo wraith
#

And that entire hasattr thing allows to only load the guild once from the db avoiding double calls

fresh sierra
#

Translation ?

echo wraith
#

it's the database data

fresh sierra
#

Yes but to do what ?

#

To check if the guild has all the row required insert for ur game ?

echo wraith
fresh sierra
#

Ok, well that’s smart !

river bramble
#

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.

limber terrace
#

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?
fresh sierra
#

But you will need a fonction that is recursive to get this one

#

(Command group => sub command groups => command)

limber terrace
#

this is a thing?

#

damn

#

u havin an example?

fresh sierra
#

Or about that : /group subgroup command

limber terrace
#

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

fresh sierra
#

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

limber terrace
#

if u havin an example in this case, your welcome to share

#

saves me time

fresh sierra
#

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)

limber terrace
#

ill find a way, thank you :D

fresh sierra
#

My pleasure

fresh sierra
#

saumon

#

la bouffe

#

le sushis

lean garnet
#

Hi, is it possible to display custom emojis in field names ?

sage tendon
#

P sure no

fresh sierra
lean garnet
#

Ok, thank you

#

and in value it's still not possible ?

#

only description ?

sage tendon
#

the value should support anything

lean garnet
#

ok maybe i did something wrong

sage tendon
#

emojis are a little weird to put in text imo

lean garnet
#

oh i forgot :

#

yes it works now

#

first time i learn you something The Toothy :p

sage tendon
#

?

lean garnet
#

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

sage tendon
lean garnet
#

yes !

sage tendon
#

ah, lol

#

i think its just markdown that doesnt work in field names then

fresh sierra
lean garnet
#

you're welcome ;)

fresh sierra
#

how to use the allowed mention bot things ?

#

i cant find any example

sage tendon
#

like what

#

bot-wide?

fresh sierra
#
allowed_mentions=[discord.AllowedMentions.replied_user= false, discord.AllowedMentions.everyone])
#

something like so

sage tendon
#

no

#

its one allowedmentions object

fresh sierra
#

can you give me an example of how should i do ?

sage tendon
#

allowed_mentions=discord.AllowedMentions(replied_user=False, everyone=True)

fresh sierra
#

ok thanks you

sage tendon
#

everyone is true by default tho

#

everything is true by default actually

fresh sierra
#

does role should be like so :

#
 allowed_mentions=discord.AllowedMentions(users=True, roles=False, everyone=False, replied_user=False))
sage tendon
#

yea

fresh sierra
#

because of the list snowflake

#

and if i want to specify some role

#

i can do

#

roles=[role_id 1, role_id2]

sage tendon
#

you can leave out users tho, everything is true by default

sage tendon
fresh sierra
sage tendon
#

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

fresh sierra
#

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

rapid jackal
#

how can I create a task that runs every day at exactly 0:00 O'Clock in my time zone?

rugged lodgeBOT
#

Here's the background task example.

devout linden
#

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.

shell radish
#

the rendering is a discord app thing and there's nothing you can do about the physical mention itself

devout linden
#

boo, i was afraid that was the problem given what i've (not) been able to find about this. thank you.

sage tendon
#

wait, but, mentions always use the display name

#

as in, guild nickname if set

#

or what am I missing

shell radish
sage tendon
#

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

vital bramble
#

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.

fresh sierra
sage tendon
#

0 makes no sense lol

atomic fern
#

what is this? didnt understand at all about the error, i cant use send_modal

little cobalt
atomic fern
#

noo

vital bramble
little cobalt
sage tendon
ivory beacon
#

can i send message like this ?
i mean ephemeral message after interaction is already responded ?

sage tendon
#

sure

rain dune
little cobalt
sage tendon
#

tasks really dont work differently in cogs i think

rain dune
#

thanks

little cobalt
#

eh what?

rain dune
sage tendon
#

i mean fair, cogs do change the way you need to use the slash decorator

sage tendon
#

yes really

#

@discord instead of @bot

little cobalt
#

I use the one from discord.commands

sage tendon
#

yea

little cobalt
#

that is how I use my slash commands ;3

sage tendon
#

yea, me too

#

minus guild only and the top ofc

#

tho no option decorator is a sin

little cobalt
#

the @config is just my command builder for the names and descriptions at the command and options

grizzled loom
# sage tendon yea, me too

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?

sage tendon
#

nicht sichtbar für unbefugte

#

deswegen immer den nehmen

#

und kann in den servereinstellungen überschrieben werden

grizzled loom
#

as expected. I think for my nieche case the self built thing is better.

sage tendon
#

suddenly german

grizzled loom
#

man das stƤndige sprachen wechseln macht mich noch bekloppt! šŸ˜‚

little cobalt
red mist
#

Immer diese Deutsche hier

fresh sierra
grizzled loom
broken pivot
#

how i can make this in bot description?

shell radish
#

discord adds them automatically and you can't do anything

broken pivot
lament hound
#

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

sage tendon
#

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

lament hound
#

I'm just reading the documentation, must be in need of an update

sage tendon
#

it's bot.add_cog

#

wait you forgot to make the cog class lol

lament hound
sage tendon
lament hound
#

Will take a look now, thanks

sage tendon
#

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

lament hound
#

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

sage tendon
#

well you still shouldnt use add_command tho

#

follow the cog guide

lament hound
sage tendon
#

yea not sure

lament hound
#

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

sage tendon
#

hm

#

can you do pip list and send it here

lament hound
#

sure can, forgive me for not using virtual envs more

sage tendon
#

hm
you did reinstall it?

lament hound
#

yep

sage tendon
#

can you show your current code in the cog

lament hound
#
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?

sage tendon
#

no

#

can you remove the entire hello command
its a prefix command and that wont work with discord.Bot because thats slash only

lament hound
#

yep! that fixed it!

sage tendon
#

yea, you need to use @discord.slash_command() for slash commands

lament hound
#

should that be updated to reflect on the documentation?

#

appreicate the support

sage tendon
#

i mean the docs have both a prefix and a slash command in there, its kind of just an example of everything

lament hound
#

right, but directly copying the quick example would give that error

sage tendon
sage tendon
lament hound
#

okay cool

lament hound
little cobalt
#

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

lament hound
#

I read the documentation lol, its actually what gave me the error that meant I had to come here

sage tendon
#

i do agree tho, there should probably be 3 guide parts for prefix, bridge and slash only bots

little cobalt
#

There is a guide for it

#

But its not really updated

lament hound
sage tendon
#

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

lament hound
#
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

sage tendon
#

did you restart your discord?

lament hound
#

no, no clue you had to do that

#

wow that's super weird lol - some sort of caching issue?

sage tendon
#

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

lament hound
#

fair enough, alright will do

#

thanks again!

sage tendon
#

also i dont think it makes a big difference but you can change commands.Cog to discord.Cog too

lament hound
#

more consistent, cool

sage tendon
#

yea commands.* is mostly prefix stuff, discord.* is mostly slash stuff

#

but some stuff like listeners are still in commands

lament hound
#

ah...one last thing sorry, when I run bot.reload_extension it gives me a recursive error for loading the cog lol

sage tendon
#

ngl never heard of that

lament hound
#

....and that's because I'm an idiot

sage tendon
#

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

lament hound
#

yep, imported another class that had the same name as my cog

little cobalt
errant trout
#

Unloading with slash has never worked because it's a pain

vital bramble
#

Is there some kind of once event listener for cogs?
I can only find discord.Cog.listener() which listens on but not once...

red mist
errant trout
#

I'm not saying it's impossible, I'm saying we didn't design it like that

red mist
#

I see-

errant trout
vital bramble
#

thx

young skiff
#

Do you recommend implementing unit tests in py-cord?

ivory beacon
tidal zealot
#

is there a constant somewhere for max message length?

edgy nest
#

no

#

but its 2000

#

for bots

tidal zealot
rain dune
#

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

sage tendon
#

choices != autocomplete
and they're limited at 25

rain dune
#
    @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

sage tendon
#

sure, but it won't be validated
also, don't use the typehint if you already use the decorator

rain dune
#

thanks!

rain dune
#

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

rain dune
#

alright!

little cobalt
#

You have to use a select menu for it

rain dune
clear lark
#

Is it possible to have slash command input parameter to be multi-line instead of single line?

sage tendon
#

wdym?

lofty parcel
#

Like
This

sage tendon
#

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

rugged lodgeBOT
#

Couldn't find any results

sage tendon
#

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

errant trout
#

Multi line command input doesn't exist

#

("Yet", it was meant to be added lol)

sage tendon
#

like the modal updates I suppose

errant trout
#

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

sage tendon
#

lol

little cobalt
#

since when is ctx a command option?

sage tendon
#

wdym?

little cobalt
#

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

sage tendon
#

can you show lol

little cobalt
sage tendon
#

are you sure you didnt mess up your code

little cobalt
sage tendon
#

is that in a cog for sure?

little cobalt
sage tendon
#

hey even i, perfection on earth, make mistakes

little cobalt
#

ye

sage tendon
#

yea but not sure
maybe its considered an option within the library but that "option" is automatically filled yknow

little cobalt
#

ye

#

lets see if this it working xd

deft kestrel
#

I updated py-cord from 2.4.1 to 2.5 today and now my bot crashes at this line during load

sage tendon
#

it's discord.ApplicationContext

deft kestrel
#

oh

#

and also my server might be running an even older version of py-cord

sage tendon
#

then fix that

deft kestrel
#

idk

#

it has been more than a year since I installed it

#

fixed this crash

#

had to replace over 80 of these instances

#

lol

deft kestrel
little cobalt
errant trout
tribal crown
#

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

lofty parcel
tribal crown
#

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 šŸ˜„

glossy moon
#

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

tribal crown
glossy moon
#

hmm, it doesnt appear that Mee6 is sending an embedded message

tribal crown
#

šŸ¤”

#

You mean this?

#

From mee6s

#

get the channel by ID, and then use channel.mention

glossy moon
#

yea

tribal crown
#

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 šŸ˜„

glossy moon
#

ill give it a try, looks like ill need the channel id per to documention

tribal crown
lofty parcel
#

You can just hardcode the channel mention if it's always going to be the same.

glossy moon
#

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

lofty parcel
tribal crown
lofty parcel
#

99% of the cases, you never instantiate those classes by yourself.

glossy moon
#

i thought it was the same as instantiating discord.Bot(intents...)

lofty parcel
#

Most of the times the objects you have, contain a guild attribute which contains a discord.Guild object

glossy moon
#

that makes more sense

tribal crown
#

But:

guild = bot.get_guild(GUILD_ID)
role = guild.get_role(ROLE_ID)

Is how I would get the role šŸ˜›

lofty parcel
#

member has a guild attribute

tribal crown
#

There is also discord.utils.get()

lofty parcel
#

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

tribal crown
#

Reminds me of the spiderman gif

glossy moon
#

thank you, you've all been super helpful

#

any reason why when i use channel.mention, its also including the server?

lofty parcel
glossy moon
#

rip

lofty parcel
#

It's just how discord formats mentions

glossy moon
#

must be a newer feature then, because when i set it up way back when that didnt inlcude that

lofty parcel
#

It's kinda new

glossy moon
#

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

keen dragon
#

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?

sage tendon
#

Views only last for 15m max unless they're made persistent

errant trout
#

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)

sage tendon
#

oh right, sorry, mixed it up

vital bramble
#

Do I need the members intent when I want to get the member roles or fetch a member in an interaction?

sage tendon
#

i do think so

errant trout
#

just access ctx.author

sage tendon
#

50/50, pick the answer you like :3

#

but yea ctx.author might always be supplied

vital bramble
#

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

sage tendon
#

why would you need to fetch them again

vital bramble
#

because it does not update them in cache...

#

somehow

sage tendon
#

you dont have members cached without members intent though (?)

errant trout
#

it's because add/remove roles doesn't return anything

vital bramble
#

oh, that may have been the problem.
I just used default.
But why was I able to fetch them then?

errant trout
#

so there's no in-place edit

vital bramble
#

oh ok

#

so the fetch IS necessary

errant trout
#

only when you don't have the intent, yes

#

fetching a single member doesn't require the intent

sage tendon
#

honestly if its easier with the intent, just enable it

#

no point not to

vital bramble
#

because the first two access the cache?

errant trout
#

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

vital bramble
#

so if the members flag is not set in the intents object, the members cache is basically disabled?

errant trout
#

no, there's a separate setting for the members cache

sage tendon
#

It's not disabled, it's just never properly populated

vital bramble
errant trout
#

roles can't be updated locally without the intent

vital bramble
vital bramble
sage tendon
#

well you just tell the API to update the member but at no point does your bot ever know about the updated member

errant trout
#

it doesn't matter

#

it has to be enabled on both

sage tendon
#

that would only happen if the user did another command or, well, you fetched them

vital bramble
#

that's the information I was missing, thanks šŸ™‚

balmy dome
#

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.

errant trout
#

it will be possible in a future pycord version

balmy dome
sage tendon
#

i dont see much use in that tbh

errant trout
#

being able to manage commands without restarting is significantly more convenient than the current system

sage tendon
#

for what use case

errant trout
#

...not having to restart your bot

sage tendon
#

yea but like, what

#

if you add code for a cmd you need to restart your bot lol

errant trout
#

no?

#

you can reload cogs and the callbacks update, you just can't do it for command metadata

sage tendon
#

hm

fresh sierra
#

wait we have to restart the whole bot to add new slash command ?

rapid jackal
#

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?

sage tendon
#

no

#

it's near instant

#

restart your discord though

echo wraith
#

yeah @sage tendon what's that thing where people say it's 1h? Where does that come from?

sage tendon
#

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

forest rain
#

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.

errant trout
#

pycord uses InputText, TextInput is from discord.py

sage tendon
#

ngl weird name

forest rain
little cobalt
lofty parcel
#

.rtfm create_scheduled_event

sly karmaBOT
lofty parcel
#

@stable yarrow

stable yarrow
#

okay thnx

little cobalt
#

;3

lofty parcel
#

No

#

;3

little cobalt
stable yarrow
#

#app-commands :)

shell radish
#

:p

sinful juniper
#
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'

hi, but https://github.com/Top-gg-Community/python-sdk/blob/master/examples/discordpy_example/callbacks/autopost.py

GitHub

A simple API wrapper for top.gg written in Python. Contribute to Top-gg-Community/python-sdk development by creating an account on GitHub.

sage tendon
#

regardless, this would be a topgg issue, not one for here

#

and i heard their SDK is quite shit

sinful juniper
sage tendon
#

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

obsidian elm
#

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?

errant trout
#

did you do pycord or py-cord

obsidian elm
#

py-cord

sage tendon
#

can you show the console output

obsidian elm
#

I also tried different versions as in #library-updates

errant trout
#

don't think it's an issue on our end

#

full traceback would be helpful

obsidian elm
#

(on a raspberry pi bullseye with freshly installed python 3.12.3)

sage tendon
obsidian elm
#

the line isn't there if i sudo it, but the error is the same

sage tendon
#

whats the command you're doing

obsidian elm
#

pip install py-cord

errant trout
#

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

#

you'd be better off setting up a venv too

obsidian elm
#

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

echo wraith
echo wraith
#

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

errant trout
#

yeah you're probably better off just writing your own file for specific requests, seeing how old the official library is

sinful juniper
forest rain
#

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}')`
sage tendon
#

anything in your console?

forest rain
sage tendon
#

so only in discord?

forest rain
little cobalt
#

Not on_submit

forest rain
sage tendon
#

thats when @Override would've helped :)

deft kestrel
#

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

sage tendon
#

yea

deft kestrel
#

huh, this line causes a circular import

shell radish
#

your download was corrupted one way or the other

deft kestrel
#

time to redo .venv lol

#

it worked literally 2 seconds ago

sage tendon
#

bit flip

deft kestrel
#

ok now it works, I redid .venv

shell radish
fresh sierra
#

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
shell radish
#

the second command

fresh sierra
#

?

#

like what is the second command ;)

#

can i print every command until that error ?

rugged lodgeBOT
shell radish
#

walk it to find out

fresh sierra
#

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

fresh sierra
errant trout
#

Oh that was you? Allgood

robust ginkgo
#
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.

little cobalt
#

read the error

robust ginkgo
# little cobalt *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.

errant trout
robust ginkgo
#

Nope.

errant trout
#

could you show your main file

robust ginkgo
#

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"])
little cobalt
#

looks fine

errant trout
#

how many cogs do you have?

robust ginkgo
#

let me see

#

these are all of them

errant trout
#

is this a new error you're getting?

robust ginkgo
#

yes

errant trout
#

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)

robust ginkgo
#

I might try with my newest cogs I've recently added, one of them might be the problematic one.

errant trout
#

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

little cobalt
#

do you have something like a restart cog?

errant trout
#

you can narrow it down by printing bot.pending_application_commands[8]

robust ginkgo
robust ginkgo
#

okay it's this one, but it seems to be working perfectly fine

errant trout
#

well, what happens if you disable it (i.e. remove the command decorator)

#

oh wait

#

my bad, it's 7 not 8

robust ginkgo
#

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

errant trout
#

isee

robust ginkgo
#

Still getting the error

errant trout
#

what does it say at the bottom

robust ginkgo
#
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In 17: Application command names must be unique
errant trout
#

to elaborate, your original error was In 7: Application command names must be unique which reveals the index

robust ginkgo
#

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

errant trout
#

yeah sometimes you miss stuff like that

robust ginkgo
#

the error is gone now, ty @errant trout @little cobalt

errant trout
#

allgood

little cobalt
#

alright

#

.close

sly karmaBOT
#

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.

errant trout
#

well

little cobalt
#

ups xd

#

I though it was a new thread opened xd

robust ginkgo
#

LOL

little cobalt
#

I really should get some sleep

red mist
#

Yes.

clear lark
#

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

edgy nest
#

then you can use isinstance

fresh sierra
clear lark
#

Oh shoot right

fresh sierra
#

its for prefix but you understand

upper flint
#

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

little cobalt
upper flint
#

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

upper flint
ivory beacon
#
message = await interaction.response.send_message(embed=embed)
print(message.id)

why this is isn't printing the message id ?

ivory beacon
#

printing something else's id (maybe interaction)

fresh sierra
#

To get message you need to use interaction.get_original_message()

#

Or something like that

deft kestrel
#

How do I make a datetime as an option

sage tendon
#

not possible

#

just let them input a unix timestamp

deft kestrel
#

alright

fresh sierra
deft kestrel
#

I'll make them input days or hours

stable yarrow
#

or use humanize package

deft kestrel
#

since it's always in the future

stable yarrow
#

from pypi

#

it converts something like "1 day 3 hrs" into number of seconds

sage tendon
#

thats useful

stable yarrow
#

oh fuck my bad

#

its called timeparse not humanize

#

humanize is something else

echo wraith
mild trout
#

Quick question, whats the difference betwen @default_permissions() and @has_guild_permissions()

red mist
#

.rtfm default_permissions

sly karmaBOT
red mist
#

.rtfm has_guild_permissions

red mist
#

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

sage tendon
#

there's also just has_permissions i think

errant trout
#

has_permissions is for current channel, has_guild_permissions is guild wide

red mist
#

*has guild permissions

spice pond
#

why? and fix

#

any help?

red mist
spice pond
# red mist 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()}")```
red mist
red mist
spice pond
red mist
#

well that's unfortunate and tricky...

spice pond
red mist
#

difficult for me atm not going to be home anytime soon, but im sure someone smarter than me might figure out your issue

errant trout
#

Remove your try/except in the modal and let it error normally

spice pond
# errant trout 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

#

'-'

errant trout
#

Do you get any error in the console

spice pond
errant trout
#

What if you implement logging

sly karmaBOT
#
import logging

logging.basicConfig(level=logging.INFO)
red mist
# spice pond nah

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

spice pond
spice pond
red mist
#

just try to do a raise

#

Instead of printing formatted traceback

errant trout
#

Oh duh

#

It's not on_submit, rename it to callback

spice pond
#

wait

red mist
#

huh oh

spice pond
#

damn bro thanks

red mist
#

Told you he smarter than me xD

spice pond
fresh sierra
#

How to ping a slash command ?

#

Like <;id>

stable yarrow
#

</name:id>

#

</name:12>

clear lark
#

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

fresh sierra
fresh sierra
clear lark
#

holy.... this is exactly what I need

sage tendon
#

its basic python lol

#

and its not always ideal to do it that way

clear lark
#

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)

grizzled loom
#

code?

sage tendon
#

not necessarily

fresh sierra
#

Basically you import a from file 1 and in file 1 you import b from form 2, so it import each time

fresh sierra
sage tendon
#

"most likely"

fresh sierra
#

And since he just add the import

#

It’s like

#

99% cos of that

sage tendon
#

And in every instance i encountered that error, it was NOT a circular import

fresh sierra
#

Was it just after importing something from a file ?

#

?tag past

limber wagonBOT
#

dynoError No tag past found.

fresh sierra
#

?tag paste

limber wagonBOT
#

Please copy and paste your code here. This makes it easier for everyone helping you.

sage tendon
#

its just the generic error when an import fails

fresh sierra
clear lark
#

hold on

#

wait a minute

#

I think I realized something

fresh sierra
#

Ok

#

Try and tell us if that work

sage tendon
#

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

fresh sierra
#

( 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

clear lark
fresh sierra
#

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

sage tendon
#

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

fresh sierra
#

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

upper flint
#

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

little cobalt
upper flint
#

It's for my development container, not production one. On production I use extensions of course

errant trout
#

and restarting the entire thing is more convenient...?