#Basic Pycord Help (Quick Questions Only)

1 messages · Page 77 of 1

cyan quail
#

otherwise there's something else in the file that's messed it up

topaz rune
#

do you know if there is a doccumentation for type in @option?

cyan quail
#

the type is inherited from your typehint

#

hm

#

actually

cyan quail
#

i.e. description=...

topaz rune
#
 @commands.slash_command(name="mute", description="Permet de mute un utilisateur")
    @option("user", "L'utilisateur que l'on souhaite mute", required=True, type=discord.Member)
    @option("reason", "La raison du mute", required=False, type=str)
    async def mute(self, ctx, user, reason='L\'admin n\'a pas donné de raison'):
    

the description after @commands.slash_command?

cyan quail
#

that description

topaz rune
#

oh got ut

#

I just put type=**kwarg ?

#

sorry im not so good w/ oop

cyan quail
#

you can leave the type part in

#

im just asking you to add description= to the 2nd args

topaz rune
#

oh

#

ok

#

well

topaz rune
cyan quail
#

because you didn't use it as a kwarg, it assumed the description you set was the type

topaz rune
cyan quail
#

mhm

candid coral
#

Does the execution speed decrease if the variable assignment is done in one line?
Before:

variable1 = ...
variable2 = ...
... = ...

After:

variable1, variable2, ... = ..., ..., ...```
cyan quail
#

so then when you tried to do type=.. later, it broke because you passed type twice

cyan quail
#

allgood

#

the thing is that this is the opposite of Option

#

because the first arg in Option is input_type and the 2nd arg is optional description

#

but it's too significant to change at this point

topaz rune
# cyan quail allgood

ok last question for tonight buddy:

@bot.event
async def on_member_remove(member):
    rank.remove_user(member.id)
    le_serv = bot.get_guild(923316085950918656)
    mention=member.mention
    guild=member.guild
    user_num = len(le_serv.members)-4
    embed=discord.Embed(title=str("*** Quelqu'un s'en va! ***"),colour=0x6BFF33,description=str(f"Malheureusement, {mention} a quitté le {guild}, à bientôt!").format(mention=mention, guild=guild))
    if member.avatar != None:
        embed.set_thumbnail(url=f"{member.avatar}")
        embed.set_author(name=f"{member.name}",icon_url=f"{member.avatar}")
    else:
        icon = 'https://imgs.search.brave.com/8q2vzpdFmkVX8pvFePnT9a0xfU-i8HKXE7ozolyxSLs/rs:fit:1024:1024:1/g:ce/aHR0cHM6Ly9pLmlt/Z3VyLmNvbS9QUTdE/OUt2LnBuZw'
        embed.set_thumbnail(url=f"{icon}")
        embed.set_author(name=f"{member.name}",icon_url=f"{icon}")
    embed.set_footer(text=f"{member.guild}",icon_url=f"{member.guild.icon}")
    embed.add_field(name="Nom d'utilisateur:", value=member.display_name)
    embed.add_field(name="Nom du serveur:",value=guild)
    embed.add_field(name="Membre numéro:", value=user_num)
    await guild.system_channel.send(embed=embed)

sometimes, when someone leave, this function just don't activate, like it work... sometimes.
Am I making smth wring?

#

maybe I should use on_raw_member_remove instead of on_member_remove?

young bone
#

what are your intents?

topaz rune
# young bone what are your intents?
intents = discord.Intents.all()
intents.emojis = True
intents.guilds = True
intents.messages = True
intents.message_content = True
intents.members = True

proud mason
#

well sometimes the member is not available in cache

proud mason
topaz rune
proud mason
#

hmm the class should be stated there too

#

one sec

proud mason
#

that class will be returned

topaz rune
#

it dont feel safe to use

proud mason
#

lol why not

topaz rune
#

idk, when I click on the doc, it put warning

proud mason
#

the non-raw version just does bot.get_guild(payload.guild_id).get_member(user.id) thats all

topaz rune
#

and my poor english makes me scared of coding smth that I dont understand

proud mason
young bone
topaz rune
proud mason
young bone
#

oof

topaz rune
#

anyway
thanks for your help @proud mason@young bone@cyan quail, it help me a lot!
💙 💙 💙 💙

solemn idol
#

yup typing made it work, almost looks the same but typing does make it look better, and still lets the user know the bot is working :)

stable cradle
#

How can I get a list of the IDs of the roles the author has?

solemn idol
#

You need to access the roles attribute of the Member object and use a list to extract the IDs

stable cradle
#

how can I do that?

solemn idol
#

I suppose you do that a bit like this;

role_ids = [role.id for role in member.roles]
solemn idol
#

(if you're using that in a command ofc, you can also use ctx.author.roles)

stable cradle
#

ctx.author.roles?

solemn idol
#

yes

stable cradle
#

yeah was about to say lol

solemn idol
#

^^

young bone
solemn idol
worldly schooner
#

Does on_application_command gets executed before the command or at the same time as the command?

#

If it is at the same time, is there a way to make the on_application_command run first?

worldly schooner
# young bone what?

eg.: Someone sends a command to the bot, and I want the on_application_command to be executed before the command that the user called. Main purpose of that is to update the user data before he runs the command in question.

#

I will try something called @before_invoke

cyan quail
#

But yeah before_invoke is what you want

potent tendon
#

I am trying to setup a virtual environment with pycord and I installed the base dependency, but it says there is no module called discord, what do I do?

potent tendon
#

I'm using a venv so it's really just py-cord

#

and all the dependencies

#

huh wait

#

using the venv instead of just a requirements folder changes stuff

frail spade
#

can i have discord link where i can have basic templet of runing the bot

opaque needle
#
class MyView(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)
    @discord.ui.select(
        placeholder="Выбирете роль",
        min_values=1,
        max_values=1,
        custom_id="role",
        options=generate_menu()
    )
    async def select_callback(self, select, inter: discord.Interaction):
        print(select.values)
        role = inter.user.roles
        for i in role:
            print(role)
            print(i.id)
            if i.id == int(select.values[0]):
                await inter.user.remove_roles(get(inter.guild.roles, id=int(select.values[0])))
                await inter.response.send_message(f"Вы выбрали роль <@&{select.values[0]}>. Успешно забрана!")
            else:
                await inter.user.add_roles(get(inter.guild.roles, id=int(select.values[0])))
                await inter.response.send_message(f"Вы выбрали роль <@&{select.values[0]}>. Успешно выдана!")```

Error:
discord.errors.InteractionResponded: This interaction has already been responded to before
torpid wraith
#

I can't seem to get the bot to play a simple local audio file... And I'm having trouble debugging it because it successfully connects and then just freezes and reports "The application did not respond". No errors in the console. I added some print statements, and it never gets to the second one:

# Join the user's voice channel
print("I get here!")
voice_channel = ctx.author.voice.channel
voice_client = await voice_channel.connect()

# Load the local audio file
print("I don't get here?")
audio_source = discord.FFmpegPCMAudio(AUDIO_DIR + file)```
#

If I run the command again it throws: ClientException: Already connected to a voice channel.

torpid wraith
# proud mason Update to 2.4.1

Omg... Tysvm... I had py-cord >= 2.3.2 in my requirements.txt file thinking it would "install any version above that value" facepalm

proud mason
#

that code logic is very scuffed

#

i suggest you do smth like this instead of the loop-

role = member.guild.get_role(int(select.values[0]))
if role in member.roles:
  # remove it
else:
  # add it
#

this will be much faster and much more efficient

#

and this will actually work

#

button parameter goes before the interaction parameter

#

self, button, interaction

#

like that

quasi stratus
#
class BaseView(View):
    def __init__(self, interaction: discord.Interaction, game: BaseGame) -> None:
        super().__init__(timeout=15.0, disable_on_timeout=True
        self.interaction = interaction
        self.game = game

    async def on_timeout(self) -> None:
        await self.interaction.edit_original_response(content="Game stopped due to timeout")
        self.stopGame()

    def stopGame(self) -> None:
        self.disable_all_items()
        self.stop()
        self.game.stopGame(self.ogPlayer.id)```

