#Basic Pycord Help

1 messages · Page 23 of 1

oblique sable
#

im looking again to be sure

#

this should be good right? im doing that for every view

#

is the view timeout the same one than the tokens ?

#

because here it says the default timeout is 180 so its not 15 minutes, maybe its not the same thing we re talking about

#

sorry to bother lol, its just that i keep getting this error for a long time

errant trout
#

remove default=True

errant trout
urban zealot
# errant trout remove `default=True`

Thank you this stops it from defaulting back to general but do you know of anyway that I can have it so that if I select one of the options then it'll keep that as selected item until i choose another and then it'll change what was happening with the default thing to that selected option?

errant trout
#

what is it doing currently?

oblique sable
errant trout
#

update what manually

oblique sable
#

im having a panel where users can do things on it, so if an user doesnt do anything for 15 minutes then the buttons are not working since it timeouts right

#

my problem was sending ephemeral messages

urban zealot
oblique sable
#

the buttons work i mean, its the ephemeral messages that crash, basically sending a followup

errant trout
errant trout
rugged lodgeBOT
#

Here's the persistent example.

errant trout
#

and you use the persistent method to keep it working through restarts

oblique sable
errant trout
#

so what's wrong there

#

interaction failed?

oblique sable
#
le "c:\Users\billy\Desktop\disco\cogs\projects\audio.py", line 151, in generate_audio
    await pnl.ephemeral(f"Audio block **{pnl.audio_selected[0]}** generated successfully!", file=discord.File(pnl.proj.path + f"/audio/{pnl.audio_selected[0]}.wav", filename=f"{pnl.audio_selected[0]}.wav"), expire=300)
  File "c:\Users\billy\Desktop\disco\cogs\__init__.py", line 93, in ephemeral
    return await self.panel.send_followup(content=text, file=file, ephemeral=True, delete_after=expire)
  File "C:\Users\billy\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\webhook\async_.py", line 1776, in send
    data = await adapter.execute_webhook(
  File "C:\Users\billy\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\webhook\async_.py", line 222, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 401 Unauthorized (error code: 50027): Invalid Webhook Token

i am trying to send a followup as an ephemeral

errant trout
#

uhhhh

#

what is self.panel

oblique sable
#

panel is the interaction

#

thats an old traceback haha, renamed it to interaction now

#

but i keep getting this error when trying to send followups

errant trout
#

you're always using a single interaction object? or does this refresh

oblique sable
#

maybe its the 15 minutes timeout

oblique sable
errant trout
#

would be easier to figure out with the full code

#

if a user presses a button and you respond to the interaction in under 15 minutes then that wouldn't happen, unless you're actually taking that long?

oblique sable
#

in fact it does not take that long

oblique sable
# errant trout would be easier to figure out with the full code

its very very big, i have a panel class where the interaction keeps getting updated
also this is the reason i cant save persistent views from what i saw, because each view is particular to an user so i would have to save them in a database or something to then rebuild the panel instance

#

but thanks for your help, now i get it so i will re look at my whole code, i did something wrong then

errant trout
#

can you just send the ephemeral function?

oblique sable
#

yes

#
async def ephemeral(self, text: str = "", embed=None, file=None, expire: int = 10):
        if embed and file:
            return await self.inter.respond(content=text, embed=embed, file=file, ephemeral=True, delete_after=expire)
        elif embed:
            return await self.inter.respond(content=text, embed=embed, ephemeral=True, delete_after=expire)
        elif file:
            return await self.inter.respond(content=text, file=file, ephemeral=True, delete_after=expire)
        else:
            await self.inter.respond(content=text, ephemeral=True, delete_after=expire)

(not sure i could have these parameters as None)

#

self.inter is the interaction that is always updated on a button press

errant trout
#

oh you're using the new respond function ic

oblique sable
#

honestly i can use whatever if it works

#

i tried followup i tried lots of things

errant trout
#

hmmm

#

what about the generate_audio function?

#

if it's too big it'll convert to a text file anyway, which is fine

oblique sable
#

i will shorten it to essential

errant trout
#

fair enough

oblique sable
#

the audio is first resetting self.inter to the actual Interaction
then it generates audio with elevenlabs api, and sends the generated file as an ephemeral message
once it sends the generated file, it updates the view to show that audio is generated

#

and the code

#
async def callback(self, interaction: Interaction, cog: Type[Any], run_func = None, end_func = None, cog_is_func = False):
        self.inter = interaction
        if cog_is_func:
            return await cog(self)
        
        if (not run_func is None) and run_func != 0:
            tcb = await run_func(self)
            if tcb: # not used yet
                return 
        if isinstance(cog, UI.Modal): # is a modal
            return await self.send_modal(cog)
        cmptype = interaction.data.get("component_type")
        if run_func is None and cmptype == SelectCmp:
            await self.execute_cog(cog)
        await self.init_cog(cog)
        await self.edit()

        if not end_func is None:
            await end_func(self)

it runs this function with the interaction, my custom cog (self.edit() is a function that edits the interaction with the data from my cog)
run_func is generating the audio and sending the ephemeral message, so nothing too much

#

i got a pretty complicated system, do you need anything more?

errant trout
#

hm, so how long does this normally take (without errors)?

oblique sable
#

like 5 seconds

#

maximum

errant trout
#

did you ever defer?

oblique sable
#

no i did not, can that be the reason?

errant trout
#

try await interaction.defer(ephemeral=True) before your heavier functions

oblique sable
#

okay okay thanks, btw i will be able to edit it after right ? wont cause any issues

#

im running some tests but i need to wait 15 minutes each time 😭

errant trout
#

should be fine

#

interaction.respond and interaction.edit in 2.5 already account for defers

#

(i hope anyway, i implemented it like last june and haven't used it since)

oblique sable
#

oh gosh, so it should work anyways

#

anyways i understand why it does that, most likely a bug from my code because it should not happen otherwise

#

is there anywhere i can donate you?

errant trout
#

pls don't im fine LOL

#

i would have realised it was defer earlier but the error confused me

#

in general, if your function takes more than 3 seconds you have to defer interaction

oblique sable
oblique sable
#

because it works for anything else

#

i just think i messed up somewhere so im checking again, thank you for your help!

errant trout
#

defer automatically?

oblique sable
#

yeah because it takes 10s somtimes

#

i never defer it

errant trout
#

if you're unsure on how long it takes, then always defer

oblique sable
#

okay will do !

little cobalt
errant trout
frail ocean
#

There is nothing called Type

lofty parcel
frail ocean
frail ocean
#
    if interaction.user.voice.channel:
AttributeError: 'NoneType' object has no attribute 'channel'```
How can i grap this?
If i do:
```py
if not interaction.user.voice.channel:

The same error comes

lofty parcel
#

Check first for user.voice?...

deft hull
#

is there a shortcut to return a list of only TextChannels from a guild

#

instead of return a full list and having to remove every channel that isn't a TextChannel

#

Also, how do I detect the class type of a channel

oblique sable
#

hey guys how can i delete the last response of an interaction? and will it work if i want to delete it like 30 minutes later?

lapis dock
lapis dock
#

Interaction tokens expire after 15 min so 30 min will not work

oblique sable
#

so the solution would be to defer it right?

lapis dock
#

Defer still only gives up to 15 minutes

oblique sable
#

damn

#

but ii only want to delete the message, like a normal message, why wouldnt that be possible?

#

i mean manually i can delete it even after a few hours, maybe i can stack the id of the interaction message or something and after fetch the message and delete it?

lapis dock
#

You would have to have the message ID, you can get that via interaction.message it it was the first one I think

oblique sable
#

okay thanks!

deft hull
#

How do I get the channel which system messages are posted (i.e. new member/nitro boost)

#

this thing

frail ocean
lofty parcel
deft hull
#

thank you!

oblique sable
oblique sable
#

its in a class

#

i have a panel basically

#

this is a function that is supposed to delete the panel if the user opens a new one

#

but im having an issue where if the user doesnt touch the panel for more than 15 minutes, then reopens a new one, the old one is not deleted and i get this error

deft hull
#

What objects does discord.TextChannel.can_send accept

#

I'm trying to check if the bot can send messages on a channel

lofty parcel
oblique sable
#

Okay thanks

lofty parcel
#

.rtfm TextChannel.can_send

sly karmaBOT
lofty parcel
#

Or it does. Probably the same stuff as a normal channel.send

sage tendon
#

thats mediocre documentation tho

oblique sable
#

any idea guys?

oblique sable
#

something like that?

#

if thats the way to do it, it would be nice to maybe have a direct function attribute to do it directly

sage tendon
#

can't you just call delete on the original response?

oblique sable
#

when i do that after 15 minutes

#

i get this error

sage tendon
#

hm

lapis dock
oblique sable
#

okay thx

frail ocean
#

How can i create modals like this

errant trout
#

replace view with modal and assign callback, then add_item takes inputtext instead

frail ocean
#

Thx

deft kestrel
#

how to follow a channel in pycord?

fresh totem
#

Copy pasted code from a past project which has been working fine

    titlePerm = {guild.default_role: discord.PermissionOverwrite(read_messages=False, send_messages=False, view_channel=True),
                 guild.me: discord.PermissionOverwrite(read_messages=True, send_messages=True, view_channel=True)}

    NewsCategory: discord.CategoryChannel = await guild.create_text_channel(name="📰┊BitThreadz", overwrites=titlePerm, position=0)

and I'm getting this error:

    titlePerm = {guild.default_role: discord.PermissionOverwrite(read_messages=False, send_messages=False, view_channel=True),
                                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: PermissionOverwrite() takes no arguments
#

what am I missing

errant trout
fickle salmon
#

how do I make a long running command async? defer() doesn't work by itself, when the one command is running other commands time out

sage tendon
#

that will need some context

fickle salmon
#

isn't there a way to wrap a line in a new thread or whatever

sage tendon
#

like you have a slash command that needs time to execute?

fickle salmon
#

that's all I'm looking for

#

yeah, but just one line of that slash command is slow

sage tendon
#

code

fickle salmon
#
async def generate(self, ctx, prompt: Option(str, "Prompt")):
    """generate an image from a text prompt"""
    try:
        await ctx.response.defer()
    except:
        pass
    response = await ctx.respond("generating ...")
    try:
        result = await self.sd_generate(prompt) # slow line
    except ConnectionRefusedError as e:
        await response.edit(content="server is down, try again later")
        return
    except Exception as e:
        import traceback
        traceback.print_stack()
        await response.edit(content="server is down, try again later")
        return

    image = result.get("name")

    await response.edit(content=prompt, file=discord.File(image))```
sage tendon
#

thats a lot of try excepts

fickle salmon
#

ok

sage tendon
#

you can use ctx.defer btw

#

well if the sd_generate is actually async, it shouldn't block your other code
but as you described it it sounds like it isnt

fickle salmon
#

it's not

#

I need to make it async

sage tendon
#

are you making an API request in it?

#

if yes use aiohttp

fickle salmon
#

I just want to wrap that line in a new thread or whatever

sage tendon
#

no need

fickle salmon
#

yes need, it's blocking

sage tendon
#

are you making an API request?

fickle salmon
#

you're not answering my question

sage tendon
lapis dock
#

Bot.loop.create_task(code) might work

fickle salmon
#

self.bot?

lapis dock
#

👍

sage tendon
#

why not just make the API request async

fickle salmon
errant trout
sage tendon
#

are you self hosting it or what

#

lol

fickle salmon
#

yes

errant trout
fickle salmon
#

what is the exector?

#

None?

errant trout
#

None uses the default, should be fine

fickle salmon
#

hm I still get The application did not respond on the 2nd invocation

errant trout
#

idk that's meant to do exactly what you're looking for, runs a func in another instance/thread

fickle salmon
#

idk

sage tendon
#

try to use ctx.defer and not ctx.response.defer
might just be a shortcut but idk

errant trout
#

they're the same

sage tendon
#

actually, wait, you don't even need to defer

#

because you instantly respond anyway

errant trout
#

true

#

but their problem is the bot gets blocked regardless

#

(i hope you're not calling () it in run_in_executor)

fickle salmon
errant trout
#

so run_in_executor(None, self.sd_generate, prompt) still breaks it?

fickle salmon
#

yes

#

they're the same

#

hm now I'm getting Application Command raised an exception: AttributeError: 'coroutine' object has no attribute 'get'

#

what do I do with an awaitable

errant trout
#

...await it?

fickle salmon
#

I did

errant trout
#

do it again

fickle salmon
#

result = await result?

#

🙃

#

probably with ()

errant trout
#

isn't it because you made sd_generate async too

fickle salmon
#

that makes sense I think

#

async all the way down

errant trout
fickle salmon
#

ah so no parens 🤔

errant trout
#

like

fickle salmon
#

still times out...

#

what the heck

errant trout
#

thats how everything in the lib works, ctx.send() and await are separate

fickle salmon
#

should I try making a ThreadPoolExecutor or will that cause problems

errant trout
#

go for it

#

i think you need to dive into sd_generate , since that isn't the blocking function itself; it happens to run other blocking functions

fickle salmon
#

same issue 🙃

#

hm maybe

#

even if I move it further down it still errors

errant trout
#

ah... while true....

fickle salmon
#

can I use asyncio.ensure_future?

errant trout
#

ig just keep trying and see what sticks, not much experience here from me

fickle salmon
#

yeah not much here either 🙃

#

maybe loop.run_forever() and then loop.stop()?

#

no, nevermind

#

so I just added await asyncio.sleep(0.1) in the loop and I think that worked

#

well, it worked once. running a 3rd time still times out

oblique sable
#

hey, quick dumb question
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Context' object has no attribute 'respond'

i checked and Context has this attribute, what should I do instead?

#

await self.ctx.respond(embed=embed, view=self.view)

errant trout
#

send

shell radish
fickle salmon
oblique sable
#

i am in a class

fickle salmon
#

I know

#

just do await ctx.respond

errant trout
#

respond is only for slash commands, otherwise use send

oblique sable
fickle salmon
#

that too

oblique sable
errant trout
#

(they've passed ctx somewhere else)

oblique sable
#

but its in a class so dw, works now

#

another thing guys,

i am having this command

bot = Bot(command_prefix=commands.when_mentioned, intents=discord.Intents.all())

@bot.command()
async def menu(ctx: Context, custom_id: str = None):

is there a way to have this command work when i only mention the bot?
Now it only works when i do @mybot menu

errant trout
#

ehhh use on_message event then run the function there instead?

oblique sable
#

yeah thought about this, was wondering if there was a more intentional way of doing that 🤔

shell radish
#

or add a check

#

you can get the message with ctx.message

errant trout
#

they mean to bypass the command name and have it run directly on mention instead

oblique sable
#

yeah

errant trout
#

but at that point, why have it as a command

oblique sable
#

i would just like to have it run when the bot is mentionned, wasnt sure if there was a way of doing that without going through on_message

errant trout
#

well... on_message is how mentions are detected in the first place

oblique sable
#

yeah, i think i'll go directly with that, thx for clarifying

errant trout
#

also refer to this section in the FAQ to make sure your commands don't break

fickle salmon
#

added a longer sleep and it's totally working

errant trout
#

nice

deft hull
#

Running this gives me the error discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access

shell radish
#

you don’t have the permissions to send a message in that channel

deft hull
#

somehow the bot can still send messages

edgy girder
deft hull
#

Ye it seems my bot cannot view the channels mb

lofty hedge
lapis dock
#

I believe that discord allows the bot to send interaction responses in channels that it cannot send messages in or see. The bot will just not be able to send unprompted messages.

grizzled loom
errant trout
#

Only responses bypass perms; timeout edits generally won't work because chances are it's out of the response window, something like edit_original_response would still work but gotta be <15min

#

(If not that then presumably response.edit_message, but that's obviously a first response rather than something on timeout)

grizzled loom
lofty parcel
#

Do i need a session to edit a WebhookMessage?

#

I always get a Session closed error when trying to edit one.

deft kestrel
#

is there a way we can fetch a message through an attachment, i tried using the ids in the url, the first one corresponds to the channel id but the second one doesn't with the message apparently is there any way to get the message

loud kayak
#

The message ID where said attachment is on is the second ID in the url https://media.discordapp.net/attachments/1132206148309749830/1214371968128778271/image.png …

#

It’s better off to get the message ID from something else tho

lost ocean
#

i only need sevrer members intent, how do i define it here?

loud kayak
lost ocean
#

okay thanks a lot

fresh totem
fresh totem
# sage tendon show your package list
aiohttp                3.9.3
aiosignal              1.3.1
attrs                  23.2.0
certifi                2024.2.2
charset-normalizer     3.3.2
frozenlist             1.4.1
idna                   3.6
multidict              6.0.5
mysql-connector-python 8.3.0
pip                    22.3.1
py-cord                2.5.0
requests               2.31.0
setuptools             65.5.1
tabulate               0.9.0
urllib3                2.2.1
wheel                  0.38.4
yarl                   1.9.4
fresh totem
#

(Resending problem for context) 👇

Copy pasted code from a past project which has been working fine

    titlePerm = {guild.default_role: discord.PermissionOverwrite(read_messages=False, send_messages=False, view_channel=True),
                 guild.me: discord.PermissionOverwrite(read_messages=True, send_messages=True, view_channel=True)}

    NewsCategory: discord.CategoryChannel = await guild.create_text_channel(name="📰┊BitThreadz", overwrites=titlePerm, position=0)

and I'm getting this error:

    titlePerm = {guild.default_role: discord.PermissionOverwrite(read_messages=False, send_messages=False, view_channel=True),
                                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: PermissionOverwrite() takes no arguments
shell radish
#

full traceback?

fresh totem
#
Ignoring exception in command setup:
Traceback (most recent call last):
  File "\Lib\site-packages\discord\commands\core.py", line 131, in wrapped
    ret = await coro(arg)
          ^^^^^^^^^^^^^^^
  File "\Lib\site-packages\discord\commands\core.py", line 1013, in _invoke
    await self.callback(ctx, **kwargs)
  File "\Lib\site-packages\discord\commands\core.py", line 49, in setup
    titlePerm = {guild.default_role: discord.PermissionOverwrite(read_messages=False, send_messages=False, view_channel=True),
                                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: PermissionOverwrite() takes no arguments

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

Traceback (most recent call last):
  File "\Lib\site-packages\discord\commands\core.py", line 1130, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "\Lib\site-packages\discord\commands\core.py", line 376, in invoke
    await injected(ctx)
  File "\Lib\site-packages\discord\commands\core.py", line 139, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: PermissionOverwrite() takes no arguments

#

there you go

fresh totem
sage tendon
#

show your package list

little cobalt
sage tendon
#

ah mb

fresh totem
deft hull
#

i have a view which edits the message to something else upon timeout

#

how am i supposed to override this when finishing a command

granite pier
#

depends what do youmean by override

deft hull
#

oh ok

#

How do I change another button's appearance upon clicking a button

#

I know each button has custom ids but have no idea how to use them

granite pier
granite pier
#

show ur code

deft hull
sly ember
#

what can i do here guys?

granite pier
granite pier
#

as far as i see from error you probably using self.client

subtle moth
sly ember
subtle moth
#

We cannot predict your code

#

You'll need to show first

granite pier
#

but yeah without self as you should use callback interaction arg

sly ember
#

uid is a collum in my table and stands for "userid"

#

this is a new error btw the old one is fixed

lofty parcel
sly ember
#

sure

sly ember
lofty parcel
#

static methods do not take self

sly ember
#

ahh

lofty parcel
#

so your method actually takes 4 args

sly ember
#

yes, and instead of self i may use interaction right? to like connect to the db with "async with interaction.client...."

lofty parcel
#

that works too

sly ember
#
    @staticmethod
    async def get(interaction, mid: int, gid: int, uid: int):# -> list or None:
        async with interaction.client.pool.acquire() as conn:
            async with conn.cursor(aiomysql.DictCursor) as cursor:
                try:
                    data = await cursor.execute(
                        ("SELECT * FROM surveys_votes WHERE gid = %s AND mid = %s AND uid = %s", (gid, mid, uid)))
                    data = data[0]
                except (IndexError, TypeError):
                    return None
                return UserVote(data['mid'], data['uid'], data['gid'], data['vote'])

Do you think that is okay?

#

ahh and the vote arg, how could i add that in the function?

#

yea i somehow have the same error still think

lofty parcel
#

wdym vote arg

sly ember
#

i mean uid sorry, i dont understand how i can fix that error

#

its saying somethign with uid but idk what

lofty parcel
#

show the error?

sly ember
#

that one

lofty parcel
#

youre not passing interaction

sly ember
#

you mean UserVote.get(interaction)?

lofty parcel
#

and now youre missing the other arguments...

sly ember
#

oh hell nah 😅

#

hm

#

ahhhh

lofty parcel
#

this is basic python

#

you just gotta add a new arg

sly ember
#

yes yes wait is it UserVote.get(interaction.message.id, interaction.guild.id, interaction.user.id)?

lofty parcel
sly ember
#

ahhh

lofty parcel
#

man read your own method definition

#

you created the method

sly ember
#

okay, sorry i came back to coding after a long time, sorry!

lofty parcel
sly ember
#

yes you are right

sage tendon
#

ah yes, so much for descriptive variable names

sly ember
#

ah damn it, never seen an error like this one

#

    async def save(self, interaction) -> None:
        async with interaction.client.pool.acquire() as conn:
            async with conn.cursor(aiomysql.DictCursor) as cursor:
                return await cursor.execute(("INSERT INTO surveys_votes (gid, mid, uid, vote) VALUES (%s, %s, %s, %s)",                                                                      
                                             (self.gid, self.mid, self.uid, self.vote)))

its in this part

sage tendon
#

that doesn't look like the part that's causing it

#

somewhere something expects an object to get an id of but gets nothing

frail ocean
#

Is there a way to get emojis from servers in which the bot isnt in for stealing etc

sage tendon
#

not that I know

#

since you need to fetch the guild

sly ember
sage tendon
#

looks like it

sly ember
#

before i got an error saying that there is missing an "Interaction" in the brackets which i added then and got the current error

frail ocean
sage tendon
#

It's not possible for all I know

frail ocean
sage tendon
#

well then

frail ocean
sage tendon
#

that's not the issue since there'll obviously be an interaction to pass

subtle moth
#

You've made the entire sql query + the variables to a tuple and passed it as the first parameter

sage tendon
#

ruh

subtle moth
#

huh

sly ember
#

huh

#

ahh

subtle moth
#

Can you fix your parentheses and see if it works

sly ember
#

sure!

sly ember
sage tendon
#

in the execute

sly ember
#

you mean the 2 start brackets?

sage tendon
#

yes

sly ember
#

ahhh

#

it worked halfly, the button response works now, it says which button i voted for, but the percent should change, which it doesnt

sage tendon
#

then make it change lol

sly ember
#

sure!

sage tendon
#

somewhere you aren't editing that value shrug

sly ember
#

😅

#

staticmethods dont take self right?

#

yea 👍

sage tendon
#

man i have never used any non discord decorator idfk

sly ember
#

what?

frail ocean
#

Is there a way to get messages which got hold back from automod?

sage tendon
#

They are normal messages in the automod channel

sage tendon
sly ember
sage tendon
#

yes

sly ember
#

but what do you mean with that message, im not really good at english sorry cheemspray

sage tendon
#

i dont know

sly ember
#

okay 👍

frail ocean
sage tendon
#

that for sure, yes

#

the author of that message will also be the person who wrote the initial message

#

if you can catch them otherwise, idk

frail ocean
#

Okay

subtle moth
#

staticmethods are underrated

sly ember
#

i hate the attribute error even though it is one of the easiest errors to fix damnthatscrazy

sage tendon
#

well either the guild or the message is none

#

so fix that

subtle moth
#

You're passing interaction.mesage.id to the method and the method is trying to extract the bot attribute from the id

#

Which doesn't exist

#

Actually you're getting 2 different errors from 2 different areas

sly ember
#

damn it

subtle moth
#

Seems like you're trying to fix some pre existing code or smth

sly ember
#
@staticmethod
async def getAll(pool, mid: int, gid: int, vote: str = None):  # -> list or None:
    async with pool.acquire() as conn:
        async with conn.cursor(aiomysql.DictCursor) as cursor:
            if vote:
                data = await cursor.execute(
                    ("SELECT * FROM surveys_votes WHERE gid = %s AND mid = %s and vote = %s", (gid, mid, vote)))
            else:
                data = await cursor.execute(("SELECT * FROM surveys_votes WHERE gid = %s AND mid = %s", (gid, mid)))
            if data is None:
                return None
            return [UserVote(data['mid'], data['uid'], data['gid'], data['vote']) for data in data]

do you think this will work hm Thinking_Green

subtle moth
#

you generally should be knowing what methods you've defined and their parameters

sage tendon
#

either that or chatgpt

#

because for the code you send you seem to have surprisingly little clue about python

subtle moth
sly ember
sly ember
sage tendon
#

no, i mean your code doesnt seem like it was written by you entirely

sly ember
#

its old, i was better before i stopped for a while skull_cry i feel dumb as hell asking here and dont knowing what you are talking about haha

#

but its getting better

#

i think

subtle moth
sly ember
#

Facts, i onced hate the urge to start coding a discord bot, and damn it, it was so hard starting, i was completely lost, but i think i developed myself better by the time, but the decision to stop again was a big mistake

subtle moth
#

Lol

#

Even I started python from making discord bots, wouldn't recommend

subtle moth
#

But I just kept working on it for like 2-3 years now and I've gotten most of pythons core concepts well

sly ember
#

okay so ive been trying the past 5 minutes, as it says the error is from the other function, and i think i found a way to fix that:

votes = {}  
for i in range(Anzahl_der_Votes): 
    votes[i] = await UserVote.getAll(pool, interaction.message.id, interaction.guild_id, i)
#

this is the part btw

subtle moth
#

Because the methods first parameter accepts a pool object but instead you passed in an integer as the argument

#

In your line 260

sage tendon
#

dude your "pool" is an int

#

what are you doing

subtle moth
sage tendon
#

man you are using ChatGPT or you're just copying someone's discord.py repo, you cant tell me otherwise

subtle moth
#

Personally, yes

sage tendon
#

again, i highly believe that you didnt write that code

#

so, yea

sly ember
deft kestrel
errant trout
#

well

#

await channel.follow(other_channel)

deft kestrel
errant trout
#

you can use bot.get_channel(id) to jump past guild entirely

sly ember
#

like (interaction, .....)

errant trout
sage tendon
#

they seem to have just as little clue about their own code as everyone else does

sly ember
deft kestrel
#

Is it possible to use a different proxy for each request? Instead of only establishing one proxy at the very start?

sage tendon
#

you have like 5 errors at once

#

its incredibly hard to even try troubleshoot

sly ember
#

damn it

#

where cryingcatemoji2

sly ember
#

what the hell is that bdumb

#

ahhh

#

sorry haha

fresh totem
#

what is the default timeout limit for buttons if a timeout is not set

#

and what is the maximum timeout we can set, for buttons

sage tendon
#

15m for both i believe

fresh totem
#

Aight, thanks! 🙌🏻

deft kestrel
# errant trout `await channel.follow(other_channel)`
@bot.slash_command(description="Set Announcements channel")
async def setannouncements(ctx, channel: discord.TextChannel):
    canale_annunci = bot.get_channel(1214305562112565349)
    await channel.follow(canale_annunci)```


> Application Command raised an exception: TypeError: follow() takes 1 positional argument but 2 were given
sage tendon
#

its not a positional argument, its a kwarg

deft kestrel
little cobalt
#

Why do you use follow?

errant trout
#

to follow a channel...

#

(e.g. #library-updates, #server-announcements)

deft kestrel
#

how to reload slash commands list without reloading my client?

sage tendon
#

you cant really

#

just reload, it takes 5 seconds

pale scroll
#

wow, dark, hi!

lofty parcel
velvet cradle
#

is there any way to get the bot user itself as guild member, without member intent or fetching it every time from the api?
I want to check, if the bot has a specific permission on a guild, and need the bot as member to do this.
but without member intent, the "guild.me" is None

#

sure, the bot can not get all members as normal without the intent, but it would be useful, if the bot knows itself....

errant trout
velvet cradle
#

thats, what I thought, but it is not

errant trout
#

hmmm just checked and it's worked fine on my end

#

do you stlll have the guilds intent?

velvet cradle
#

I have no intents at all

errant trout
#

you need some at least

velvet cradle
#

ok, nice to know, will try it, give me a second

errant trout
velvet cradle
#

intents=discord.Intents.default() should be enough, right?

errant trout
#

intents.default gives you every intent apart from presences, message_content and members

velvet cradle
#
        if not (destination_guild := await get_or_fetch_guild(self.bot, ctx, destination_guild_id)):
            return
        print(f"Me: {destination_guild.me}, guild name: {destination_guild.name}")

still yields
Me: None, guild name: BTS2

#

so the bot does find the guild, but the bot member does not exist

errant trout
#

you 100% sure you passed intents? i just checked, and disabling guilds intent dropped my bot member

velvet cradle
#
class Bot(discord.Bot):

    async def on_ready(self):
        print(f"{self.user.name} is ready and online!")

    def __init__(self):
        super().__init__(intents=discord.Intents.default())
        print("Connecting to database...", end=" ")
        # rest ignored


print("Starting bot...")
bot = Bot()
#

as far as i know, this should be enough, or am I missing something?

errant trout
#

hm, looks fine to me...

#

what happens when you print(len(list(self.get_all_members()))) (where self is the bot)

velvet cradle
#

(i changed the class name before sending the message and removed the database stuff, because this is just al lot of code, which is not important here)

#

it gives me 3

errant trout
#

and im guessing your bot is in 3 guilds?

velvet cradle
#

nope

errant trout
#

then how many

velvet cradle
#

it prints twice itself (in two guilds) and one time myself (also in both guilds; bot only one time in the output)

errant trout
#

so it's in 2 guilds, and it sounds like you are getting the bot member in both guilds?

#

the reason you only show once is because it only recieved you in one guild through other means (e.g. interaction)

velvet cradle
#

bot and me are in guild a and guild b
it prints
itself in a, itself in b, myself in a

#

no other users are shown

errant trout
#

yeah sounds about right

velvet cradle
#

nope

errant trout
#

???

#

what about guild.get_member(bot.user.id)

velvet cradle
#

None

errant trout
#

show the exact output of guild.members

velvet cradle
#

sec

#
[<Member id=1087478322834980934 name='bottest' discriminator='8370' bot=True nick='ChannelMirrorTNT2k' guild=<Guild id=1087478373346983988 name='Bot Test Server' shard_id=0 chunked=False member_count=36>>, <Member id=759537934873133076 name='tnt2k' global_name='TNT2k' bot=False nick=None guild=<Guild id=1087478373346983988 name='Bot Test Server' shard_id=0 chunked=False member_count=36>>]

the bot and myself

errant trout
#

then i have no clue why those other methods are failing

velvet cradle
#

interesting

#

i am trying something

errant trout
#

this is literally how guild.me is defined py @property def me(self) -> Member: self_id = self._state.user.id return self.get_member(self_id) # type: ignore

velvet cradle
#

i found a clue

#

if I try to get the bot user in the guild, I run the command, it works.
if I want to get the bot user of the other guild, it does not work.

errant trout
#

can you show the code you're using

velvet cradle
#

sure, give me a second to clean it up a little

#
@group.command(name="create", description="")
    async def create(self, ctx,
                     source_channel: Option(TextChannel, ""),
                     destination_guild_id: Option(str, "")
                     ):
        if not (destination_guild := await get_or_fetch_guild(self.bot, ctx, destination_guild_id)):
            return
        print(destination_guild.members)
        print(ctx.guild.members)
        print(ctx.guild.me)
#

so this yields

[]
list with two members (there are more on the guild)
the bot user
errant trout
#

is get_or_fetch_guild your own function

velvet cradle
#

but I can not get the bot user of the other guild

#

yes

errant trout
#

can you show that too

velvet cradle
#
async def get_or_fetch_guild(bot, ctx, guild_id) -> Guild | None:
    try:
        return bot.get_guild(guild_id) or await bot.fetch_guild(guild_id)
    except Forbidden:
        if ctx:
            await ctx.respond("Not a member of destination guild", ephemeral=True)
        return
    except NotFound:
        if ctx:
            await ctx.respond("Destination guild doesn't exist", ephemeral=True)
        return
    except:
        if ctx:
            await ctx.respond("An error occurred", ephemeral=True)
        return
errant trout
#

can you convert guild_id to int

velvet cradle
#

so can slash commands not get the bot user of this instance in the other guild?

#

I could, yes, but this does not change anything, the destination guild is not None

errant trout
#

it changes everything

#

fetch_guild doesn't return members

velvet cradle
#

if it was, the command would exit right away

errant trout
#

get_guild returns None because it's a string

velvet cradle
errant trout
#

nope

velvet cradle
#

oh, thats indeed a problem

errant trout
velvet cradle
#

so how do I fix that? I can convert it to int, but if the bot does not have this guild in its cache, the "guild.me" would be empty nevertheless

errant trout
#

converting it to int fixes everything because the bot must have the guild in its cache

#

you can't fetch a guild you aren't in

velvet cradle
#

nice to know. ideally, i would require an int as argument, but ids are too large

errant trout
#

just convert it in the command

velvet cradle
errant trout
#

yes

velvet cradle
#

thats nice to know, thaks a lot for the help

errant trout
#

allgood

frail ocean
errant trout
#

not particularly

round heart
#

Somewhat of a security question - are bots (like spammer bots) able to read button values? Like if I wanted to do a math problem, should I make the IDs randomized instead of the actual label? Trying to reduce as much automation possibility as I can.

velvet cradle
#

is there any way to let a bot trigger a slash command? wanna test something with slash commands, and it would be way easier to do it that way, than disassembling the api.... i need to test something permission related, and users do not really care, if the should do something or not...

velvet cradle
round heart
#

Yeah, so the question is whether I should obfuscate the values or whether the label is going to make that useless

velvet cradle
#

well, you can do something different and more complex like "tell me were the cross in this coordinate system is" and you just make an 8x8 grid and put the red cross somewhere in it

#

I do not know, if the id will help them, but the label certainly will, because the users must be able to read it

errant trout
#

just map your randomized IDs internally

round heart
#

Yeah. The (theoretical) question is whether all of that effort would be effective

#

I wonder if I can send unicode for the numbers so it's not just straight characters. \x0030 or however you'd do it. Make the client render

errant trout
#

Shrug it's not really that much effort, but also it depends on if you think people would actually bother

lapis dock
#

if they are specifically targeting automation of your bot they will be able to do all the simple captchas. If you just want to protect against normal math bots you can change it up

round heart
#

All I know is that I'm currently using captcha.bot and everyone unilaterally hates it. It takes you out of Discord to link your account to a centralized entity's website that is probably a pretty big target for compromise.

Haven't seen any good existing solutions to draw inspiration from.

#

Was going to try to do a 'one of these things is not like the other' with Pillow, but ChatGPT solves them effortlessly, even with backgrounds that try to break computer vision.

granite pier
#

but depends on need

#

i mean you can e.g. unload/load cogs and then call sync_commands(cmds)

#

and use delete_existing if needed

granite pier
#

but it makes the most sense only for bots that have a time-consuming startup

young cove
#

Hey all, I'm trying to add logic to my slash command so a certain autocomplete value adds another option/argument to the command. For example:

@option(
    "update",
    description="Fields to update",
    autocomplete=discord.utils.basic_autocomplete(
        ["Character Info", "Add Image"]
    ),

So if option == "Add Image" :

/add ["Add Image"] [New Option appears here that is not there when "Character Info" is selected as first argument]

#

I don't need help with the whole command, just curious about how to dynamically add @options in a slash command.

#

I think I remember seeing a post about it a while back (either here or on stack) but can't find it for the life of me.

granite pier
#

you can't dynamically add options

#

unless you mean autocomplete results

young cove
#

No essentially I want to give users the option to upload an image when "add image" is selected. But not give them that option when "Character info" is selected.

granite pier
#

you can add 2 options with default None and check if e.g. option1 == X and option2 is not None

#

so like:

opt[update]
opt[text] = None
opt[image] = None

if opt[update] == "Character Info" and not opt[text]:
  // text not provided
if opt[update] == "Add Image" and not opt[image]:
  // image not provided
#

but the better way wold be just make your command run like

opt[text] = None
opt[image] = None
#

so you'll just select what do you want to update

#

and if none then return original or an error

#

description="Fields to update"

#

let options be your fields

#

and update them if they are not None / default (unless None is possible)

young cove
# granite pier so like: ``` opt[update] opt[text] = None opt[image] = None if opt[update] == "...

Thank you for the help so far! I've been trying this to no avail.

@option(
        "image",
        discord.Attachment,
        description="Image files must be .png or .jpg",
        required=False,
)

In the above declaration, it seems you can't set the option = none.

I also tried here:

async def autocomplete(
        ctx: discord.ApplicationContext,
        name: str,
        update: str,
        image = None
        #image: None
):

That at least compiles and runs, but the option for the image is always there.

young cove
granite pier
granite pier
#

Or both if needed

#

or you can use different logic of args like update_info: bool+avatar:...

#

if not avatar and not update_info:
error

if avatar:
update avatar

if update_info:
return send modal

respond

young cove
young cove
deft hull
#

why is this?

sage tendon
#

just use the option decorator tbh

#

way cleaner anyway

finite plover
#

how to realese event on_message in cog?

granite pier
deft hull
#

thanks

deft hull
#

how do you use the option decorator

#

I've tried @option but it's not defined

granite pier
deft hull
#

ok thx a lot

sage tendon
#

is there even a difference between option and Option

granite pier
#
def option(name, type=None, **kwargs):
    """A decorator that can be used instead of typehinting :class:`.Option`.
sage tendon
#

yea but you can also do @Option

#

I'm p sure

granite pier
#

its class not decorator

little cobalt
granite pier
#
@discord.option

or

(
option: discord.Option(...)
)
deft hull
#

Do you guys keep your embeds and views in a separate file?

little cobalt
#

I do

errant trout
#

Eh, not really? Up to you

little cobalt
#

I use a core folder where you can see all the views utils etc

sage tendon
#

util file ftw

little cobalt
#

Util file?

round heart
#

That way I can better track aspects of the embed if I need to modify it in response to interactions with the View

deft hull
#

For EmbedFields do you have to insert the keywords or just do (arg1, arg2, arg3)

red mist
#

What @sage tendon means is that there is an option decorator like this;

import discord
from discord import option

@discord.slash_command(name='your_command')
@option('user', discord.Member, description='Choose a member.', required=False)
async def your_command(ctx: discord.ApplicationContext, user: discord.Member=None):
  ...
#

I put it so that you can choose to select a discord user in this example

#

which eventually looks like this

fresh totem
#

Hey quick question:

[<Reaction emoji='👍' me=True count=2>, <Reaction emoji='👎' me=True count=2>]

This is message.reactions

How do I make this readable

#

As in, fetch the count for reactions

red mist
#

As you said, fetch it first, and then just go trough the reactions like in a list or dict and then finally .count I suppose

fresh totem
#

Tried .count(), didn't work as expected

but I got it working using a for loop and .emoji

#

Thanks!

red mist
#

without the ()

#

just

#

oh

#

okay

#

welp ig

#

Would've just said

message = await message.channel.fetch_message(message-ID)

upvote = message.reactions[0].count
downvote = message.reactions[1].count

print(f"Upvotes: {upvote}, Downvotes: {downvote}")
fresh totem
red mist
#

np

little cobalt
red mist
#

Why tho... I didnt contribute to the library so I really dont deserve it

little cobalt
#

Time to change that

fresh totem
#

Wait, all helpers have contributed to the development? W team

red mist
#

idk but if I recall correclty, anyone on the staff has contributed.

arctic plover
#

I do not know why, but I have several instances of bots. As a result, when using the command, I get an error message: Application Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction At the same time, I get a response from an old instance of the bot. The picture shows that when I enter the same command, I get different answers.

arctic plover
sage tendon
#

don't run your bot twice

finite plover
#

why is there this error: ValueError: View is not persistent. Items need to have a custom_id set and View must have no timeout?

sage tendon
#

what line does that error come from?

finite plover
#

line 36 in main py

#

but...?

sage tendon
#

you cant add that view to the bot because its not persistent ig

sage tendon
#

wip i guess

lofty parcel
sage tendon
#

i didnt even know that was a thing
arent slash commands synced automatically?

finite plover
sage tendon
#

shrug read the persistent view guide i guess

finite plover
#

if i remove second button its work

finite plover
sage tendon
#

oh, i guess because you assigned an id to the buttons but not the view?

lofty parcel
#

Because that's not how you define link buttons.

#

You can't define link buttons through a decorator.

finite plover
#

ahhhh

#

okay

#

how to do link buttons?

#

guide doesn't mention it or i'm blind

lofty parcel
#

You add it manually

#
self.add_item(discord.ui.Button(label="My Link", link="https://google.com", style=discord.ButtonStyle.url))
little cobalt
finite plover
#

oh 4 line

#

idk this is not my code

sage tendon
#

bruh

little cobalt
#

....

lofty parcel
#

breh

peak axle
#

its saying that pycord isnt installed, but it is

#

i tried uninstalling and reinstalling it

little cobalt
peak axle
little cobalt
#

weird

#

restart PyCharm and if its still, install py-cord again

peak axle
#

ok

errant trout
#

you sure it's running in the pycharm venv itself

little cobalt
#

good question

peak axle
#

still doesnt work

little cobalt
#

which venv do you use?

peak axle
#

oh

#

i fixed that issue i think

little cobalt
#

What was it?

peak axle
#

it was the wrong interpreter

sage tendon
#

pycharm will complain about importing discord because it doesnt match py-cord

errant trout
#

that was an actual import error, not pycharm

sage tendon
#

i know

lapis dock
nova epoch
#

Not sure this is worth an entire post because it's probably me just being blind, but details are below:

I am trying to crate a bot that catched invites and refuses them unless they are created by specific people. I have done this using the following code:py @bot.event async def on_invite_create(invite): if invite.inviter.id not in [user_ids.get('tobezdev'), user_ids.get('vimto'), user_ids.get('self')]: await bot.delete_invite(invite) e = discord.Embed( title="Invite Creation", description=f"Invite creation is disabled on the `{invite.guild.name}` server. To invite a user, please use the `/invite` command.", color=embed_colors.get('200_warn') ) e.add_field(name="Prefilled Invite Command", value="Click here to invite a user: </invite:1213823153835352174>") await invite.inviter.send(embed=e) e = discord.Embed( title="Invite Blocked", description="An invite was blocked from being generated.", color=embed_colors.get('200_warn') ) e.add_field(name="User Info", value=f""" User ID: {invite.user.id} Username: {invite.user.name} Display Name: {invite.user.display_name} """)

The event catches it fine, however the bit gets a discord.errors.HTTPException: 400 Bad Request (error code: 50007): Cannot send messages to this user from attempting to DM itself.

My question is: Why does the bot attempt to run the invite.inviter.send even when its ID is in the list of allowed IDs?
I have checked both the invite and the ID in the user_ids dictionary, and they all match up.

Thanks in advance.

red mist
red mist
#

Which may cause the not in to not get accessed.

nova epoch
#

-> int | None -- I have a filter that catches None if it is returned built-in to the get function.

red mist
#

Ah

nova epoch
#

The only way it gets to the error line is if the ID is type int.

lofty parcel
#

IDs must be an int

nova epoch
#

ID is an int.

#

Thats why I'm so confused

#

I mapped everything to PyCord docs and it all checks out

red mist
#

Also the error you're getting is just the bot failing to dm the user because they may have disabled their dms

nova epoch
#

It's the bot trying to DM itself, because it created an invite.

#

The bot's ID is in the allow list.

#

🤷

lofty parcel
#

Then your condition is wrong

#

¯_(ツ)_/¯

nova epoch
#

if invite.inviter.id not in [user_ids.get('tobezdev'), user_ids.get('vimto'), user_ids.get('self')]:

#
@bot.event
async def on_invite_create(invite):
    if invite.inviter.id not in [user_ids.get('tobezdev'), user_ids.get('vimto'), user_ids.get('self')]:
        await bot.delete_invite(invite)
        e = discord.Embed(
            title="Invite Creation",
            description=f"Invite creation is disabled on the `{invite.guild.name}` server. To invite a user, please use the `/invite` command.",
            color=embed_colors.get('200_warn')
        )
        e.add_field(name="Prefilled Invite Command", value="Click here to invite a user: </invite:1213823153835352174>")
        await invite.inviter.send(embed=e)
        e = discord.Embed(
            title="Invite Blocked",
            description="An invite was blocked from being generated.",
            color=embed_colors.get('200_warn')
        )
        e.add_field(name="User Info", value=f"""
User ID: {invite.user.id}
Username: {invite.user.name}
Display Name: {invite.user.display_name}
        """)```
#

Thats the whole event ^

lofty parcel
#

You already sent that

#

Show the user_ids dict

nova epoch
#
global user_ids
user_ids = {
    "vimto": 381938080690733056,
    "tobezdev": 969254887621820526,
    ("self", "bot"): 1212532236583440434
}```
lofty parcel
#

Does it work if its you the one creating the invite?

nova epoch
#

To be honest, I haven't tried, give me a moment.

red mist
#

:o

#

Also maybe for the future consider using try except blocks >~< they're much more useful in the handling of these types of errors.

nova epoch
lofty parcel
#

Using your dict and using user_ids.get("self") returns None.

nova epoch
#

Uh

red mist
#

Wait what

nova epoch
#

Now I'm really confused

red mist
#

Oh

#

Wait

#

Bro

nova epoch
#

There's a filter on it that prevents None from even being returned

red mist
#

Is it

#

It's not a dict / list

#

Is it?

#

Am I stupid

#

I thought {} werent

nova epoch
#

Yes, {} represents a Dictionary

red mist
#

Oh well

#

Fuck

lofty parcel
#

Just double it.

nova epoch
#

Double it?

lofty parcel
#
global user_ids
user_ids = {
    "vimto": 381938080690733056,
    "tobezdev": 969254887621820526,
    "bot": 1212532236583440434,
    "self": 1212532236583440434
}```
red mist
#

Oh self and bot make it a string inside s tuple

#

*a

#

Yeah

#

That

#

Should

lofty parcel
#

I think there's a misconception how indexing dicts work

#

I'm sure python sees the tuple, as literally a tuple with "self" and "bot" inside and that's the index in the dict

#

In fact, indexing it as a tuple returns the int

nova epoch
#

Oh look, there's an ID now...

#

Thanks guys

#

<3

lofty parcel
#

Plus

#

Dunno what's stopping you from using a normal list

#

With just ids

red mist
#

In Python, when you use parentheses around multiple values, it creates a tuple.

So, ("self", "bot") is actually a tuple containing two strings: "self" and "bot".

#

Fuck I messed up

#

The 2nd part was my own messsge

#

First was google

#

Ugh

#

Even if its obvious but yah

nova epoch
#

I think it's setting the value of ("self", "bot") to the ID, and then seeing that 'self' != ("self", "bot")?

red mist
#

No again, its not a key anymore its an entire string

nova epoch
#

In my head, it's treating ("self", "bot") as the store of data, not self and bot induvidually.

#

Welp, anyways. Its sorted now so no point arguing over it. Thanks so much guys <3

red mist
#

still helps ya in the future, with more ducts ;)

#

*dicts

lofty parcel
#

The tuple is the key.

#

Not each value inside of it.

red mist
errant trout
#

(in python, any object can be a dict key which leads to some fun interactions)

deft hull
#

If my Select is in a class do I need to pass (self, select, interaction) or just (self, interaction) in the callback

errant trout
#

Wait

#

Oh I see, no it's the latter

deft hull
#

oh thanks!

errant trout
#

The first is if you're using the @select decorator inside views

deft hull
#

ah I see

#

can I use await interaction.response.edit_message within it

errant trout
#

Yes

#

(In 2.5, interaction.edit is a shortcut for this)

deft hull
#

ah I see, thanks a lot

round heart
#

Is it possible to determine whether an ephemeral is still active? Like will get_message fail if it's been Dismissed (or work if it hasn't been?)

shell radish
#

no

round heart
#

Damn, why doesn't Discord want us to make state-aware apps

shell radish
#

because thats not how ephemeral messages work

round heart
#

But ... hear me out -- it could. Click a button, get a response that shouldn't be public, but only one copy of the response, unless it was deleted.

shell radish
#

in its current state, the "copy" of the response is sent to all clients currently logged into that account

deft hull
#

Why do I get this error?

shell radish
#

you never initiated the parent class

deft hull
#

so I should use super().init().add.item()?

shell radish
#

you need a super().__init__() somewhere in your __init__ (preferably first line)

deft hull
#

ah ok

arctic plover
#

When I copy message id via this:

message = await ctx.respond("smth")
message_id = message.id

And then I compare it with the ID that I get when I click the “copy ID” button on the message, I get different results. Why?

shell radish
arctic plover
#

As far as I understand, the Interaction object must have an attribute "message", but when I try to receive a message using interaction.message I get NoneType object

shell radish
arctic plover
shell radish
#

the first one

arctic plover
deft hull
#

my interaction failed and there is no error message in my terminal

#

I can't even find any errors

#

How do I get the value the user selected in this case?

little cobalt
deft hull
#

how do I define a callback for a button i addee via self.add_item()?

#

I'm not using a separate class for that button

sage tendon
#

you made a view class, no? so the function for the button should already be there

subtle moth
#

You needn't manually add the button to the view

deft hull
#

yeah but I need to set a button's properties based on a conditio?

subtle moth
deft hull
#

@subtle moth So I have to define a function then set the callback as that function?

subtle moth
#

Yes

deft hull
#

Alright thank you very much

lofty parcel
deft hull
#

apparently there is no callback argument for discord.ui.Button

#

I should just subclass it

deft hull
#

what's this error

discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components.1.components.0.label: This field is required
lofty parcel
#

You didn't pass a label

deft hull
#

I set a label but the issue still persists

frail ocean
deft hull
#

slash command

@bot.slash_command(description='View information on a specific Pokémon.')
@discord.option('name', description='The name of the outfit or Pokémon', autocomplete=discord.utils.basic_autocomplete(filter_names))
async def pokemon(ctx, name):
    try:
        pokemon = pkmn.get_by(name=name)
        await ctx.respond(embed=models.Main(pokemon=pokemon), view=models.MainNav(pokemon=pokemon))
    except Exception as error:
        print(f'An error occured: {error}')      
        await ctx.respond(embed=discord.Embed(description='This Pokémon or outfit does not exist. Did you misspell it?'))

view object

class MainNav(discord.ui.View):
    def __init__(self, pokemon: pkmn.Pokemon, level: int=25, ol: int=4):
        super().__init__()
        self.pokemon = pokemon
        self.level = level
        self.ol = ol
        self.add_item(OutfitSelect(pokemon=pokemon, level=level, ol=ol))
        self.add_item(ShinyButton(pokemon=pokemon, level=level, ol=ol))

    async def on_timeout(self):
        self.disable_all_items()


class ShinyButton(discord.ui.Button):
    def __init__(self, pokemon: pkmn.Pokemon, level: int=25, ol: int=4):
        self.level = level
        self.ol = ol
        
        if pokemon.get_counterpart() is None:
            self.has_shiny = False
        else:
            self.has_shiny = True
            self.counterpart = pokemon.get_counterpart()

        super().__init__(label='', style=discord.ButtonStyle.success, disabled=(not self.has_shiny))
    
    async def callback(self, interaction):
        await interaction.response.edit_message(embed=Main(pokemon=self.counterpart, level=self.level, ol=self.ol), 
                                                view=MainNav(pokemon=self.counterpart, level=self.level, ol=self.ol))
lofty parcel
#

I'm sure the label can't be " "

hushed pebble
#
import discord
from discord.ext import commands
from discord.ui import Button, View, Modal

class Review(Modal):
    def __init__(self, title="Отзыв"):
        super().__init__(timeout=15, title=title)
        
    first = discord.ui.InputText(
        style=discord.InputTextStyle.short,
        label="Оценка",
        required=True,
        placeholder="Введите вашу оценку(10/10)"
    )
    second = discord.ui.InputText(
        style=discord.InputTextStyle.long,
        label="Отзыв",
        required=True,
        placeholder="Напишите отзыв о игре"
    )
    
    async def on_submit(self, interaction: discord.Interaction):
        user_id = 906115102888046623
        user = await bot.fetch_user(user_id)
        embed = discord.Embed(title="Новая Заявка!", description=f"{self.user.name} написал отзыв!", color=discord.Colour.blurple(), timestamp=interaction.message.created_at)
        embed.add_field(name="Оценка:", value=f"{self.first.value}:starr:/10:starr:", inline=True)
        embed.add_field(name="Отзыв:", value=f"Отзыв: {self.second.value}:kodart:", inline=True)
        embed.set_footer(text="Kodart :heartt:")
        embed.set_author(name=self.user)
        await user.send(embed=embed)
        await interaction.response.send_message("Ваш отзыв был отправлен!", ephemeral=True)

intents = discord.Intents.all()
bot = commands.Bot(command_prefix='!', intents=intents)

@bot.event
async def on_ready():
    print(f'Logged in as {bot.user.name}')

@bot.slash_command()
async def hello(interaction):
    button = Button(label="Оставить отзыв..", style=discord.ButtonStyle.grey, emoji=":00settings:")
    
    async def button_callback(interaction):
        modal = Review()
        await interaction.response.send_modal(modal)

    button.callback = button_callback

    view = View()
    view.add_item(button)
    await interaction.response.send_message("Привет!", view=view)

bot.run(TOKEN)
hushed pebble
# hushed pebble ```py import discord from discord.ext import commands from discord.ui import But...

Ignoring exception in view <View timeout=180.0 children=1> for item <Button style=<ButtonStyle.secondary: 2> url=None disabled=False label='Оставить отзыв..' emoji=<PartialEmoji animated=False name='00settings' id=1215000851597238342> row=None>:
Traceback (most recent call last):
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ui\view.py", line 426, in _scheduled_task
await item.callback(interaction)
File "C:\Users\Lenovo\Downloads\KodArt\main.py", line 47, in button_callback
await interaction.response.send_modal(modal)
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\interactions.py", line 1178, in send_modal
await self._locked_response(
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\interactions.py", line 1243, in locked_response
await coro
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\webhook\async
.py", line 222, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components: Must be between 1 and 5 in length.

deft hull
lofty parcel
#

And on_submit doesn't exist in pycord

#

It's callback

hushed pebble
lofty parcel
#

Next time say something like "hey, I've been trying to debug this but I can't find a solution. Could you help?"
We aren't AI

lofty parcel
rugged lodgeBOT
#

Here's the modal dialogs example.

hushed pebble
lofty parcel
#

Type that again in understandable English

hushed pebble
lofty parcel
#

You are supposed to add the inputs to the modal

#

Just defining them on the init doesn't magically add them

finite plover
#

why doesn't it work after rebooting the bot?

UPD: non-relevant problem

lofty parcel
#

.idw

sly karmaBOT
#

Saying it doesn't work or asking what's wrong with this code is not helpful for yourself or others.
Describe what you expect and/or tried (with your code), and what isn't going right.
Please provide any errors you get for optimal assistance.

hushed pebble
finite plover
# finite plover why doesn't it work after rebooting the bot? UPD: non-relevant problem

ah ok, what can i say about it? it doesn't work after rebooting. no errors and works when i run the command set_channel:

@commands.command()
    async def set_channel(self, ctx, channel: discord.TextChannel = None):
        # Проверка наличия роли "Верефицированный"
        verified_role = discord.utils.get(ctx.guild.roles, name="Верефицированный")
        if not verified_role:
            embed = discord.Embed(title=":error: | Ошибка", description="**Роль** `Верефицированный` **не найдена. Пожалуйста, создайте эту роль перед использованием команды** `set_channel.`", color=0xff0000)
            await ctx.send(embed=embed)
            return

        # Установка канала для верификации
        if channel is None:
            embed = discord.Embed(title=":error: | Ошибка", description="**Пожалуйста, укажите канал для верификации.**", color=0xff0000)
            await ctx.send(embed=embed)
            return
    
        global verification_channel_id
        verification_channel_id = channel.id
        
        curs.execute("INSERT INTO verify_settings VALUES(?, ?)", (ctx.guild.id, verification_channel_id))
        conn.commit()
        
        embed = discord.Embed(title=":success: | Канал верификации установлен", description=f"**Я отправил сообщение на канал** {channel.mention}", color=0xff100)
        await ctx.send(embed=embed)

        # Отправляем сообщение в установленный канал
        embed = discord.Embed(title=":verify: Верификация", description="**Добро пожаловать!\n\nДля того чтобы продолжить участие на сервере, необходимо пройти процедуру верификации. Просто нажмите на реакцию ниже (:verify:), чтобы подтвердить свою личность. После успешной верификации у вас откроется доступ ко всем каналам и возможностям сервера.\n\nБлагодарим вас за понимание и сотрудничество!**", color=0x009bff)
        message = await channel.send(embed=embed)
        await message.add_reaction(':verify:')```
arctic plover
#

My bot is administrator, but he still can`t mention everyone. My respond:
interaction = await ctx.respond(ctx.guild.default_role.mention, embed=embed, view=GiveawayView(code, giveaway_id))
But i get this:

lofty parcel
#

no need to use ctx.guild.default_role.mention

arctic plover
#

interaction = await ctx.respond("@everyone", embed=embed, view=GiveawayView(code, giveaway_id))

#

bot has one role that has permission "Administrator"

lofty parcel
arctic plover
#

i`ll try

#

spoiler: im wrong

lofty parcel
#

interaction webhooks work in a weird way

arctic plover
#

now it works

#

thanks you

frail ocean
lofty parcel
frail ocean
lofty parcel
#

You just said "it doesn't work"

#

Do you expect me to be able to debug that

sage tendon
#

yea make it work

lofty parcel
#

I ain't no github copilot

finite plover
lofty parcel
#

Did you even try to debug it by yourself using prints?

finite plover
#

no results

shell radish
#

that's literally the purpose of a debugger, but ok

sage tendon
#

people can't use debuggers

lofty parcel
#

^

lofty parcel
shell radish
#

anyways, is the command even being triggered?

lofty parcel
#

The problem is the event

#

Not the command

grizzled loom
sage tendon
#

but it's already broken sooo

#

consider them unbreakpoints

shell radish
#

how is your bot or client defined?

shell radish
finite plover
sage tendon
#

alright I might be a bit dumb but don't reactions require intents?

shell radish
shell radish
#

which is ... the default if no intents are passed

shell radish
#

the specific code for it would be helpful

finite plover
#

it actually says that

shell radish
#

and your commands work just fine?

finite plover
#

yes

shell radish
finite plover
sage tendon
shell radish
finite plover
#

yes

sage tendon
#

is that a yes to my question?

finite plover
shell radish
#

can you send the output of pip list

sage tendon
#

you'd think if someone wants help they'd answer properly

finite plover
sage tendon
#

you can

finite plover
#

nah

subtle moth
#

lowkey think theyre trolling atp

sage tendon
#

man just do it in a console

shell radish
finite plover
sage tendon
#

bruh

shell radish
#

do you have a requirements.txt or packages.toml

#

or Dockerfile

shell radish
#

can you send that

finite plover
#

ok

#
py-cord==2.5.0
requests==2.31.0```
sage tendon
#

bruh

#

and uninstall it from your hosting

#

and your pc of course

subtle moth
#

And don't use requests

sage tendon
#

^ use aiohttp instead

little cobalt
#

but

#

?tag rie

limber wagonBOT
#

You can run blocking code (such as PIL/Pillow) in an executor to run it in a separate thread: ```py
def my_blocking_func(*args):
...

@bot.command()
async def test_command(ctx):
ret = await bot.loop.run_in_executor(my_blocking_func, 'put', 'args', 'here')``` See the python documentation for more info.

finite plover
#

🙂

sage tendon
#

reinstall pycord

finite plover
sage tendon
#

any error?

lofty parcel
#

Don't you need intents for that

little cobalt
sage tendon
#

and, yesno

finite plover
little cobalt
#

so you dont have the reaction intents?

sage tendon
#

it's part of default intents

finite plover
#

but in first it works

sage tendon
#

guys were spinning in circles

little cobalt
lofty parcel
finite plover
sage tendon
#

according to squid

sage tendon
little cobalt
shell radish
little cobalt
#

oh ok

shell radish
sage tendon
#

my main question is where is the event listener even defined

#

and how do you know it doesn't work

shell radish
sage tendon
#

man I'm getting lost here

finite plover
sage tendon
#

if you put a print into the event listener does it print at all?

#

like at the very start

shell radish
#

they said nothing happens

finite plover
#

nah, it doesn't print anything

#

hah, if i add reaction to new message i can see this:

Traceback (most recent call last):
  File "/home/container/.local/lib/python3.11/site-packages/discord/client.py", line 400, in _run_event
    await coro(*args, **kwargs)
          ^^^^^^^^^^^^^^^^^^^^^
TypeError: Verify.on_reaction_add() takes 2 positional arguments but 3 were given```
sage tendon
#

well then

vital bramble
#

How can I perform dynamic checks on slash commands in a cog?
Like checking for a role that may be changed.