Any idea why the on_timeout doesn't disable the items but when my button does view.stopGame() it disable the items ?
Maybe there's something i didn't understood about the on_timeout 🤔
proud mason
#

disable_on_timeout=True is ignored if you override the on_timeout method

quasi stratus
#

Yeah, i know for this one it's just here by default x)

#

And yeah thanks, forgot the view=self

proud mason
#

lol np

green hinge
#

Can I use the on_member_update function to access whether or not a new user has accepted Discord's "Accept Rules" themselves and then assign them a role accordingly? 🙂

full basin
#

.tias

winter condorBOT
full basin
#

The docs pretty much answer your question.

green hinge
full basin
#

Yes, get triggered when it changes

green hinge
# full basin Yes, get triggered when it changes

Okay then it should work like this or ?

    @commands.Cog.listener()
    async def on_member_update(self, before, after):
        if before.pending and not after.pending:
            for role in ROLES:
              await after.add_roles(role)
full basin
#

Yes.

#

But you can remove that for loop

#

.rtfm add_roles

winter condorBOT
full basin
#

add_roles can take a list of roles afaik

green hinge
full basin
#

Yes

green hinge
proud mason
nimble rose
#

how can i get number of bans in server?

nimble rose
young bone
nimble rose
#

i just check the docs xd

opaque needle
#

How to create such a message?

spring hare
solemn idol
#

(the that only you can see it is called an ephemeral)

opaque needle
#

Thanks

topaz rune
#

hi, sorry to disturb, but I want to know smth:
with / commands and @options, how can I do that my user can mention many users in once.
actually, I have this:

@commands.command()
    async def invite(self, ctx, *args):
        """
        Permet d'inviter un/plusieurs utilisateur(s) dans son salon vocal privé
        discord.Member : *args -> les/la mention(s) faite(s) par l'utilisateur de la commande (l'auteur)
        """
        is_there = False
        members = (
            ctx.message.mentions
        )  # je récupère la liste des mentions (sous forme de discord.Member)

and I want to transform it into a slash command:

@commands.slash_command(name="invite", description="Invite un ou des utilisateurs dans ton salon privé!")
@option(name="user", description="Les utilisateurs à inviter", type={?????}, required=True)
async def invite(self, ctx, *args):
        """
        Permet d'inviter un/plusieurs utilisateur(s) dans son salon vocal privé
        discord.Member : *args -> les/la mention(s) faite(s) par l'utilisateur de la commande (l'auteur)
        """
        is_there = False
        members = (
            ctx.message.mentions
        )

thanks

opaque needle
#

discord.errors.InteractionResponded: This interaction has already been responded to before

young bone
topaz rune
solemn idol
# opaque needle

right... you can only have 1 response to that, if you could provide your entire command it might be easier to tell you what you're doing wrong :P

proud mason
#

@opaque needle if you want to send multiple messages, use interaction.followup.send()

merry dune
#

Heya, i have question, how i can integrate button in prefix command😅

young bone
merry dune
#

thanks, it remains to create a function for this and call the buttonkek

proud mason
#

i suggest you check out the guide

#

.guide

winter condorBOT
merry dune
merry dune
opaque needle
#
    async def select_callback(self, select, inter: discord.Interaction):
        role = inter.user.guild.get_role(int(select.values[0]))
        if role in inter.user.roles:
            await inter.user.remove_roles(get(inter.guild.roles, id=int(select.values[0])))
            resp = "Роль убрана!"
            await inter.response.defer()
        else:
            await inter.user.add_roles(get(inter.guild.roles, id=int(select.values[0])))
            resp = "Роль добавлена!"
            await inter.response.defer()
        await inter.response.send_message(resp, ephemeral=True)```
#

?

proud mason
#

do you have multiple instances running?

#

also, defer at the start of the callback, instead of doing it inside the if blocks

merry dune
#

await inter respond
And last line too

#

U need one respond and other only send

proud mason
#

and just pass role to add/remove_roles ??

merry dune
#
    async def select_callback(self, select, inter: discord.Interaction):
        role = inter.user.guild.get_role(int(select.values[0]))
        if role in inter.user.roles:
            await inter.user.remove_roles(get(inter.guild.roles, id=int(select.values[0])))
            resp = "Роль убрана!"
            await inter.response.defer() #1 pespond
        else:
            await inter.user.add_roles(get(inter.guild.roles, id=int(select.values[0])))
            resp = "Роль добавлена!"
            await inter.response.defer() #1 respond 
        await inter.response.send_message(resp, ephemeral=True)# 2 respond```
Umm i see 2 cases respond
proud mason
#

oh right

#

im sorry

#

yes 2nd should be interaction.followup.send

merry dune
proud mason
#

||i thought you were talking about the 2 defers doggokek ||

merry dune
#

I myself once wrote a bunch respond on the authomaticalkek
and then I thought it was wrongblobpain

if == ...
   await ctx.respond("first")
else:
   await ctx.respond("second")

await ctx.send("dont use respond here")```
merry dune
#

Не за чтоLovePycord

green hinge
#

Why are all members always shown as offline although some are online?

intents.members = True
intents.guilds = True


guild = ctx.guild
      for member in guild.members:
        print(member.status)```
coarse cargo
gleaming falcon
#

Is there an autocomplete example for mentionables? I thought it was in Guide or examples folder, but failing to find it

green hinge
gleaming falcon
coarse cargo
gleaming falcon
coarse cargo
cyan quail
#

however, discord only defines it as users and roles

#

you won't get channels there

gleaming falcon
cyan quail
#

it's just the direct type that discord uses

#

when you typehint member/role, it's converted to SlashCommandOptionType internally

gleaming falcon
#

ahhhh. Gotcha! pycord magic 🪄

cyan quail
#

(you probably still need to use Option though)

gleaming falcon
cyan quail
#

oh i meant specifically for SlashCommandOptionType

gleaming falcon
#

Ah, I see

#

Unrelated, how can we get things like ctx.respond to have IDE autocompletion. I'm always afraid I'm going to misspell ephemeral 😛

cyan quail
#

i can't really comment because autocomplete has always worked for me by default

proud mason
green hinge
lost lodge
proud mason
livid wolf
#

How do I have a new line in an embed?

proud mason
livid wolf
#

Oh

#

that simple

proud mason
#

yea lol

young bone
proud mason
#

inline is for fields

young bone
#

ye

proud mason
#

@livid wolf you were asking for the description right? or fields?

proud mason
#

oh

#

the field itself can be put on a new line by passing inline=False

young bone
livid wolf
#

Thanks

violet heron
#

ok im prolly dumb but

young bone
violet heron
#

using one of the quickstart sripts here

young bone
#

replit oof

#

?tag replit

obtuse juncoBOT
violet heron
#

and i get

young bone
violet heron
#

good question

violet heron
#

yeah i saw that

#

ok so i uninstalled but it's the same error

young bone
#

just create a new project and do the stuff

violet heron
#

yeah

young bone
violet heron
#

argh

#

now i can't click on the button

young bone
#

what?

violet heron
#

let me cook actually i think im just 0 iq

young bone
#

No, its Replit

#

its really bad for that stuff

violet heron
#

what do you suggest instead

#

that i can host for free

young bone
#

this maybe?

#

I use a Raspberry Pi

violet heron
#

ah

#

back where i started

young bone
violet heron
young bone
#

Do you know basic python?

violet heron
#

kinda

#

i have an already working bot

#

but i was trying to go through pycord instead

#

whats weird is my previous one worked with bot = commands.InteractionBot() to initialize but bot = discord.Bot() doesn't

young bone
#

what?

#

can you send the pip list?

violet heron
#

for which one

young bone
#

the one who is not working

violet heron
#

numpy 1.24.3, flask 2.3.2, urllib3 2.0.2 py-cord 2.4.1, discord 2.2.3

young bone
#

discord is installed

violet heron
#

yes

young bone
#

you have to uninstall all discord and other librarys

#

?tag install

obtuse juncoBOT
#
  1. Uninstall discord.py or any other forks of discord.py you might have with the namespace discord.
    python -m pip uninstall discord.py discord -y

2a. Install py-cord
python -m pip install py-cord

2b. Update py-cord
python pip install -U py-cord

Installing other builds:
Note: You need to have git installed. Use ?tag git to find out how to install git.

Updating the module to master branch (unstable):
pip install -U git+https://github.com/Pycord-Development/pycord

violet heron
#

alr

#

same error

#

idk don't worry about it

young bone
green hinge
#

How is it possible to dynamically create the buttons depending on how many values are present in self.specc?

        for specc in self.speccs:
            self.add_item(discord.ui.Button(label=specc, custom_id=specc, style=discord.ButtonStyle.green))

    @discord.ui.button()
    async def button_click(self, button: discord.ui.Button, interaction: discord.Interaction):
specc = button.custom_id```
proud mason
green hinge
proud mason
#

and instead of adding discord.ui.Button(...), add your subclass. like self.add_item(MyButton(...))

#

yea much better to subclass Button

green hinge
#

Ah thank you! 🙂

violet heron
green hinge
proud mason
#

yes

earnest bear
#

Is there any way i could categorize my slash commands?

proud mason
#

yes

#

slash groups

coarse cargo
#

How can i edit only the field of an embed without need to rewrite all the embed? if this is even possible.

coarse cargo
#

Maybe can you explain me how to do that?

young bone
#

I cannot explain it because I dont know how to do it xd

#

but maybe this can help you

coarse cargo
#

ty, i'll try

proud mason
#

.rtfm set_field

winter condorBOT
coarse cargo
agile dust
#

Since when does ctx.author.id not work???

await ctx.respond(f":tick: <@{ctx.author.id}> has been vouched `{lines}` times", file=discord.File(f"Reputation/{member.id}.txt"))
AttributeError: 'NoneType' object has no attribute 'id'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/pacity/.local/lib/python3.9/site-packages/discord/bot.py", line 1114, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "/home/pacity/.local/lib/python3.9/site-packages/discord/commands/core.py", line 375, in invoke
    await injected(ctx)
  File "/home/pacity/.local/lib/python3.9/site-packages/discord/commands/core.py", line 132, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'NoneType' object has no attribute 'id'
#

ping when replying

cyan quail
robust hatch
#

Hi! I have this code to check if the user is registered in the bot and I cant figure out how to stop it from executing when the user isn't registered

async def on_command(ctx):
    #if user not is registered
        #cancel the command```
robust hatch
#

i know but i need to cancel the command with pycord

#

when someone calls any command it goes first in this function

#

i want to cancel the command somehow

young bone
#

you could use check

robust hatch
#

how

young bone
#
@commands.check()
robust hatch
#

what does it do?

young bone
robust hatch
#

ty

#

tysm

#

i got it

violet heron
#

how do i make a slash command arguement mandatory?

full basin
#

theyre required by default unless you provide a default argument

violet heron
#

ah ok

violet heron
#

what events covers when the bot is pinged?

silver moat
violet heron
#

ahh

#

ok ty

copper pine
#

hi there, i'm having a little issue, this is my code:

@bridge_command(description="Get useful info about Books and eBooks")
@discord.option("book_name",description="Enter a book name (Optional tip: add authors to get better results)")
    async def bookinfo(self, ctx, book_name):

The problem that is only reciving one argument, anyone knows how to get more arguments?

elfin dagger
#

add another discord.option and argument to the function

silver moat
#

you can add up to 25 options

rare ice
#

What are the benefits of using a Sharded Bot with a bot that is in over 700 servers? Currently I am using the standard commands.Bot

rare ice
#

I mean like does the bot run more smooth?

#

Like faster?

#

What are the differences?

cyan quail
#

sharding only starts to make a difference closer to 1500 or so? maybe less

#

if you want your bot to run smoother then that's on the specs it's running on

rare ice
#

Ah ok

cyan quail
#

the reason it exists is mainly to split events across several instances

raw ore
#

Are variadic slash commands a thing? ie smth like python async def authorize_users(self, ctx, members: [discord.Member] = None):

proud mason
raw ore
#

slash, but if its different between the two I'd be curious to know anyway

proud mason
#

Yea you can do it in prefix commands

#

The library will manage everything for you

#

You can even accept a list of a type between other parameter
Like async def cmd(ctx, name: str, users: list[discord.Member], reason: str)

#

This isn't possible for Slash commands as i remember

#

Because the discord.Member option only let's you pick 1 member

raw ore
#

got it, ty

proud mason
#

you might be able to do some tricks by accepting a string and using Converters

#

Although im not quite familiar with how that would work

distant roost
#

Is there a way to check if a member is timeouted?

proud mason
winter condorBOT
distant roost
#

Thank you i haven’t founded it in the docs

solemn idol
#

anyways I did it like this

proud mason
#

format_exc won't work like that

#

Use traceback.format_exception(error)

#

On python <3.10, you might need to pass some extra args like error.__class__, error.__traceback__ and stuff

#

Search Google for examples

solemn idol
#
@discord.Cog.listener()
    async def on_application_command_error(self, ctx, error):
        # Get the guild and the channel where you want to log the errors
        guild = self.bot.get_guild(GUILD_ID) # Replace GUILD_ID with the ID of the guild
        channel = guild.get_channel(CHANNEL_ID) # Replace CHANNEL_ID with the ID of the channel

        # Create an embed to log the error
        em = discord.Embed(title='Error', color=em_red)
        em.add_field(name='Error Type', value=type(error).__name__, inline=False)
        em.add_field(name='Error Message', value=f'`{error}`', inline=False)
        em.add_field(name='Exception', value=f'`{traceback.format_exc()}`', inline=False)
        await channel.send(embed=em)
coarse cargo
#

There is any benefit in using @option, instead of defining them in the parameters?

proud mason
fervent cradle
#

I'm using youtube_dl and I get this error after half playing a 3 minutes song,
if any of you had this same issue, what solution did you use to solve it? I tried different ways and it never worked. sad

young bone
violet heron
#

How would I make the bot respond in a whisper

rare ice
#

.rtfm InteractionResponse.send_message

winter condorBOT
rare ice
#

.rtfm ApplicationContext.respond

violet heron
#

Ahh ty

raw ore
#

What's the canonical way to define a slash command that deliberately does not send a response message, and doesn't cause a timeout error?

#

or would my best bet be 'send it anyway, and delete it after/make it ephemeral' if that's not possible

silver moat
#

It’s always better to say something like “Done!” than to say nothing at all.

graceful brook
#

Does anyone know how to use a local file for the url parameter of discord.Embed.set_image()? Or if it's possible?

meager heron
#

My bot hit 2500 servers, so I just enabled sharding via commands.AutoShardedBot. I'm getting the following warning every minute:
WARNING:discord.gateway:WebSocket in shard ID 0 is ratelimited, waiting 60.00 seconds
The bot seems to work fine, though on_ready() hasn't fired. Is this something to worry about?

#

Ah! It just ticked up to shard ID 1 after 11 minutes. Progress, perhaps

obtuse juncoBOT
#
f = discord.File("some_file_path", filename="image.png")
e = discord.Embed()
e.set_image(url="attachment://image.png")
await messagable.send(file=f, embed=e)```
silver moat
meager heron
#

Yeah, I'm used to that, just not to receiving this particular shard ratelimit warning

#

If that's all that's happening, then cool

silver moat
#

yeah that’s just the library fetching all the members

graceful brook
graceful brook
# silver moat ?tag localfile
file = discord.File(f"attachments://assets/test.png", filename=f"test.png")
embed.set_image(url="attachments://assets/test.png")
await message.edit_original_response(content=content, embed=embed, view=SetupButtonsView(), file=file)

I apologize if I may be misunderstanding how to do this.

silver moat
#

should just be attachments://test.png iirc

graceful brook
#

I will try that when I get home, thank you

glossy forum
#

Hey, Is there a way to wait until msg is sent in order to add emojis to it?
y'know, standard dealing with 'NoneType' object has no attribute 'add_reaction'

glossy forum
#

oh, this might be what I need, lemme check it out

violet heron
#

what event handler is for when someone replies to the bot?

silver moat
violet heron
#

how would i format it

silver moat
#

.rtfm message.reference

violet heron
#

i don't see it

silver moat
#

you can try getting/fetching the message reference ID and getting the author attribute of it

violet heron
#

ah

#

so something like message.ReferencedMessage.author?

silver moat
#

the MessageReference class doesn't have an author attribute

violet heron
#

ah

silver moat
#

you should use the id attribute and get/fetch the actual message instead

glossy forum
# glossy forum oh, this might be what I need, lemme check it out

okay, that helped
but there's another issue - wait_for doesn't give the expected result

@discord.slash_command()
async def register(self, ctx: discord.ApplicationContext):
    def check(reaction_: discord.Reaction, user_: discord.Member):
        return user_ == ctx.author and reaction_.message == message and str(reaction_.emoji) in answer_emoji
    answer_emoji = ('\U0000274E', '\U00002705')  # no, yes
    #some code
    interaction = await self.bot.send_privacy_policy(ctx, registration=True)
    message = await interaction.original_response()
    await message.add_reaction(answer_emoji[1])
    await message.add_reaction(answer_emoji[0])
    try:
        reaction, user = await self.bot.wait_for('reaction_add', timeout=60.0, check=check)
    except asyncio.TimeoutError:
        await ctx.respond("Registration canceled due to lack of response")
        await message.delete()
        return
    else:
        if str(reaction.emoji) == answer_emoji[0]:
            await ctx.respond("Registration canceled due to rejecting privacy policy")
            await message.delete()
            return
    # some code in case the answer_emoji[1] is selected
violet heron
#

getting 'Message' object has no attribute 'MessageReference' @silver moat

violet heron
#

ooooh

silver moat
#

even a comment like # LOOK HERE could help

glossy forum
#

Sorry, I was in the process of editing it
basically, I expect the user to click on the emoji depending if they agree with the bot's privacy policy or not
the emojis display as expected, but the bot doesn't react on that and defaults to the except clause

the #look here is this line reaction, user = await self.bot.wait_for('reaction_add', timeout=60.0, check=check)

silver moat
#

and also what are you trying to do and what isn't working

glossy forum
#

@silver moat okay, now it's cleared up

violet heron
#

alr i got the id of the reference message, how do I find the author of that message

silver moat
#

.rtfm get_message

silver moat
#

.rtfm fetch_message

glossy forum
silver moat
#

.tias

winter condorBOT
violet heron
#

:/

glossy forum
#

but ig that answers the question as well :p

silver moat
#

you can always try printing the value

#

of str(reaction_.emoji) ofc

violet heron
#

test = await message.channel.fetch_message(message.reference.id)

#

object has no attribute 'id'

#

doesn't work with message_id either

violet heron
#

asked chat gpt, got answer, code fixed

#

i love crying

fleet viper
#

guys is anyone here familiar with the tasks.loop parameters? I have a list containing the hour and minute of the time I want the loop to run at. My code used to run in discord.py but now that I try to migrate it to pycord (for slash commands mostly) It seems to not work anymore and I either get a typeerror : can't compare offset-naive and offset-aware times
or the loop just doesnt execute and when checking for the remaining seconds it just returns None

from dateutil.tz import gettz
...           @tasks.loop(count=1,time=dt.time(tzinfo=gettz("Europe/Berlin"), hour=int(timeS[0]), minute=int(timeS[1])))
async def timer():
    await self.reminder()

return timer

I check with timer.seconds , after using timer.start() later in the code

glossy forum
glossy forum
#

okay, I needed to compare their IDs

silver moat
#

If there isn't one, then Python will compare their memory locations, which are different.

glossy forum
#

gotcha

silver moat
fleet viper
#

do you mean with tzinfo=None as the time parameter? It avoided the error but the loop didnt execute on time and i couldnt figure out how it would

silver moat
#

or in other words, subtract 2 hours from the time since berlin is GMT+2

fleet viper
#

so there isnt a way to just use GMT for that?

silver moat
fleet viper
#

thank you, I will take a look at it tomorrow

torpid wraith
#

Is it possible to pass a slash command parameter to a before_invoke decorated function?

strong bobcat
#

Please help

#

TypeError: Invalid permission(s): Administrator

#

I use @has_permissions(Administrator = True)

#

from discord.ext.commands

proud mason
cyan quail
#

you could probably do something like accessing ctx.selected_options, but you won't get the direct variables/args from the command.

topaz rune
#

Hi, is there an equivalent of @bot.event for @commands pls?

@commands.event
AttributeError: module 'discord.ext.commands' has no attribute 'event'
proud mason
#

What are you trying to do?

topaz rune
#

on_member_join

proud mason
#

Run some code when any command is executed?

#

?

topaz rune
#
@commands.event
    async def on_member_join(member): 
        await rank.add_user(self.member.id, member.name,1,1)
#

add into database user when join

proud mason
#

Oh wait are you trying to add an event listener in cogs?

topaz rune
#

yes thats the point

#

can't I?

proud mason
#

Use @commands.Cog.listener()

topaz rune
#
@commands.Cog.listener()
@commands.event
    async def on_member_join(member): 
        await rank.add_user(self.member.id, member.name,1,1)
#

like this?

proud mason
topaz rune
#

okok

#

thanks ill try

#

works, ty

solemn idol
#

I am trying to make an error handler for my bot... yet I am struggling on how to do this most efficient.

Basically I have the default
on application command error stuff
with if isinstance ...

But now I am trying to make some custom embed errors which I can just call... because as of right now I have a cog with a lot of try and except statements some with literally the same embed made on multiple places and its taking up unnecessary space...
I was trying to do this in my error_handler.py cog but I am not sure how to do this, if I should somehow make custom errors which get put into isinstance or just custom classes which get called on the except statement in the (extra large cog, because of the amount of embeds).... any ideas?

cyan quail
#

You can also have error handlers for each specific cog

tulip ledge
#

What do I need to make bots on my PC?

proud pagoda
young bone
#

Xd

proud pagoda
#

Everything else is online, i.e Discord Account, Code editor, Python installed

young bone
tulip ledge
#

Yes

solemn idol
cyan quail
#

Mhm

solemn idol
#

mh that just enlightened my thoughts, thank you very much :)

cyan quail
#

Well, probably not forbidden

solemn idol
#

that was an example eheh-

cyan quail
#

since it's HTTPexception it has some other requirements

#

Yeah

solemn idol
cyan quail
#

Well if you look In the file

#

HTTPException requires a request response from discord

#

You want to use an error that can be initialised freely

topaz rune
#

hi blood_hi
does someone have an idea of why this thing doesn't get execute:


class CommandErrorHandler(commands.Cog):

    def __init__(self, bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_command_error(self, ctx, error):
        traceback_str = ''.join(traceback.format_exception(type(error), error, error.__traceback__))
        print(traceback_str)
        print(error)
        if "You do not own this bot." in traceback_str:
            await ctx.reply("T'as pas le droit de faire ça :).")
        console = await self.bot.fetch_channel(1070805582447136819)
        
        if "is not found" not in traceback_str:
            await console.send(f'L\'utilisateur <@{ctx.author.id}> a effectué la commande `{ctx.message.content}` dans le channel <#{ctx.channel.id}> à {datetime.now().strftime("%H:%M:%S")} le {datetime.now().strftime("%d/%m/%Y")}.')
            await console.send(f"Erreur:")
            await console.send(f"py\n{error}\n`")
            await console.send(f"Traceback:")
            await console.send(f"py\n{traceback_str}\n\n\n\n")

Like it's not getting call when there is an error

cyan quail
#

Or regular command

topaz rune
cyan quail
#

Apparently

topaz rune
#

so thats on_slash_error?

#

or a thing like this?

cyan quail
#

on_application_command_error

topaz rune
#

ty, imma try

solemn idol
#

oh well that makes my life easier

topaz rune
cyan quail
#

It has the error arg

topaz rune
#

I am looking for all of the errors

cyan quail
#

Hm

#

on_error maybe?

topaz rune
cyan quail
#

Though idk if that actually has the error arg

topaz rune
#

sorry for my poor english ahah

topaz rune
proud mason
topaz rune
proud mason
#

you dont get ctx with it

topaz rune
#

oh

#

uh

proud mason
#

in fact, you dont even get error. you need to get it yourself

#

.rtfm on_error

topaz rune
proud mason
#

thats the error object

topaz rune
#

yes yes

proud mason
#

but on_error doesnt have it

topaz rune
#

I have it

proud mason
proud mason
#

that is different from on_error

topaz rune
#

hm

proud mason
#

unless it gets handled by try except

topaz rune
#

so a thing like this should work?

#

still have error on my console, I think that I dont get it, im sorry

proud mason
#

i dont think you can register that event as a listener thinkCat

#

needs to be @bot.event or override by subclass

cyan quail
#

Out of curiosity, what other errors are you trying to catch?

proud mason
#

probably event listeners?

topaz rune
proud mason
#

yep (type(e), e, e.__traceback__)

#

e is the error object

topaz rune
#

traceback_str = ''.join(traceback.format_exception(type(error), error, error.__traceback__))

proud mason
#

oh yea so you can directly unpack the tuple into it

#

error_tup = sys.exc_info()
and then format_exception(*error_tup)

#

or yk what

#

there is a built in method for this

#

traceback.format_exc()

#

simple

solemn idol
topaz rune
solemn idol
topaz rune
solemn idol
proud mason
solemn idol
solemn idol
#

why is it white... o-o VSCode color scheme is usually different

#

this is cursed too

topaz rune
solemn idol
#

this is what it looks like for me

topaz rune
solemn idol
#

why is white?????

topaz rune
#

oh idk

solemn idol
topaz rune
# solemn idol pip list?
Package                Version
---------------------- --------------
aiohttp                3.8.4
aiosignal              1.3.1
async-class            0.5.0
async-timeout          4.0.2
asyncio                3.4.3
attrs                  20.3.0
beautifulsoup4         4.12.2
blinker                1.4
certifi                2020.6.20
chardet                4.0.0
charset-normalizer     3.1.0
cloud-init             20.4.1
configobj              5.0.6
cryptography           3.3.2
dbus-python            1.2.16
distro-info            1.0
fail2ban               0.11.2
frozenlist             1.3.3
gyp                    0.1
httplib2               0.18.1
idna                   2.10
importlib-metadata     1.6.0
Jinja2                 2.11.3
jsonpatch              1.25
jsonpointer            2.0
jsonschema             3.2.0
MarkupSafe             1.1.1
more-itertools         4.2.0
multidict              6.0.4
mysql-connector        2.2.9
mysql-connector-python 8.0.33
oauthlib               3.1.0
Pillow                 9.5.0
pip                    20.3.4
protobuf               3.20.3
py-cord                2.4.1
pycurl                 7.43.0.6
PyGObject              3.38.0
pyinotify              0.9.6
PyJWT                  1.7.1
pyrsistent             0.15.5
PySimpleSOAP           1.16.2
python-apt             2.2.1
python-debian          0.1.39
python-debianbts       3.1.0
PyYAML                 5.3.1
reportbug              7.10.3+deb11u1
requests               2.25.1
setuptools             52.0.0
six                    1.16.0
soupsieve              2.4.1
systemd-python         234
tk                     0.1.0
turtle                 0.0.1
typing-extensions      4.5.0
unattended-upgrades    0.1
Unidecode              1.3.6
urllib3                1.26.5
watchdog               3.0.0
wheel                  0.34.2
yarl                   1.9.2
zipp                   1.0.0
solemn idol
#

it looks fine.... I have honestly no idea why your vscode color scheme is so weird but hm

solemn idol
#

but your bot in general does work right? so it does go on, even while its white (when running it via vscode)

#

because if it doesnt then uh vscode might be a problem...

topaz rune
#

only color

solemn idol
#

oh well then idk

proud mason
#

pretty sure this is just a colour scheme thing

#

nothing to worry about

solemn idol
topaz rune
solemn idol
#

Welp idk whats wrong your code seems fine to me tbh

proud mason
# topaz rune

did you move the handler to the main file? you need to use @bot.event

topaz rune
#

gpt tell me this:

import traceback
from datetime import datetime
from discord.ext import commands

class CommandErrorHandler(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_application_command_error(self, ctx, error):
        await self.send_error_message(ctx, error)

    @commands.Cog.listener()
    async def on_command_error(self, ctx, error):
        await self.send_error_message(ctx, error)

    @commands.Cog.listener()
    async def on_error(self, event, *args, **kwargs):
        console = await self.bot.fetch_channel(1107314055322030120)
        await console.send(f'Une erreur est survenue lors de l\'événement {event} à {datetime.now().strftime("%H:%M:%S")} le {datetime.now().strftime("%d/%m/%Y")}.')
        traceback_str = traceback.format_exc()
        await console.send(f"Traceback:")
        await console.send(f"`py\n{traceback_str}\n`\n\n\n")

    async def send_error_message(self, ctx, error):
        traceback_str = ''.join(traceback.format_exception(type(error), error, error.__traceback__))
        if "You do not own this bot." in traceback_str:
            await ctx.respond("T'as pas le droit de faire ça :).")
        console = await self.bot.fetch_channel(1107314055322030120)
        await console.send(f'L\'utilisateur <@{ctx.author.id}> a effectué la commande `{ctx.message.content}` dans le channel <#{ctx.channel.id}> à {datetime.now().strftime("%H:%M:%S")} le {datetime.now().strftime("%d/%m/%Y")}.')
        await console.send(f"Erreur:")
        await console.send(f"`py\n{error}\n`")
        await console.send(f"Traceback:")
        await console.send(f"`py\n{traceback_str}\n`\n\n\n")

what do u think abt it

proud mason
#

ngl dont use gpt

topaz rune
#

what is the ctx.message.content equivalent for the / commands pls?

solemn idol
#

Quick question, what faulty code can I use to recreate a quick HTTP error .-.

topaz rune
topaz rune
#

oh

#

mbmb

proud mason
#
  1. checking error based on string in traceback pogbruh
topaz rune
# solemn idol pycord http error lol
@bot.command()
async def faulty_command(ctx):
    try:
        # Trying to fetch a non-existent channel.
        channel = await bot.fetch_channel(123456789012345678)
    except discord.HTTPException as e:
        # Handle HTTPException
        await ctx.send(f"An HTTPException has occurred: {e}")
solemn idol
#

thanks

proud mason
topaz rune
# proud mason 1) as i said, `on_error` cant be in a cog. the others can be 2), no need to fetc...
@bot.event
async def on_error(event, *args, **kwargs):
    console = await bot.fetch_channel(1107314055322030120)
    await console.send(f'Une erreur est survenue lors de l\'événement {event} à {datetime.now().strftime("%H:%M:%S")} le {datetime.now().strftime("%d/%m/%Y")}.')
    traceback_str = traceback.format_exc()
    await console.send(f"Traceback:")
    await console.send(f"`py\n{traceback_str}\n`\n\n\n")

am I good there?

proud mason
#

looks ok

#

except point 2

#

and 5

#

also, codeblock is ```
not `

topaz rune
#

what is partial_channel?

topaz rune
proud mason
#

ah ok

topaz rune
proud mason
topaz rune
proud mason
#

simple use-

channel = bot.get_partial_messageable(id)
await channel.send(...)
proud mason
#

sending message only needs the channel id

topaz rune
proud mason
#

which is slow

proud mason
#

you get all the stuff from the channel like perms etc

#

which isnt needed for sending messages

topaz rune
#

ok, so my last problem (I hope) is this:

ctx.message.content

error:

AttributeError: 'NoneType' object has no attribute 'content'
#

maybe I should use ctx.command.name?

#

fck that's feels good

#

thanks yall

#

💙

proud mason
#

btw i would put both the messages in the same message

proud mason
#

yea

#

just use \n

topaz rune
#

I can do a list and send with for el in list

proud mason
#

otherwise it will be spammy

#

eh no

#

send a single message

topaz rune
#

ok

proud mason
#

difference of just 3 lines shrug

topaz rune
#

as you want ouichef

proud mason
#

😂

topaz rune
#
@bot.event
async def on_error(event, *args, **kwargs):
    traceback_str = traceback.format_exc()
    await console.send(f'Une erreur est survenue lors de l\'événement {event} à {datetime.now().strftime("%H:%M:%S")} le {datetime.now().strftime("%d/%m/%Y")}.')
    await console.send(f"Traceback:\n`py\n{traceback_str}\n`\n\n\n")

async def send_error_message(ctx, error, command_content):
    traceback_str = ''.join(traceback.format_exception(type(error), error, error.__traceback__))
    if "You do not own this bot." in traceback_str:
        await ctx.respond("T'as pas le droit de faire ça :).")
    await console.send(f'L\'utilisateur <@{ctx.author.id}> a effectué la commande `{command_content}` dans le channel <#{ctx.channel.id}> à {datetime.now().strftime("%H:%M:%S")} le {datetime.now().strftime("%d/%m/%Y")}.')
    await console.send(f"Erreur:\n`py\n{error}\n`\nTraceback:\n`py\n{traceback_str}\n`\n")
#

good now?

#

only 2 message

#

🙂

#

ty

proud mason
#

better prayadge

topaz rune
#

I dont want to have commands with prefix

#

I want all of em /

#

thats why idc

proud mason
#

lol

proud mason
topaz rune
proud mason
#

better to check using classes

violet heron
#

how can i specify a user with the purge command?

proud mason
#

In the purge method

#

.rtfm purge

violet heron
#

ive tried somehting like that

#

await channel.purge(limit=numbers, check=message.author==user)

#

where numbers is the limit, and user is the message author (deleting messages by the person who called the command)

#

but I get AttributeError: 'Message' object has no attribute 'purge'

proud mason
#

The check is a function

#

So smth like lambda m: m.author==user

violet heron
#

ahh

proud mason
#

Also, how did you define channel

violet heron
#

my brain died and i had channel = message

#

fixed to channel = message.channel

#

thank u :)

proud mason
#

Lol

tulip ledge
jaunty raft
#

can someone explain why?

young bone
jaunty raft
#

sure

#
aiofiles            23.1.0
aiohttp             3.8.4
aiomysql            0.1.1
aiosignal           1.3.1
ajsonrpc            1.2.0
anyio               3.6.2
async-generator     1.10
async-timeout       4.0.2
attrs               23.1.0
beautifulsoup4      4.12.2
blinker             1.6.2
bottle              0.12.25
certifi             2023.5.7
cffi                1.15.1
charset-normalizer  3.1.0
click               8.1.3
clipboard           0.0.4
colorama            0.4.6
discord-protos      0.0.2
emoji               2.2.0
exceptiongroup      1.1.1
Flask               2.3.2
frozenlist          1.3.3
googlesearch-python 1.2.3
h11                 0.14.0
idna                3.4
itsdangerous        2.1.2
Jinja2              3.1.2
MarkupSafe          2.1.2
marshmallow         3.19.0
multidict           6.0.4
outcome             1.2.0
packaging           23.1
pip                 23.1.2
poe-api             0.3.1
protobuf            4.23.0
py-cord             2.4.1
pycparser           2.21
pyelftools          0.29
PyMySQL             1.0.3
pyperclip           1.8.2
pyserial            3.5
PySocks             1.7.1
python-dotenv       1.0.0
python-socks        2.3.0
requests            2.30.0
selenium            4.9.1
semantic-version    2.10.0
sniffio             1.3.0
sortedcontainers    2.4.0
soupsieve           2.4.1
starlette           0.26.1
tabulate            0.9.0
trio                0.22.0
trio-websocket      0.10.2
urllib3             1.26.15
uvicorn             0.22.0
websocket-client    1.5.1
Werkzeug            2.3.4
wsproto             1.2.0
yarl                1.9.2
youtube-dl          2021.12.17
young bone
jaunty raft
#

got it

#

yeah it should work now

#

tho where is discord.ApplicationContext?

#

is it moved?

young bone
#

what?

jaunty raft
#

like discord slash command context

proud mason
jaunty raft
#

valid

proud mason
#

yes

jaunty raft
#

so my intellisense is wrong?

#

if thats the case then

young bone
#

?

jaunty raft
#

I just restart my pc

young bone
#

why?

jaunty raft
#

idk intelisense not doing his jobn

young bone
#

But you know basic python? saisneaky

jaunty raft
#

yeah but discord.ApplicationContext

#

nevermind

#

its doing its job

#

thanks guys

proud mason
proper sundial
#

Does the default built in help command work for slash commands or do I need to do that myself? I've seen it mentioned on the Pycord guide but i don't know if it works for slash commands also.

silver moat
proper sundial
#

Alright then, fair enough.

fervent cradle
#

is it possible to have a requirement for a file with a slash command?

fervent cradle
#

so when a user runs a slash command

#

e.g. /upload, they add a file

silver moat
#

yes, see

fervent cradle
#

ive been looking on the docs but cant find anything about it

#

unless im just blind lol

young bone
#

file: discord.Attachment

silver moat
fervent cradle
#

oh, that works with slash command?

young bone
#

.tias

winter condorBOT
fervent cradle
#

oh, thank you

silver moat
young bone
#

ye

fervent cradle
#

i tried includign the option when defining the function too

fervent cradle
#
@slash_command(name="vdf")
    async def vdf(ctx: discord.ApplicationContext, attachment: option("VDF file", discord.Attachment, description="Your VDF file", required=True)):
        if attachment:
            file = attachment
            if file.filename != "config.vdf":
                return await ctx.respond("file is not a config.vdf")
            else:
                file = file.save()
                file = file.readlines()
                print(file)
#

its inside a cog if that mattters

#

i always remememberd option ot have a capital O?

#

but in that example it doesnt

cyan quail
#

you should be using the capitalized version there

fervent cradle
#

ah okay thansk

cyan quail
#

it's only lowercase if you use the decorator @option

#

also the type should be first, then you pass name= to change the name

#

option names have to be lowercase without spaces

fervent cradle
#

its been a while since ive worked with options

#

im pretty rusty now lol

cyan quail
#

it's fine, just gotta remember the restrictions

fervent cradle
#

for some reason it still doesnt show the option

cyan quail
#

did you restart?

fervent cradle
#

this is my new code:

silver moat
fervent cradle
#
    @slash_command()
    async def vdf(ctx: discord.ApplicationContext, attachment: Option(discord.Attachment, name="vdffile", description="Your VDF file", required=True)):
        if attachment:
            file = attachment
            if file.filename != "config.vdf":
                return await ctx.respond("file is not a config.vdf")
            else:
                file = file.save()
                file = file.readlines()
                print(file)
fervent cradle
cyan quail
#

is this inside a cog?

fervent cradle
#

how i sent it

silver moat
#

try commenting out the command, run the bot, un-comment out the command, and re-run the bot. finally, restart your discord app

fervent cradle
#

yesi

#

alright thanks

cyan quail
#

first arg needs to be self

fervent cradle
#

oh yeah

silver moat
#

that too

fervent cradle
#

its 10pm i havent ate maybe i should eat and get some sleep 😅

#

yup its wokring with the first arg as self

#

facepalm i completely forget about that

#

thank you

cyan quail
#

allgood

fervent cradle
#

I have a command that will send an embed with two buttons to a channel. When I select one of these buttons I want it to DM the original command user. How can I do this?

class requestAccept(discord.ui.View):
    async def on_timeout(self):
        for child in self.children:
            child.disabled = True
        await self.message.edit(view=None)

    @discord.ui.button(emoji="✅", label="Accept", style=discord.ButtonStyle.grey)
    async def first_button_callback(self, button, interaction):
        user = await discord.Bot.fetch_user(None)
        user.send("Accepted")
        await interaction.message.edit(view=None)
        self.stop()

    @discord.ui.button(emoji="⛔", label="Deny", style=discord.ButtonStyle.grey)
    async def second_button_callback(self, button, interaction):  
        await interaction.message.edit(view=None)
        self.stop()
proud mason
#

Store it on a self variable

#

Don't forget to call super init

#

Then in the callback just do await self.author.send(...)

#

Oh and pass ctx.author when creating the view

fervent cradle
#

Worked, thank you!

topaz rune
#

Hiii my friends 🙂

@commands.slash_command(
        name="xp", description="Commande qui affiche l'xp d'un utilisateur"
    )
    @option(
        name="user",
        description="L'utilisateur dont vous voulez voir l'xp",
        required=False,
        type=discord.User,
    )
    async def xp(self, ctx, user=None):
        initial_response = await ctx.respond("Création de la banniere en cours...")
        #my code
        await initial_response.edit(content=" ", file=discord.File("/srv/barman/bann_xp/xp_bann.gif"))

error:

discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'Interaction' object has no attribute 'edit'
#

how can I edit my first response please guys?

proud mason
winter condorBOT
#

Target not found, try again and make sure to check your spelling.

proud mason
#

Oops

#

.rtfm context.edit_original

winter condorBOT
#

Target not found, try again and make sure to check your spelling.

proud mason
#

Try await ctx.edit_original_response
If not then ctx.interaction.edit_original_response

cedar bluff
#

How do I make embedded pages? What I mean is that the person clicks the button not reaction and it goes to the next page or back a page. I tried the guides but it didn't really help much.

cedar bluff
proud mason
cedar bluff
#

I'll give it a shot.

proud mason
#

you can always build your own if you want

#

but thats probably more effort doggokek

cedar bluff
#

How do I send the paged embeds?

proud mason
cedar bluff
#

thx.

proud mason
#

paginator.respond if interactions

cedar bluff
#

hmm, weird error:

#
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: expected Context not <class 'discord.commands.context.ApplicationContext'>```
cedar bluff
#

It's a bit big but... ```Traceback (most recent call last):
File "/home/runner/Spongebot/venv/lib/python3.10/site-packages/discord/commands/core.py", line 124, in wrapped
ret = await coro(arg)
File "/home/runner/Spongebot/venv/lib/python3.10/site-packages/discord/commands/core.py", line 980, in _invoke
await self.callback(ctx, **kwargs)
File "main.py", line 131, in testing
await paginator.send(ctx)
File "/home/runner/Spongebot/venv/lib/python3.10/site-packages/discord/ext/pages/pagination.py", line 973, in send
raise TypeError(f"expected Context not {ctx.class!r}")
TypeError: expected Context not <class 'discord.commands.context.ApplicationContext'>

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
await ctx.command.invoke(ctx)
line 375, in invoke
await injected(ctx)
line 132, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: expected Context not <class 'discord.commands.context.ApplicationContext'>```

proud mason
#

hmm thats weird

#

oh wait

#

you are using slash cmds

cedar bluff
#

yeah.

proud mason
cedar bluff
#

now i got raise ApplicationCommandInvokeError(exc) from exc discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: expected Interaction or BridgeContext, not <class 'discord.commands.context.ApplicationContext'>

young bone
#

what is the py-cord version?

cedar bluff
proud mason
#

update to 2.4.1

cedar bluff
#

done.

proud mason
cedar bluff
#

great.
another error

discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: 'Interaction' object is not callable```
proud mason
#

just do await paginator.respond(ctx.interaction)

#

thats it

cedar bluff
#

oh ok, i'll try it now. idk why i did await ctx.interaction(paginator) lol

proud mason
#

lmao

cedar bluff
#

It worked, thanks!

silver moat
silver moat
proud mason
cedar bluff
#

Now time to make this an embed for something...

cedar bluff
proud mason
#

??

cedar bluff
#

the guide you linked. idk what to do with the my_pages which contains the embed.

signal topaz
#

Um if an argument is used to mention a user, how can you fetch the id of the user?

cedar bluff
violet heron
#

How to set nick of user

#

Member.edit and member.nick don’t work

stiff crest
violet heron
#

What should the member variable be?

#

I have it as user attribute

stiff crest
#

i have all intents btw

frank thistle
#

Is there a way to have slash command options which are required only in certain cases? I assume not right?

For example

Command: /balance
Options 1: View, Withdraw, Deposit
Option 2: Amount

/balance View
/balance Withdraw [Amount]
/balance Deposit [Amount]

Make the [Amount] required when the first option is not equal to View

jaunty raft
#

hey guys how do I use ctx.defer()?

frank thistle
jaunty raft
#

and then await ctx.respond()?

frank thistle
#

No, then you followup

#

for example: await ctx.followup.send

jaunty raft
#

so like:


async def cmd(ctx: discord.ApplicationContext) -> None:
  await ctx.defer()
  await ctx.followup.send("defer")
frank thistle
#

yes

jaunty raft
#

and for how long will it wait? or like hold

frank thistle
#

It wont hold for any amount of time if you dont have any code in between the send

#

Defering just means it wont say Interaction Failed once there has been no response for longer than 3 seconds

jaunty raft
#

ohh makes sense

#

thanks got it

violet heron
frank thistle
#

Course

violet heron
#

I have await member.edit(nick=“nick”)

#

With member being a user object

#

Code returns error “‘User’ object has no attribute ‘edit’”

frank thistle
#

Ok? and whats your problem with that

#

The User object, has no attribute edit so you need a Member object

proud mason
#

how did you get the member object?

frank thistle
#

You can get a member object by looping over guild.members or by using get_member

proud mason
violet heron
#

Member = await client.fetch_user()

proud mason
#

yea no

violet heron
#

Inside parentheses is an id

proud mason
#

use guild.get_member

frank thistle
violet heron
frank thistle
#

You can also make it an option if its a slash command

frank thistle
#

eg discord.Option(discord.Member, required=True

proud mason
frank thistle
#

I do it a lot, defer things and never actually followup to them

proud mason
#

you could rather just send Ok! or smth lol

frank thistle
#

Ya but thats ugly

#

esp when using buttons and dropdowns etc

#

Imagine, clicking a button which takes some time to process and it says 'Okay!' every time you click it 😂

proud mason
frank thistle
#

Yeah no, I dont really defer ever for commands

proud mason
#

defer and ignore is actually the best way for components

frank thistle
#

YOUR BOT IS THINKING Loading

frank thistle
proud mason
#

you could use slash cmd groups

#

that would achieve a similar functionality

frank thistle
#

Its nicer to have one command with the options tho :(

proud mason
frank thistle
#

Ah well, will just have to keep amount optional

proud mason
#

discord limitation

violet heron
#

@proud mason it still not working T-T

solemn idol
#

wasn't there a way to make it so that if the buttons expired you could make the bot reply if someone still tried to press one?

frank thistle
violet heron
#

One sec

frank thistle
solemn idol
solemn idol
cyan quail
solemn idol
frank thistle
#

yes

cyan quail
#

if you actually want them to expire then either remove the buttons or disable them and edit the message

frank thistle
#

Or use self.stop()

violet heron
#

` Given p = user_id (tested and is an actual id)
K = string for nick
guild=message.guild
member= guild.get_member(p)
print(message.author)
print(member)
await member.edit(nick=k)
await message.reply(f"Nickname updated for {p.display_name}") ```

#

Mobile moment

violet heron
solemn idol
#

So I could just define my timeout to be None in the class of the ui?

violet heron
#

Guild.get_member returns none

cyan quail
#

but this won't protect against restarts, you'd have to make it persistent

errant craneBOT
#

Here's the persistent example.

violet heron
#

And fetch_user worked and gave a user object, but it’s still reported as user object not having edit attribute

cyan quail
#

because it doesn't

#

User and Member are different

violet heron
#

Ah

cyan quail
#

just checking, what happens when you print guild.members

violet heron
#

[<Member id=1087100813593301053 name='asuka' discriminator='0226' bot=True nick='asuka' guild=<Guild id=1050189593628119130 name="Cat's Cafe" shard_id=0 chunked=False member_count=55>>]

#

Hmm

cyan quail
#

is that correct?

solemn idol
violet heron
cyan quail
#

but presumably that isn't all your members

#

have you enabled the members intent?

violet heron
#

All intents are enabled

cyan quail
#

in code as well?

cyan quail
#

discord's structure of interactions is pretty different to how we present it to the user

cyan quail
#

i'll be real

#

idk

solemn idol
#

LOL

#

honest xD ill take it

violet heron
cyan quail
#

ohok havefun

violet heron
#

So now it’s giving missing permissions for the member.edit line

cyan quail
cyan quail
#

you can't edit the nickname of someone with a higher role than you

#

or the guild owner

violet heron
#

Oh

#

Yeah maybe nicking myself like an idiot is bad

cyan quail
#

rip LOL

violet heron
#

Ok now

#

It’s not returning an error but their nick isn’t being updated

#

Prolly on my end again

#

Got it to work tysm

coarse cargo
#

Its possible to update the choices list of a command after giving it one without need to restart? I have a command that uploads a file to a folder and i want it to show up as choice in the command but it doesn't. Any solutions?

errant craneBOT
#

Here's the slash autocomplete example.

coarse cargo
coarse cargo
#

General question, it's better like this:

def get_datanamesfile():
    with open('data/data_names.json') as data_names:
        json_data = json.load(data_names)
        return json_data


def get_keys():
    with open('data/data_names.json') as data_names:
        json_data = json.load(data_names)
        keys = [key for key in json_data.keys()]
        return keys


def get_filepath(name):
    with open('data/data_names.json') as data_names:
        json_data = json.load(data_names)
        filepath = json_data[name].get('filepath')
        return filepath

Or like this

with open('data/data_names.json') as data_names:
    json_data = json.load(data_names)

def get_datanamesfile():
        return json_data


def get_keys():
        keys = [key for key in json_data.keys()]
        return keys


def get_filepath(name):
        filepath = json_data[name].get('filepath')
        return filepath

So open the file 1 time or multiple times

cyan quail
#

but you still need to save it back after

alpine kernel
#

had the idea to store discord user id's as a primary key in a sqlite db, but looking at the highest value user id in my dataset and it's ~1x10^18 and max int size in sqlite is ~9x10^18, any thoughts if that's a bad idea? and if so alternative methods?

cyan quail
#

that's how discord does it on their API already

#

the only reason we use ints is because python supports large ints pretty cleanly

alpine kernel
#

mmm k, just was aware of performance differences in int vs string

dry fulcrum
#

Quick question, I currently have a bot with a few cogs using application command, the bot loaded all other cogs fine, but on 1 specific cog, it cannot seem to register any of the command, in a debug session the command doesn't show up at all in the AllCommand list, but the cog itself show on the cog list, is there any common cause for this issue?

#

Current amount of cog is 7 cogs, total amount of command registered is 47 commands

winter condorBOT
# dry fulcrum Quick question, I currently have a bot with a few cogs using application command...

Checklist for Application Commands Not Showing Up:
• Does your bot have the application.commands scope?
• Are you loading cogs before on_ready and on_connect?
• Is on_connect not overridden?
• Did you update to the newest version of py-cord (tag: install)?
• Is User Settings > Accessibility > Chat Input > Use legacy chat input turned off?
• Did you share your code and errors?
• Do you still have libraries that conflict with the discord namespace (e.g. discord.py)?

proud mason
#

Points 2 and 3 are important

dry fulcrum
#

All are yes, except the share your code part, which I don't get, like share it here?

#

Actually the cog are loaded within on_ready

#

And upon further testing, when I removed all cog except for this one, then the commands show up

#

Could it be the command limit?

proud mason
dry fulcrum
#

yea, like the first line of on_ready

#

is loading the cog

proud mason
#

you should load your cogs before on ready

#

outside of it

dry fulcrum
#

one of my cog actually need the user id from the bot object

proud mason
#

hmm

dry fulcrum
#

but the issue is resolved no

proud mason
#

where does it need it?

dry fulcrum
#

the issue was discord not actually pulling the changes down, or my client not pulling

#

I executed a command that doesn't exist anymore, and volla, the new commands all showed up

proud mason
#

well cmds are synced before ready. if you load your cmds after ready, then they wont be sync

#

if you run a cmd and pycord finds a difference in registered vs local, it willl. resync

dry fulcrum
#

any way to manually do a sync then?

proud mason
#

ngl load before ready

proud mason
#

does it need the id in the init?

dry fulcrum
#

It does, the init for a cog initiate a connection to another service, which utilize the bot id as a parameter

proud mason
#

you could use a special method and call it on ready, which sets and uses the id

proud mason
dry fulcrum
#

it's in a cog so..

#

i can't exactly put a second on_ready in a cog, right?

proud mason
#

You can have event listners in cogs

dry fulcrum
#

wait, so i can have 2 on_ready(s)?

proud mason
#

yes

dry fulcrum
#

O.o

#

okay that changes a lot then

proud mason
#

1 cog can only have 1 iirc

#

.rtm cog.listener

#

.rtfm cog.listener

winter condorBOT
proud mason
#

2nd one

dry fulcrum
#

huh..

#

i thought there can only be 1 event listener for each event

proud mason
#

in the main file, yes

dry fulcrum
#

wait, so for example, if i have 2 on_ready(), one in a cog, and one in the main file, both of them will triggers with the corresponding code?

#

on_message(), i mean

#

sorry

proud mason
#

Usage would be-

class MyCog(...):
  
  @commands.Cog.listener()
  async def on_ready(self):
    print("hi")
dry fulcrum
#

one more question, so for the on_message, if i have more than 1 of them, in which one should i put the process_message_command? Or do I not need to use that at all now? (I don't use prefix command anymore, just slash commands)

#

i definitely butchered the messagecommand stff, didn't i..

proud mason
dry fulcrum
#

Alright, i can skip that one then

#

thank you for your help

proud mason
#

np

somber pelican
#

what could be the cause for this?

#

the stack doesn't show anything about my files, just discord/client.py

full basin
obtuse juncoBOT
#

If you're getting the [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1108) error on a Windows host do the following:

Download and install this certificate here: https://crt.sh/?id=2835394
--> It can be installed by double-clicking the file and installing it to Local Computer, download link location: https://beans-took-my-kids.reeee.ee/38qB2n.png

For those curious, it was caused by this:
https://support.sectigo.com/Com_KnowledgeDetailPage?Id=kA03l00000117LT

somber pelican
#

it wasn't a windows host, it's on a linux vps

somber pelican
full basin
#

Google the error. High chance its on stackoverflow

vital timber
#

Hello friends. Quick Q here

#

If a user initiates a DM with my bot and my bot responds to it - is it still at risk of triggering Discord's DM softban?

grizzled sentinel
#

I wouldn't think so but I can try to verify

vital timber
#

How can we verify? I wouldn't want to take up much of your time

grizzled sentinel
#

I just posted the question in ddevs discord.

#

Just to be sure. The user would not be using a slashcommand it would be a message?

vital timber
#

Correct

#

Would triggering a slashcommand in a DM make a difference if the response is a message?

#

Or if the response is asynchronous - like say, a timer - so the response wouldn't be within the context of the same Interaction

full basin
#

The only attribute you lose in a dm context is the guild

#

And guild related stuff ofc

hardy crescent
#

How do i prevent blocking code when i create a image with Pillow?
it takes 3sec and blocks all other tasks in the bot

full basin
#

Use an async library

hardy crescent
#

Could you recommend one where i can join 3 images in to 1 big image?

grizzled sentinel
vital timber