#Basic Pycord Help

1 messages · Page 50 of 1

sage tendon
#

at the highest level

sand bolt
#

ok ok

fresh sierra
#

so ur just in the wrong server

sage tendon
#

no?

sand bolt
#

ops

fresh sierra
sage tendon
#

you cant know what they're using based on that code

fresh sierra
#

...

#

await load extension

#

app_commands

#

setup hook

sage tendon
#

hm true

#

didnt see the import

sand bolt
#

sorry

fresh sierra
#

dw

sage tendon
#

if you're new to programing, i'd recommend pycord if you wanna use slash commands

#

discord.py is unnecessarily complicated and weird with slash commands

sand bolt
#

what can i use?

sage tendon
#

whatever you want, but i recommend pycord lol

sand bolt
#

ok thanks

stoic patio
#

why would this happen

echo wraith
stoic patio
#

why would that happen

echo wraith
#

idk where do you set self.user

#

maybe you are setting it to none

#

you aren't giving enough context

sage tendon
#

Most importantly, what did you change since it last worked

sage tendon
#

the top of the stacktrace is what matters
the more you go down the more it gets into library code

heavy inlet
#

How do I make a button that only works for the person who ran the command?

stoic patio
sage tendon
echo wraith
sage tendon
little cobalt
stoic patio
sage tendon
#

show your code

stoic patio
#

but that only happens when it resumes

#

not upon first startup

sage tendon
#

resume?

stoic patio
#

on_resumed

#

that thing

little cobalt
#

wtf is on_resumed

rugged lodgeBOT
sage tendon
#

are you by any chance running the bot again inside on_resume

stoic patio
heavy inlet
little cobalt
heavy inlet
#

yeah it's working, ty

stoic patio
heavy inlet
#
class DeleteButton(discord.ui.View):
    def __init__(self, author):
        super().__init__(timeout=None)
        self.author = author # for outside classes

    @discord.ui.button(label="Delete", custom_id="delete_button", style=discord.ButtonStyle.red)
    async def delete_callback(self, button: discord.ui.Button, interaction: discord.Interaction):
       if interaction.user.id != self.author.id:
           await interaction.response.send_message("You do not have the permission to delete this message!", ephemeral=True)
           return
       await interaction.message.delete()

This button is supposed to be persistent, but it says Interaction Failed after the bot restarts. It doesn't even throw any exceptions

#

for information it does work before the bot restarts

lofty parcel
#

.rtfm Bot.add_view

vague plaza
#

is there a way to tag everyone without actually showing @ everyone in the text message?

sage tendon
#

no

vague plaza
#

how can I hide it with a spoiler ||like this||? just with ||?

sage tendon
#

yea, but why lol

lofty parcel
#

But I gotta DM you the text cause the stupid automod mutes me

sage tendon
#

well yea you can but the markdown spam trick doesn't work on mobile I think

#

and it just depends on a bug so meh

lofty parcel
vague plaza
sage tendon
#

I forgor then

vague plaza
flint talon
#

guys

#

so I have a ton of commands for my bot

#

and all of them work as intended

#

except one of them

#

I just programmed in this new command

#

and it just won't run

#

I've tried try catch nothing shows up in console, keeps running as usual

#

and it just won't accept this one

#

command

#

and it's driving me nuts

#

cause I cant even get an error

errant trout
quartz umbra
#
            task = asyncio.create_task(self.coro_listen_for_reaction(user, tester, activity_msg, ticket_channel, kit))
            self.tasks.add(task)
            task.add_done_callback(fn=self.tasks.discard(task))

The last line, Pylance is throwing: ```
Expected 1 more positional argument

#

can anybody help?

grizzled loom
#

When it expects more?

grizzled loom
autumn narwhal
#

how can I use the emoji with discord.CustomActivity?

activity = discord.CustomActivity(emoji=discord.PartialEmoji.from_str('![information](https://cdn.discordapp.com/emojis/1260214232528588820.webp?size=128 "information")'), name=f"啟動中・啟動進度:{int((len(self.bot.users)/per)*100)}%")
print(activity)
await self.bot.change_presence(
    status=discord.Status.online,
    activity=activity
)
fresh sierra
#

By doing a glitch

sage tendon
#

they were already told that yesterday

#

can you stop constantly replying to already-solved messages

#

it helps no one

broken igloo
#

is there a way to use pycord in a way that doesn't need a bot

#

i want to make a python script to search and fetch specific messages

sly karmaBOT
#
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
bridge.Bot # above + bridge commands (application commands and text commands in one)
sage tendon
#

Not sure if .Client would suffice but you always need a bot user in the server

broken igloo
#

oh

fresh sierra
fresh sierra
#

Will be more efficient in ur case I think since it doesn’t need to have the bot inside the server

sage tendon
#

but you cant search messages and stuff then

#

the most you can do is use a message command on 1 message each

broken igloo
#

oh

sage tendon
fresh sierra
sage tendon
#

no

#

never tried user apps?

#

they're super limited in everything

fresh sierra
#

nope

#

im waiting for the listener before looking at the user app

mellow pebble
#

ephemeral for slash command groups is not working

sage tendon
#

show what you mean and your code

mellow pebble
#

i mean when i use a slash cmd group and use ephemeral it's ntow orking

sage tendon
#

great, show what you mean and show your code

mellow pebble
#
@crypto.command(
        name="sell",
        description="Sell Crypto (Minecraft Economy)",
    )
    @option(
        "symbol",
        description="Crypto Symbol",
        choices=["ETH-USD", "BTC-USD", "BNB-USD", "SOL-USD", "AVAX-USD"],
    )
    @option(
        "quantity",
        description="Quantity Of Crypto",
        type=int,
    )
    async def sell(self, ctx, symbol: str, quantity: int):

        await ctx.defer()

        try:
            quote = self.finnhub_client.quote(symbol=symbol)

            if quote:
                price = quote.get("c", 0)
                total_price = price * quantity

                cursor = self.conn.cursor()
                cursor.execute(
                    f"""
                    SELECT {symbol} FROM stocks WHERE user_id = ?
                    """,
                    (str(ctx.author.id),),
                )

                row = cursor.fetchone()

                if row:

                    crypto = row[0]

                    cursor.execute(
                        """
                    SELECT * FROM user_data WHERE discord_user_id = ?
                    """,
                        (str(ctx.author.id),),
                    )

                    row = cursor.fetchone()
#

                    if row:
                        user = row[2]

                    if crypto >= quantity:
                        console_channel = self.bot.get_channel(self.console_channel_id)
                        await console_channel.send(f"eco give {user} {total_price}")

                        await ctx.respond(
                            "Sell Successful, Confirmation On Its Way!", ephemeral=True
                        )

                        self.symbol = symbol
                        self.buy_price = price
                        self.price = total_price
                        self.quantity = quantity
                        self.user_id = ctx.author.id
                        self.channel_id = ctx.channel.id

                    else:
                        await ctx.respond(
                            "You Don't Have Enough Crypto To Sell", ephemeral=True
                        )

                else:
                    await ctx.respond(
                        "You Don't Have Enough Crypto To Sell", ephemeral=True
                    )

        except Exception as e:
            await ctx.respond(str(e), ephemeral=True)
            traceback.print_exc()
sage tendon
#

you arent deferring ephemerally

#

so you cant respond ephemerally either

mellow pebble
#

what da ok then what to do

mellow pebble
sage tendon
#

No, it doesnt

#

you cannot respond with ephemeral=True if your defer is not ephemeral

mellow pebble
#

ohh right right i did not use defer there

#

so what do i do

fresh sierra
#

does that will work await ctx.defer() -> await ctx.defer(ephemeral=True) since defer ephemeral does not exist with slash command ?

sage tendon
#

of course you can defer with ephemeral what do you mean

sage tendon
mellow pebble
#

ok ok

fresh sierra
#

or is it the invisible ?

sage tendon
#

luma

#

try it out

fresh sierra
#

cant really rn

sage tendon
#

it should be obvious

edgy nest
#

lemme just whip out the

mellow pebble
#

like as in await ctx.defer(ephemeral=True)

sage tendon
#

yes

mellow pebble
#

kk

fresh sierra
mellow pebble
#

kk

broken igloo
#

ok so

#

i am getting 100 messages

#

and i want to get almost all the messages

#

an algorithm i thought of is get 100 messages before DATE then reverse the list to get the oldest message and then store the timestamp of the message in DATE and repeat

little cobalt
broken igloo
#

the problem is the date is a bit weird in discord

sage tendon
#

not really

broken igloo
#

i wanna convert datetime object for the first iteration to discord's own timestamp

#

then

#

i wanna get the oldest message(which is done by reversing the list) and get the timestamp via message["timestamp"] but then if i pass that timestamp it says its not a snowflake

sage tendon
#

message.created_at

#

also, why do you wanna log so many messages?

fresh sierra
#

int(message.created_at.timestamp()) -> if you want to save it in ur database else it will raise an error about unix thing

sage tendon
#

and you can just set the limit to None in channel.history

#

but you should still set a limit else you're never gonna get done

broken igloo
sage tendon
#

yea but why

broken igloo
#

bc i need specific messages

sage tendon
#

and done

broken igloo
#

but since pycord doesn't support the user stuff we mentioned earlier

#

i have to use the raw discord api

sage tendon
#

what

#

you cant scrape messages in servers if you dont have a bot user in there

fresh sierra
#

its not pycord but discord that doesnt support that stuff

sage tendon
broken igloo
#

oh

#

ok imma stop then

sage tendon
#

why cant you just add a bot to the server lol

broken igloo
#

well i want to filter specific embed messages sent from another bot that is another server

#

basically the same thing can be done as a user but its kinda teadious

#

thats why i wanted to automate a script to search for you and output a list

tidal vessel
#

One question, can the input_type argument of an application command be of 2 types? I want the moderator to be able to enter a member or user ID

sage tendon
#

thats all encompassed by discord.Member

#

automatically
discord doesnt differentiate between that

#

which is usually more of a pain than a help

#

also to make your code a little shorter you can directly import slash_command from discord

tidal vessel
sage tendon
#

also fyi you can define type unions with type1 | type 2

#

starting python 3.9 i think

mild trout
#

how do i access the bot.get_guild from inside a ui view?

#

(view is in a cog file)

sage tendon
#

pass bot to the view constructor

#

or depending on your structure just self.bot if you have it passed to the cog already

mild trout
#

gotcha thanx you

fresh sierra
lofty parcel
mild trout
mild trout
# lofty parcel interaction.client also works

it isn't getting the guild

guild = interaction.client.get_guild(os.getenv("GUILD_ID"))
role = guild.get_role(int(os.getenv("LINKEDAC_ID")))

Error:
AttributeError: 'NoneType' object has no attribute 'get_role'

It was working fine when it was a command rather than a ui view

mild trout
#

thanx i forget about that

slate idol
#

I've started getting this error code today:

future: <Task finished name='Task-21' coro=<ApplicationCommandMixin.on_application_command_auto_complete.<locals>.callback() done, defined at C:\Users\kazer\AppData\Roaming\Python\Python39\site-packages\discord\bot.py:876> exception=NotFound('404 Not Found (error code: 10062): Unknown interaction')>
Traceback (most recent call last):
  File "C:\Users\kazer\AppData\Roaming\Python\Python39\site-packages\discord\bot.py", line 879, in callback
    return await command.invoke_autocomplete_callback(ctx)
  File "C:\Users\kazer\AppData\Roaming\Python\Python39\site-packages\discord\commands\core.py", line 1111, in invoke_autocomplete_callback
    return await ctx.interaction.response.send_autocomplete_result(
  File "C:\Users\kazer\AppData\Roaming\Python\Python39\site-packages\discord\interactions.py", line 1178, in send_autocomplete_result
    await self._locked_response(
  File "C:\Users\kazer\AppData\Roaming\Python\Python39\site-packages\discord\interactions.py", line 1288, in _locked_response
    await coro
  File "C:\Users\kazer\AppData\Roaming\Python\Python39\site-packages\discord\webhook\async_.py", line 222, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction```

It's a bit sporadic, but in response to a command which does use autocompletes.
sage tendon
#

show the command's code, and the autocomplete code

echo wraith
slate idol
#

Command is enormous, but starts with....

@bot.slash_command(description="For most types of rolls.",
    integration_types={discord.IntegrationType.guild_install,discord.IntegrationType.user_install}
    )
async def roll(
    ctx, 
    description: Option(str, "You must explain in a few words what you are rolling."),
    pool1: Option(str, autocomplete=discord.utils.basic_autocomplete(pool1_autocomplete), required=False),
    pool2: Option(str, autocomplete=discord.utils.basic_autocomplete(pool2_autocomplete), required=False),
    other: Option(int, "Add other modifiers to increase or decrease the final pool", max_value=15, required=False), 
    specialty: Option(str, "Add a die for a Specialty", autocomplete=discord.utils.basic_autocomplete(specialty_autocomplete), required=False), 
    ): 
    # 200 Lines of dice rolling complexity

Pool 1 Autocomplete:

async def pool1_autocomplete(ctx: discord.AutocompleteContext):
    statList = ["Strength", "Dexterity", "Stamina", "Charisma", "Manipulation", "Composure", "Intelligence", "Wits", "Resolve", "Glory", "Honor", "Wisdom", "Athletics", "Brawl", "Craft", "Driving", "Firearms", "Larceny", "Melee", "Stealth", "Survival", "Animal Ken", "Etiquette", "Insight", "Intimidation", "Leadership", "Performance", "Persuasion", "Streetwise", "Subterfuge", "Academics", "Awareness", "Finance", "Investigation", "Medicine", "Occult", "Politics", "Science", "Technology"]
    return statList```
sage tendon
#

why do you use autocomplete lol

#

just put that stuff as choices

slate idol
#

25 choices

sage tendon
#

right

#

does the error happen during the autocomplete or after you send the command

slate idol
#

Initially was happening during, but now seems to be after, and sometimes like... many seconds after the command has successfully resolved all its tasks.

sage tendon
#

if the command code takes more than 3 seconds you need to defer first

slate idol
#

Command is basically instant. It's the error that seems to pop up way later.

sage tendon
slate idol
#

That's the whole thing

sage tendon
#

hm
can you show the other autocompletes too

slate idol
#
async def pool2_autocomplete(ctx: discord.AutocompleteContext):
    statList = ["Strength", "Dexterity", "Stamina", "Charisma", "Manipulation", "Composure", "Intelligence", "Wits", "Resolve", "Glory", "Honor", "Wisdom", "Athletics", "Brawl", "Craft", "Driving", "Firearms", "Larceny", "Melee", "Stealth", "Survival", "Animal Ken", "Etiquette", "Insight", "Intimidation", "Leadership", "Performance", "Persuasion", "Streetwise", "Subterfuge", "Academics", "Awareness", "Finance", "Investigation", "Medicine", "Occult", "Politics", "Science", "Technology"]
    return statList```

```py 
async def specialty_autocomplete(ctx: discord.AutocompleteContext):
    with open('users.json','r')as f:
        users = json.load(f)
    target = str(ctx.interaction.user.id)
    skills = ["Athletics", "Brawl", "Craft", "Driving", "Firearms", "Larceny", "Melee", "Stealth", "Survival", "Animal Ken", "Etiquette", "Insight", "Intimidation", "Leadership", "Performance", "Persuasion", "Streetwise", "Subterfuge", "Academics", "Awareness", "Finance", "Investigation", "Medicine", "Occult", "Politics", "Science", "Technology"]
    specs = []
    if ctx.options["pool1"] != None:
        pool = ctx.options["pool1"]
        if pool in skills:
            if pool in users[target]['Specialties']:
                specs.append(users[target]['Specialties'][pool]) 
    if ctx.options["pool2"] != None:
        pool = ctx.options["pool2"]
        if pool in skills:
            if pool in users[target]['Specialties']:
                if pool not in specs:
                    specs.append(users[target]['Specialties'][pool])  
    if specs == []:
        specs = ["No Specialties"]
    return specs```
#

I haven't touched any of the autocompletes in several days.

sage tendon
#

i wouldn't recommend loading a file every single time, that will cause issues

#

load the file when the bot starts and save it in a variable somewhere

#

because every time you add a letter in the option it loads the file
and that isn't ideal

slate idol
#

It changes constantly

#

I could move the file loading further into the code, though.

sage tendon
#

try changing it to load on bot start and see if you can still reproduce the issue
if no, you could make a task that loads the file every 10s or so and saves it back to a variable

shell radish
sage tendon
#

yea i figured

#

i did much the same thing

slate idol
#

Usage frequency would need it to load every second at minimum, but that really hasn't been an issue for any of the bots I've made with way sloppier json-loading.

sage tendon
#

every second wtf

#

at that point i'd look into an async sqlite db lol

slate idol
#

Thousands of users all updating their (not-DnD) characters' stats whenever they feel like it.

sage tendon
#

thousands of users in a json

slate idol
#

Yeah I'll be migrating to something else before wide launch

sage tendon
#

how big is that file anyway

slate idol
#

It's tiny right now because it's in testing - again this isn't the problem though.

sage tendon
#

i'd say it is because i have no other idea shrug

slate idol
#

I'll switch out the json before mass launch.

#

11kb

lofty parcel
#

Or you could switch now and avoid a headache later tbh

slate idol
#

Yeah but again that's not what I'm here for help with

shell radish
sage tendon
#

no, a function that returns a list

rugged lodgeBOT
sage tendon
#

i think it handles the fuzzy-matching

slate idol
#

I'm sending it lists

sage tendon
#

not quite no

shell radish
#

maybe you're adding overhead to it so maybe just make it a list instead of a coro

sage tendon
#

you're passing functions that the basic_autocomplete calls

sage tendon
#

🤓

lofty parcel
#

🤓

sage tendon
#

well fr now tho guys

#

in everything they sent i can only imagine the file loading somehow getting stuck because the OS blocks so many accesses or whatever, so one instance just gets stuck and only gets done a few seconds after

#

wdyt

shell radish
#

i don't understand why discord.utils.basic_autocomplete is used here

specialty: Option(str, "Add a die for a Specialty", autocomplete=discord.utils.basic_autocomplete(specialty_autocomplete), required=False), 
    ):
lofty parcel
#

more than 25 options

shell radish
sage tendon
#

squid, it fuzzy matches

lofty parcel
#

She can't use choices

shell radish
#

you can return infinite options

slate idol
#

Specialties needs to check [pool1] and [pool2] to see if any of those are in the user's Specialties list

shell radish
#

discord just uses 25

sage tendon
#

basic autocomplete handles fuzzy matching

#

thats the entire point

slate idol
#

K let's just go ahead and remove all my autocompletes and see if that fixes it so we can get back ont rack.

lofty parcel
#

So you need to return options based off past options?

sage tendon
#

your autocompletes are the issue

#

nothing is off track here lol

slate idol
#

They weren't for weeks

lofty parcel
#

Can't we just try doing what toothy said

sage tendon
#

now they are

slate idol
#

They have not been touched.

lofty parcel
#

Pass the list to basic_autocomplete

#

Instead of a coro

shell radish
sage tendon
#

ok no i dont think that will change anything lmao

lofty parcel
#

Isn't it

sage tendon
#

my entire point is that i think loading the file so frequently is the issue
so i just want them to try with a globally loaded file once to rule it out

lofty parcel
#

Wouldn't it (assuming) raise an exception tho?

shell radish
#

why would it

sage tendon
#

why?

#

we can sit here discussing all day but something needs to be tried
and since my best guess is the file, i want to rule that out first
if that isnt the issue we can see on

lofty parcel
#

I'm brain storming ideas leave me alone 😭

slate idol
#

Waiting for the command to update, sorry.

shell radish
#

@slate idol can you profile your code by any chance?

slate idol
#

Explain?

shell radish
#

ok, nvm then

sage tendon
slate idol
#

I'm removing all autocompletes to make sure that's actually the problem

sage tendon
#

ah

#

well it is, the traceback clearly says so

slate idol
#

Thanks!

sage tendon
#

i thought you read it lol

rugged lodgeBOT
echo wraith
#

You can just do basic_autoconplete(my list)

sage tendon
#

paillat

#

they're doing checks inside of it

#

read up, please

shell radish
#

pool1 and pool2 should be lists, but that's not the issue

slate idol
#

K so I've commented out the stuff involving the json, and it freaked out on pool1 before even getting to specialties

#

They're more than 25 items.

shell radish
#

the amount of items shouldn't matter

slate idol
#

Otherwise I'd LOVE to make them lists, believe me.

echo wraith
#

Not in pool 1 and pool 2

slate idol
#

It throws me an error.

echo wraith
sage tendon
#

i'm 99% sure autocomplete can take lists >25 long

echo wraith
sage tendon
#

can you show your current code again

shell radish
#

when you say it freaks out during pool1 what happens specifically

slate idol
#
future: <Task finished name='Task-18' coro=<ApplicationCommandMixin.on_application_command_auto_complete.<locals>.callback() done, defined at C:\Users\kazer\AppData\Roaming\Python\Python39\site-packages\discord\bot.py:876> exception=NotFound('404 Not Found (error code: 10062): Unknown interaction')>
Traceback (most recent call last):
  File "C:\Users\kazer\AppData\Roaming\Python\Python39\site-packages\discord\bot.py", line 879, in callback
    return await command.invoke_autocomplete_callback(ctx)
  File "C:\Users\kazer\AppData\Roaming\Python\Python39\site-packages\discord\commands\core.py", line 1111, in invoke_autocomplete_callback
    return await ctx.interaction.response.send_autocomplete_result(
  File "C:\Users\kazer\AppData\Roaming\Python\Python39\site-packages\discord\interactions.py", line 1178, in send_autocomplete_result
    await self._locked_response(
  File "C:\Users\kazer\AppData\Roaming\Python\Python39\site-packages\discord\interactions.py", line 1288, in _locked_response
    await coro
  File "C:\Users\kazer\AppData\Roaming\Python\Python39\site-packages\discord\webhook\async_.py", line 222, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction```
sage tendon
#

show the code again that you have now

slate idol
#

Followed up on other stuff: In 8.options.1.choices: Must be 25 or fewer in length. In 8.options.2.choices: Must be 25 or fewer in length.

#

So returning to autocompleting them.

sage tendon
#

yea we never said to try choices lol

slate idol
#

K I misunderstood

sage tendon
#

all good

#

kinda confusing all this rn lol

slate idol
#

Then my code is unchanged?

sage tendon
#

can you remove the option that uses the autocomplete with the file in it, just to make sure that one is or isnt the problem
just wanna make sure which of the 3 autocompletes is the issue

#

doesnt matter if the command itself errors

slate idol
#
 async def specialty_autocomplete(ctx: discord.AutocompleteContext):
    skills = ["Athletics", "Brawl", "Craft", "Driving", "Firearms", "Larceny", "Melee", "Stealth", "Survival", "Animal Ken", "Etiquette", "Insight", "Intimidation", "Leadership", "Performance", "Persuasion", "Streetwise", "Subterfuge", "Academics", "Awareness", "Finance", "Investigation", "Medicine", "Occult", "Politics", "Science", "Technology"]
    specs = []
    if ctx.options["pool1"] != None:
        pool = ctx.options["pool1"]
        if pool in skills:
            #with open('users.json','r')as f:
                #users = json.load(f)
            #target = str(ctx.interaction.user.id)
            #if pool in users[target]['Specialties']:
                #specs.append(users[target]['Specialties'][pool]) 
            specs.append(pool)
    if ctx.options["pool2"] != None:
        pool = ctx.options["pool2"]
        if pool in skills:
            #with open('users.json','r')as f:
                #users = json.load(f)
            #target = str(ctx.interaction.user.id)
            #if pool in users[target]['Specialties']:
                #if pool not in specs:
                    #specs.append(users[target]['Specialties'][pool])  
            specs.append(pool)
    if specs == []:
        specs = ["No Specialties"]
    return specs```
#

Commented that bit out, sorry, that has changed.

sage tendon
#

okay so none of your autocompletes load a file anymore?

slate idol
#

Correct

#

Figured out what the other person meant, replacing Pool1 and Pool2 with a global variable which is a list.

sage tendon
#

yea at this point im kinda clueless

#

anyone else

slate idol
#
Traceback (most recent call last):
  File "C:\Users\kazer\AppData\Roaming\Python\Python39\site-packages\discord\commands\core.py", line 138, in wrapped
    ret = await coro(arg)
  File "C:\Users\kazer\AppData\Roaming\Python\Python39\site-packages\discord\commands\core.py", line 1082, in _invoke
    await self.callback(ctx, **kwargs)
  File "C:\Users\kazer\Documents\Programming\DiscordBot\W5\w5.py", line 2956, in roll
    await end_roll(titlage, response, ctx, users, hex, rpool, pool, bruteskies)
  File "C:\Users\kazer\Documents\Programming\DiscordBot\W5\w5.py", line 1821, in end_roll
    await ctx.respond(embed=embedVar)
  File "C:\Users\kazer\AppData\Roaming\Python\Python39\site-packages\discord\interactions.py", line 616, in respond
    return await self.response.send_message(*args, **kwargs)
  File "C:\Users\kazer\AppData\Roaming\Python\Python39\site-packages\discord\interactions.py", line 957, in send_message
    await self._locked_response(
  File "C:\Users\kazer\AppData\Roaming\Python\Python39\site-packages\discord\interactions.py", line 1288, in _locked_response
    await coro
  File "C:\Users\kazer\AppData\Roaming\Python\Python39\site-packages\discord\webhook\async_.py", line 222, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction

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

[part 2 coming:]

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

Traceback (most recent call last):
  File "C:\Users\kazer\AppData\Roaming\Python\Python39\site-packages\discord\bot.py", line 1137, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "C:\Users\kazer\AppData\Roaming\Python\Python39\site-packages\discord\commands\core.py", line 435, in invoke
    await injected(ctx)
  File "C:\Users\kazer\AppData\Roaming\Python\Python39\site-packages\discord\commands\core.py", line 146, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction```
sage tendon
#

now that just looks like the typical "taking more than 3s to respond" error to me

slate idol
#

K, but the command fires perfectly, so is there something it's waiting for that I'm not giving it? Like a return or something?

shell radish
#

?tag defer

limber wagonBOT
#

dynoError No tag defer found.

sage tendon
#

If you responded twice the error would say so

slate idol
#

Okay, so how do I send an embed for everyone to see AND an embed only the interacter can see?

sage tendon
#

yea thats hard

shell radish
#

await ctx.send and await ctx.respond(ephemeral=True)

slate idol
#

Send and respond, will try!

sage tendon
#

and tbh i have no idea how big bots do it that need tons of db requests before being able to figure out if its ephemeral

sage tendon
#

oh wait, and

#

i misread my bad

#

ignore what i said

shell radish
sage tendon
#

i think it's also possible to respond twice, just the second time non-ephemerally

shell radish
#

right, but it has a unloaded reference message

#

which is suboptimal

sage tendon
#

true

sage tendon
slate idol
#

I'd commented out the second response, though. So while I do have code for that right now it's:

embedVar = discord.Embed(title=titlage, description=response, color=hex)
    await ctx.send(embed=embedVar)
    if bruteskies != True:
        #await ctx.respond(view=RerollView(bot, rpool, pool), ephemeral=True)
        print("this should be a reroll View")```
shell radish
slate idol
#

Frustrating thing is, it's all executing fine, it's just throwing errors.

shell radish
#

then it's probably not fine?

sage tendon
#

can you just show your entire command code once

#

just send it doesnt matter if its long

shell radish
#

.pastebin

#

where did all the tags go

#

.paste

sly karmaBOT
#

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

shell radish
#

great

sage tendon
#

not a fan of pasteban tbh

#

no syntax highlighting makes it awful

shell radish
slate idol
sage tendon
#

okay just out of curiosity, since you arent using cogs, how long is your main file

slate idol
#

Too long. I've never taken a programming course so this is all a coblled together behemoth. It was under 800 lines before I got into trouble with Views... now it's 3500 lines

sage tendon
#

holy shit

shell radish
#

I have no idea what I'm supposed to be looking at

sage tendon
#

please please please use cogs

slate idol
#

It was just supposed to be a die roller 😅

#

Wanna teach an idiot how to?

sage tendon
#

no

shell radish
sage tendon
shell radish
#

what's the error again

slate idol
#

lol

sage tendon
#

also yea, looking at your command now, you absolutely have to switch to a database before you release
the current solution is just asking for conflicts

slate idol
#

based

sage tendon
shell radish
#

json's fine for beta tbh

sage tendon
slate idol
#

It was just supposed to be a die roller, then I learned too much.

#

"Oh I can store one thing... okay a few things... okay a whole dang character sheet.... move over DnD Beyond!"

#

FIXED

shell radish
#

there's no way we don't have a tag for defer-ing

#

@sage tendon is the tag just called something else

sly karmaBOT
#

Tag not found.

sage tendon
#

sure enough

sage tendon
slate idol
#

Thanks for all your help folks... and the many tangents ❤️

sage tendon
#

.defer

sage tendon
slate idol
#

Honestly not sure.

#

It feels like it's disappeared as mysteriously as it appeared. I'll try putting in my terrible json loading again

sage tendon
#

lol

#

me waiting for the json loading turning out to be the issue all along

shell radish
#

defer definitely helps

sage tendon
#
@discord.Cogs.listener()
  on_application_command(????)
    await ctx.defer()
    await self.bot.process_commands()

Like this right

shell radish
#

what

sage tendon
#

joking lol

shell radish
#

not one line of that makes sense 💀

sage tendon
#

cry about it

shell radish
# sage tendon cry about it
- @discord.Cogs.listener()
+ @discord.Cog.listener() # commands.Cog.listener() may work instead depending on the cog type
- on_application_command(????)
+ async def on_interaction(self, interaction):
-   await ctx.defer()
+   await interaction.response.defer() # all responses are no longer ephemeral unless forced by discord
-   await self.bot.process_commands()
+   await self.bot.process_application_commands(interaction)
sage tendon
#

okay nerd

shell radish
#

and this is a listener which means it doesn't even override the current event

#

so it doesn't even work

slate idol
#

Ummmm

#

..... I had two instances of the bot running. I was sitting here trying to figure out how a function I RENAMED was still firing.

shell radish
#

amazing

slate idol
sage tendon
#

bruhhhhh

shell radish
#

i reset my bot's token every month (when I had a bot that was actually online)

sage tendon
#

why?

shell radish
#

because security or something

sage tendon
#

whats gonna happen to your token if it only sits on your VPS

#

if its compromised changing it wont help
and nothing else can happen to your token really

shell radish
#

well, it didn't

flint talon
#

Hello!

I have a features.py file with the following function:

async def mass_ban_check(file_path, ctx, ban_amount: int, seconds_between_bans: int):
    while True:
        with open(f'{file_path}') as json_file:
            data = json.load(json_file)
            baninfo = data['fileinfo']['baninfo']
            print(baninfo)
            bans_within_timeframe = []
            time_frame = timedelta(seconds=seconds_between_bans)
            for i in baninfo:
                current_time = datetime.datetime.now()
                ban_time = baninfo[i]['data']['date']
                print(ban_time)
                if(current_time - ban_time <= time_frame):
                    bans_within_timeframe.append(baninfo)
            
            if len(bans_within_timeframe) >= ban_amount:
                print("Mass banning detected")
                #take action here

        await asyncio.sleep(1)

And then I have main.py where I try to call this function (I have already imported the function correctly):

@bot.command(description="Enable mass banning detection")
async def massbandetection(ctx, ban_amount: int, seconds_between_bans: int):
    await mass_ban_check("data.json", ctx=ctx, ban_amount=ban_amount, seconds_between_bans=seconds_between_bans)
    await ctx.respond("Successfully configured mass banning detection")

And it throws this error:
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: list indices must be integers or slices, not dict

I know that I am accessing the data.json file wrong, but I just can't seem to figure out how to access it right. Here is data.json:

#
{
    "fileinfo": {
        "baninfo": [
            {
                "data": {
                    "name": "GM peters#9338",
                    "server": "test",
                    "date": "2024-07-31 17:47:17.458763"
                }
            },
            {
                "data": {
                    "name": "GM peters#9338",
                    "server": "test",
                    "date": "2024-07-31 17:47:56.785292"
                }
            },
            {
                "data": {
                    "name": "GM peters#9338",
                    "server": "test",
                    "date": "2024-07-31 18:05:07.163366"
                }
            },
            {
                "data": {
                    "name": "GM peters#9338",
                    "server": "test",
                    "date": "2024-07-31 18:07:13.706827"
                }
            },
            {
                "data": {
                    "name": "GM peters#9338",
                    "server": "test",
                    "date": "2024-07-31 18:07:52.344879"
                }
            },
            {
                "data": {
                    "name": "GM peters#9338",
                    "server": "test",
                    "date": "2024-07-31 18:09:42.475643"
                }
            },
            {
                "data": {
                    "name": "GM peters#9338",
                    "server": "Zombs Combat Series [ZCS]",
                    "date": "2024-08-01 10:04:44.670617"
                }
            }
        ],
        "unbaninfo": [
            {
                "data": {
                    "name": "GM peters#9338",
                    "server": "test",
                    "date": "2024-07-31 18:09:52.577499"
                }
            }
        ]
    }
}
devout mirage
#

is the AutocompleteContext.options value for unrequired options the default value?

dense summit
dense summit
#

I dont see it idk why

fresh sierra
dense summit
shell radish
#

the issue is that channel isn’t a complete channel object

shell radish
#

try fetching/getting it instead

shell radish
dense summit
shell radish
#

sometimes discord just doesn’t give you the information

dense summit
#

one last question what is the difference between fetching and getting a channel?

shell radish
#

one is an api call, another is from cache, which may or may not exist

fresh sierra
#

.tag get_x

sly karmaBOT
#

Any function that starts with get_ in Py-cord is retrieving the related object from your bots cache. If the object is not in the bots cache the get_ method will return None. Because of this behavior you should check if the get_x method is None and if it is use the fetch_x method.

Why Is Using fetch_ Without Using get_ First Bad?
The fetch_ method makes a call to the discord API. This API call is unneeded if you already have the information. It will also make your command take longer because it will have to send and than wait for a response from the discord API. It will also contribute to the discord APIs global rate limit of 50 requests per second.

What Is Cache?
The cache is a temporary storage inside your bot. It holds many objects from members to messages. When you restart your bot the cache will be empty. When the cache is full it will delete older objects to make space for the new objects.

fresh sierra
#

idk who did this one but its really good

dense summit
#

so in my case it's probably better to use api calls as ticket channels probably dont always exist in cache

shell radish
#

it’s generally good to first get from cache then if it doesn’t exist, then fetch

dense summit
#

👍

flint talon
#

thats the point

#

it keeps running forever

#

and checks every second

#

for mass bans

graceful spindle
#

Hi im getting this error

#

discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access

#

Could anyone help please?

#

I have MFA enabled on my acccount
The bot has Administrator priviliges
the bot has scope application.commands

shell radish
#

Do you have guild_ids or debug_guilds anywhere in your code? If so, the bot isn't in one of those servers or the ID is not valid

graceful spindle
#

I do have debug_guilds

#

The ID is correct

#

Wait

#

I feel so stupid I had it set in a config

#

But i hadnt actually added the lines to actually pull from the config

#

Thanks for that

vague plaza
#

Yall know how long was the @ everyone markdown bug around for?

#

The one that will tag everyone but you won't see the @ everyone in the text

sage tendon
#

quite long

#

discord isn't really known for fixing bugs

vague plaza
#

like a year long or a few years long?

sage tendon
#

longer

vague plaza
#

das crazy

sage tendon
#

not really

#

I know so many bugs on discord

#

but even when you report them and they say they know about it they aren't fixed for years

lofty parcel
#

(He's known for mimimi'ing everything about bugs)

vague plaza
#

im curious

sage tendon
quartz umbra
#

Hello. I need a bit of help with autocomplete in cogs. Right now this is my code (in a Cog class):


    @embed_group.command(
        description="Send an Embed from the defined Embed List (Check source code)"
    )
    @commands.has_permissions(administrator=True)
    async def send(self, ctx: ApplicationContext, embed: discord.Option(str, autocomplete=discord.utils.basic_autocomplete(self.get_embed_names))) -> None:  # type: ignore
        for i in self.LIST:
            if i["name"] != embed:
                continue
            # This is the embed we want to send
            await ctx.channel.send(content=i["content"], embed=i["embed"], view=i["view"])  # type: ignore
            await ctx.respond("Successfully sent embed to this channel", ephemeral=True)

    async def get_embed_names(self, ctx: discord.AutocompleteContext):
        output = []
        for i in self.LIST:
            output.append(i["name"])
        return output

However, I get this error: ```
async def send(self, ctx: ApplicationContext, embed: discord.Option(str, autocomplete=discord.utils.basic_autocomplete(self.get_embed_names))) -> None: # type: ignore
^^^^
NameError: name 'self' is not defined

Can somebody tell me what I'm doing wrong?
quartz umbra
sage tendon
#

nvm im blind sorry

#

yea you can't use self inside of the function header like that i'm p sure

#

thats not how OOP works in python

#

also why is your setup def not bot.add_cog(...) lol

little cobalt
#

lol

quartz umbra
quartz umbra
sage tendon
#

what

quartz umbra
#

omg

#

not typehinting, like i forget the word

#

autocomplete

sage tendon
#

I'd recommend putting that into a util class or somewhere

quartz umbra
sage tendon
#

AutocompleteUtil.get_embed_names lol

#

the problem is really just that you dont have access to self. inside of the function header

#

anything else works fine

quartz umbra
#

ok bet

sage tendon
#

or import the function directly by name then its a little shorter

#

regardless of anything i still recommend using the @discord.option decorator over typehinting

quartz umbra
#

but the issue remains that i'm using self.LIST in that function

sage tendon
#

Put that inside of the autocomplete util class

quartz umbra
#

hmm, ok, thanks

#

What does this error mean and how to fix it? ```py
File "embed_helper.py", line 14, in <module>
"view": SetActivityView(),
RuntimeError: no running event loop


embed_helper.py ```py
from views.tester_activity_view import SetActivityView
from discord import Embed, EmbedField
import discord

LIST = [
    {
        "name": "set activity",
        "content": "",
        "embed": Embed(
            title="Set Activity Status",
            description="As part of our new testing system, use the 2 buttons below to get tickets to test.",
            color=0x3333FF,
        ),
        "view": SetActivityView(),
    }
]


async def get_embed_names(ctx: discord.AutocompleteContext):
    output = []
    for i in LIST:
        output.append(i["name"])
    return output
#

can i remove the brackets (SetActivityView() -> SetActivityView) and then use it as:

ctx.respond(view=embed_helper.LIST[0]["view"]())
sage tendon
#

Put it into a class

quartz umbra
quartz umbra
#

Why is my interaction failing with my view even though there is no error in console? (I'm for sure this is the only active token)

sage tendon
#

show the button callback

quartz umbra
# sage tendon show the button callback

i will in a sec, but i'm finally getting an error out of this: ```py
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction

ik to fix this in a command you do `await ctx.defer()`, but what to do in a button callback with only an `Interaction`?
#
@discord.ui.button(
        label="I'm Online", style=discord.ButtonStyle.primary, emoji="✅"
    )
    async def active_callback(self, button, interaction: discord.Interaction):
        # Check if a tester is active already
        tester_info = firebase_helper.get_tester(interaction.user.id)  # type: ignore incorrect null
        if tester_info == None:
            embed = discord.Embed(title="You're not a tester?!?", color=0xFF3333)
            await interaction.response.send_message(embed=embed, ephemeral=True)
            return
        if tester_info["isActive"]:
            embed = discord.Embed(title="You're already active!", color=0x33FF33)
            await interaction.response.send_message(embed=embed, ephemeral=True)
            return

        # Give the tester the active role
        active_role_id = config_helper.get_rank_role_id("online")
        active_role = interaction.guild.get_role(active_role_id)  # type: ignore it is NOT None

        inactive_role_id = config_helper.get_rank_role_id("offline")
        inactive_role = interaction.guild.get_role(inactive_role_id)  # type: ignore
        if active_role != None:
            await interaction.user.add_roles(active_role, reason="online")  # type: ignore
        if inactive_role != None:
            await interaction.user.remove_roles(inactive_role, reason="online")  # type: ignore
        # Create tickets for the tester
        tickets: list[int] = await self.createTickets(
            interaction, interaction.user, tester_info
        )

        # Update tester doc
        firebase_helper.set_tester_active(interaction.user.id)  # type: ignore
        embed = discord.Embed(
            title="You are now active.",
            description="Check your channels, tickets should have automatically been made and assigned to you.",
            color=0x33FF33,
        )
        await interaction.response.send_message(embed=embed, ephemeral=True)
sage tendon
#

404 typically means you take more than 3 seconds to respond

#

in which case you have to use await ctx.defer() as the first line in your callback

quartz umbra
sage tendon
#

ah yea interaction.response.defer

quartz umbra
#

bet

#

now what does this error mean?

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

I think it's coming from this line: await interaction.response.send_message(embed=embed, ephemeral=True), but its definitely from this code block in the callback: ```py
tester_info = firebase_helper.get_tester(interaction.user.id) # type: ignore incorrect null
if tester_info == None:
embed = discord.Embed(title="You're not a tester?!?", color=0xFF3333)
await interaction.response.send_message(embed=embed, ephemeral=True)
return
if tester_info["isActive"]:
embed = discord.Embed(title="You're already active!", color=0x33FF33)
await interaction.response.send_message(embed=embed, ephemeral=True)
return

#

now though the error seems self explanatory, how could it be responded to before if i've never pressed the button before

sage tendon
#

maybe interaction defers have to be responded to in a different way, no idea

quartz umbra
#

hmm

sage tendon
#

never do much with views, maybe someone else knows

quartz umbra
sage tendon
#

also why do you have #type: ignore everywhere

quartz umbra
sage tendon
#

vsc?

quartz umbra
sage tendon
#

yea vsc is dumb

errant trout
#

(it's technically correct for annoying reasons but just don't use a typechecker lol)

sage tendon
#

because its a union and MIGHT be null?

errant trout
#

no, it's actually defined as None but doesn't know how to interpret the custom property decorator we use

sage tendon
#

ah

quartz umbra
#

well, my issue is definitely with the line: ```py
await interaction.response.send_message(embed=embed, ephemeral=True)

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

errant trout
#

just use interaction.respond

#

it handles defers for you

quartz umbra
errant trout
#

(if you defer then it's interaction.followup.send, so we added a generic respond function to streamline it)

quartz umbra
#

yep, back to ```py
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction

sage tendon
#

you are still deferring right

quartz umbra
sage tendon
#

no

#

defer.

quartz umbra
#

ok i'm testing interaction.followup.send() + defer

sage tendon
#

just defer and then respond

#

bruh

fresh sierra
#

respond will basically use interaction.response if the interaction hasn’t be responded else it will use interaction.followup

#

So if you use respond u don’t need to care about response or followup

deft kestrel
#

Can i use the auto complete feature based on a server?

#

(Option)

sage tendon
#

sure

nova epoch
#

Dumb and very late questio but does 2.6 support user installs?

little cobalt
lapis dock
#

yes

echo wraith
#

How can I specify which shard a bot connects to

echo wraith
#

just to be clear, shard_count has to be the total shard count or the count of shards this instance connects to?

errant trout
#

however many you're connecting to

echo wraith
#

yeah but like in total, or with that instance

errant trout
#

uhhh

echo wraith
#

cuz I want to be able to split up the thing in multiple containers

errant trout
#

ah

#

hmm... probably within that instance? how many guilds are you in

echo wraith
#

I have to check

#

but enough

#

And it's not like I want to now make it in multiple containers

#

I just want to prepare for doing it later

#

and also have high availability and stuff like that

errant trout
#

the docs only really talk about sharding, beyond that if you're doing multiple instances then i'd presume shard_count is for each individual instance

#

(not much will happen if you get it wrong anyway)

echo wraith
#

ok that's also easier so better that

echo wraith
deft kestrel
#

how i can connect the bot to the channel i am in?

echo wraith
#

or smth

rugged lodgeBOT
echo wraith
#

this

deft kestrel
echo wraith
rugged lodgeBOT
echo wraith
#

.channel

deft kestrel
rugged lodgeBOT
#

examples/basic_voice.py lines 63 to 70

@commands.command()
async def join(self, ctx: commands.Context, *, channel: discord.VoiceChannel):
    """Joins a voice channel"""

    if ctx.voice_client is not None:
        return await ctx.voice_client.move_to(channel)

    await channel.connect()```
echo wraith
#

when can I add @rugged lodge 's rtfm to my user so i can use it in dms and wvweywee

errant trout
#

code is right there

shadow sigil
#

how hard is it to turn prefixed commands into slash commands?

echo wraith
little cobalt
shadow sigil
#

mostly just curious

#

anything i should keep in mind while doing that

errant trout
#

and ctx.message might not be reliable

#

that's about it

#

if the command takes more than 3 seconds for the first response, defer at the start

shadow sigil
echo wraith
shadow sigil
#

aha

#

alright

errant trout
# shadow sigil how so?

interaction commands are a bit different, so it's best not to rely on it - you generally won't need it anyway, there are several shortcuts under ctx

quartz umbra
#

when will self.bot.user.avatar be None in a Cog?

fresh sierra
#

When user will not be cached ig

#

But it should do None has no attribut avatar ig

quartz umbra
#

This is the code: ```py
embed = discord.Embed(
title="Server PvP Leaderboard",
footer=discord.EmbedFooter(
text="PvP Practice Bot", icon_url=self.bot.user.avatar.url # type: ignore
),
color=discord.Colour.from_rgb(50, 127, 168),
description="See the Top 10 Overall best PvPers below:",
image="attachment://image.png",
)

and the error: ```
text="PvP Practice Bot", icon_url=self.bot.user.avatar.url  # type: ignore
                                      ^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'url'
errant trout
#

eh

errant trout
#

but also, display_avatar will guarantee an avatar is returned by using a default avatar if for some reason the user one doesn't exist

flat wind
#

Hello,
What is the best practice to initialize aiosqlite database in discord bot ? I am actually using an asyncio.run() function but it seems to not be the right method because it breaks all tasks.loop() (I don't really know because I am not using loops but someone told me this)

rugged lodgeBOT
echo wraith
#

so make an async def main function

#

in there you put

  1. Your database logic
  2. await bot.start()

then if __name__ == "__main__" you asyncio.run(main())

flat wind
# echo wraith use await bot.start()
async def main():
    bot.db, bot.cursor = await connect_database()
    # Load cogs
    for filename in os.listdir('./cogs'):
        if filename.endswith('.py'):
            bot.load_extension(f'cogs.{filename[:-3]}')

    # Run the bot
    bot.start(TOKEN)

if __name__ == '__main__':
    asyncio.run(main())
echo wraith
#

other than that, yeah that should work I think

flat wind
flat wind
#

but if I don't put it, everything work lol

echo wraith
#

that is wierd

echo wraith
flat wind
#

weird, it does not work anymore.... I will troubleshoot from myself

quartz umbra
#

Okay

flat wind
echo wraith
#

.tag logging

sly karmaBOT
flat wind
echo wraith
#

my goal is to see if bot.start actually dosen't do anything, of it this:

    bot.db, bot.cursor = await connect_database()
    # Load cogs
    for filename in os.listdir('./cogs'):
        if filename.endswith('.py'):
            bot.load_extension(f'cogs.{filename[:-3]}')

for some reason does not complete and blocks the start

furthermore, if you enable info logging like explained in the link above, you will clearly see if bot.start is being executed or not

#

and make sure to keep await on bot.start

flat wind
echo wraith
#

sure

flat wind
# echo wraith sure

the logging does not do anything more than printing the cogs prints, and the result of a print of bot.db and bot.cursor is <Connection(Thread-1, started 137563283130048)> <aiosqlite.cursor.Cursor object at 0x7d1cf3405010>. I have also added prints after cogs and it works, but it does not pass the start. I have added a print after too

async def main():
    bot.db, bot.cursor = await connect_database()
    print(bot.db, bot.cursor)
    # Load cogs
    for filename in os.listdir('./cogs'):
        if filename.endswith('.py'):
            bot.load_extension(f'cogs.{filename[:-3]}')
    print('===== Cogs are loaded ! =====')
    # Run the bot
    await bot.start(TOKEN)
    print('===== Bot is running ! =====')
echo wraith
#

explained in

#

.tag logging

sly karmaBOT
echo wraith
#
import logging

logging.basicConfig(level=logging.INFO)
flat wind
#

and I have a warning about PyNaCl for the voice but I personaly don't care

echo wraith
flat wind
#

and this after 10secs :

WARNING:discord.gateway:Shard ID 0 heartbeat blocked for more than 10 seconds.
Loop thread traceback (most recent call last):
  File "/app/main.py", line 199, in <module>
    asyncio.run(main())
  File "/usr/local/lib/python3.12/asyncio/runners.py", line 194, in run
    return runner.run(main)
  File "/usr/local/lib/python3.12/asyncio/runners.py", line 118, in run
    return self._loop.run_until_complete(task)
  File "/usr/local/lib/python3.12/asyncio/base_events.py", line 672, in run_until_complete
    self.run_forever()
  File "/usr/local/lib/python3.12/asyncio/base_events.py", line 639, in run_forever
    self._run_once()
  File "/usr/local/lib/python3.12/asyncio/base_events.py", line 1947, in _run_once
    event_list = self._selector.select(timeout)
  File "/usr/local/lib/python3.12/selectors.py", line 468, in select
    fd_event_list = self._selector.poll(timeout, max_ev)

I had it 3 times

echo wraith
#

what loop tasks do you set up

#

can you show me

flat wind
#

I don't have any loop

echo wraith
#

or I missunderstood?

#

wait no I missread mb

#

can you show me your on_ready and on_shard_ready then?

#

any any other listener that you might have (on_message, etc...)?

flat wind
#

(I don't really know because I am not using loops but someone told me this)

I just wanted the best practice for initializing an aiosqlite db without breaking anything in case I need it in the future

echo wraith
flat wind
# echo wraith any any other listener that you might have (on_message, etc...)?

Yeah I have on_raw_reaction_add and on_message.

Here is my on_shard_connect :

# On shard connect
@bot.event
async def on_shard_connect(shard_id):
    print(f"=== Shard {shard_id}/{bot.shard_count-1} is ready ! ===")

And my on_ready :

# On ready
@bot.event
async def on_ready():
    await bot.cursor.execute("""
        CREATE TABLE IF NOT EXISTS default_guild_language(
        guild_id TEXT,
        default_language TEXT,
        reaction_activated TEXT
        )
    """)
    await bot.cursor.execute("""
        CREATE TABLE IF NOT EXISTS DMUser(
        user_id TEXT,
        yesno TEXT
        )
    """)
    await bot.cursor.execute("""
        CREATE TABLE IF NOT EXISTS reversed(
        guild_id TEXT,
        channel_id TEXT,
        language_1 TEXT,
        language_2 TEXT
        )
    """)
    await bot.cursor.execute("""
        CREATE TABLE IF NOT EXISTS channel_language(
        guild_id TEXT,
        channel_id TEXT,
        language TEXT
        )
    """)
    await bot.cursor.execute("""
        CREATE TABLE IF NOT EXISTS force_reaction(
        guild_id TEXT,
        forced TEXT,
        minimalist TEXT,
        timeout TEXT
        )
    """)
    await bot.cursor.execute("""
        CREATE TABLE IF NOT EXISTS linkchannels(
        guild_id TEXT,
        channel_id_1 TEXT,
        channel_id_2 TEXT,
        language_1 TEXT,
        language_2 TEXT
        )
    """)
    await bot.cursor.execute("""
        CREATE TABLE IF NOT EXISTS langinfo(
        guild_id TEXT,
        info TEXT
        )
    """)

    print('===== Translator Bot is ready ! =====')
sage tendon
#

blocking code at all

#

doesn't matter where

echo wraith
#

WARNING:discord.gateway:Shard ID 0 heartbeat blocked for more than 10 seconds.

#

for (dumb) example:
time.sleep(x) await asyncio.sleep(x)

#

.tag asynciodebug

sly karmaBOT
#

Tag not found.

echo wraith
#

@flat wind can you set debug=True in your asyncio.run(main())

flat wind
# echo wraith <@341257685901246466> can you set debug=True in your asyncio.run(main())
WARNING:asyncio:Executing <Task pending name='Task-1' coro=<main() running at /app/main.py:194> wait_for=<Future pending cb=[shield.<locals>._outer_done_callback() at /usr/local/lib/python3.12/asyncio/tasks.py:922, Task.task_wakeup()] created at /usr/local/lib/python3.12/asyncio/base_events.py:448> cb=[_run_until_complete_cb() at /usr/local/lib/python3.12/asyncio/base_events.py:181] created at /usr/local/lib/python3.12/asyncio/runners.py:100> took 1.141 seconds
echo wraith
#

@flat wind What I think is that somewhere in your code, there is a piece of blocking code. Can you try adding one cog at a time and see when it stops working? Like you test with one, then two, etc... And also see if it works with no cogs.

flat wind
#

Okay I will test with no cogs and see

sage tendon
#

or just read the code and find the blocking bit

flat wind
#

without cogs it does not start either, this means the error is in the main file

echo wraith
flat wind
echo wraith
flat wind
echo wraith
#

the one you are trying to run rn

flat wind
#

1, because it is the "test version" of my real bot in around 13k servers

echo wraith
#

add a check to only use it in prod

flat wind
#

always worked before the edits I have just made with you today

#

I know it is not the best practice, but this is only for a test

sage tendon
#

that's not the issue

echo wraith
flat wind
shadow sigil
#

is there a way to deal with slash command changes not showing up or do you just have to restart discord

sage tendon
#

restart

#

takes 3 seconds lol it's not a big deal

#

and you typically don't add commands every 2 minutes

shadow sigil
#

i mean first of all, i actually am adding commands every 2 minutes
and even when i'm not, i'm probably changing them every 2 minutes

sage tendon
#

code changes don't count btw

shadow sigil
#

they don't, but description, autocomplete, and stuff like that seems to

sage tendon
#

yea but I mean
again
typically you don't change that all that often

shadow sigil
#

usually

#

does this library have support for application emojis?

sage tendon
#

not in 2.6 yet, but it's in master im p sure

shadow sigil
#

on an unrelated note, i just realized what this pfp is lol

sage tendon
#

what pfp

shadow sigil
#

yours

sage tendon
#

oh, lol

shadow sigil
sage tendon
#

you can use it now if you want to

errant trout
sage tendon
#

ah nvm

#

thought it got merged

errant trout
#

sometime

shadow sigil
#

eventually™️

echo wraith
#

before gta6

flint talon
#

cant make required option

#

@discord.option(
name="spam",
description="Mention spam?",
choices=["Yes", "No"],
default="Yes",
required=True
)

#

just shows up as 3 optional in slash command

sage tendon
#

required=True isnt needed

#

and restart discord to see any changes

flint talon
sage tendon
#

and make sure to put required options before optional ones

flint talon
#

I restart the app and discord every time

flint talon
sage tendon
#

show your code and what you see in discord

#

also, remove the default

#

that might be the issue

flint talon
sage tendon
#

the default kwarg

lapis dock
#

If it is required it cannot have a default. So that is most likly the issue.

stray cargo
#

How do i install pycord? Most of the guide is all over the place,and as a beginner,i feel overwhealmed

tidal vessel
#

One question, what is the difference between View.parent.message and View.message?

Do they both allow me to access the View object's message?

tidal vessel
lofty parcel
#

I'd assume View.parent wouldn't work for normal messages

tidal vessel
lofty parcel
#

Yes. self is your view.

tidal vessel
#

ok, thank you very much!

lofty parcel
#

As toothy said, that's literally what the docs say at the beginning.

quartz relic
#

stupid question, has pycord made a way to handle/use application emojis?

shell radish
quartz relic
#

ty!

chrome plover
#

hello, I have a interaction setup where after a user interacts with a button I have it defer on the first line and then later on I want to send a modal but because I have already deferred I'm not able to send the modal as it can't use followup.

Am I forced to just remove the earlier defer?

chrome plover
#

hmm

lofty parcel
#

You can't defer and send a modal. The modal must be the first response.

chrome plover
#

I just feel like that will cause people issues with slower internet

#

Because I have some processes before I have to use the modal

lofty parcel
#

Do the processes outside the button.

chrome plover
#

hmm

#

I guess so

#

yea

#

alright thanks

river oriole
#

How can I get all Messages from a Thread?

sage tendon
#

p sure you can just use .history just like for a channel

river oriole
#

Oh right. Not sure how I missed this. Thank you

shadow sigil
sage tendon
#

if it's so little code you can just send it here

#

and no

#

name and type are positional, just do
discord.option("name", str, autocomplete=...

#

the second option is right but you can just use str instead of the slash command option type, it's shorter

#

oh and if you use the decorator, remove the Option typehint in the function header

shadow sigil
#

it didn't feel like very little code
oh well

sage tendon
#

here, quite a big example from my bot

shadow sigil
#

    @discord.slash_command(name="image")
    @discord.option(
        "name",
        str,
        autocomplete=discord.utils.basic_autocomplete(single_image_name),
    )
    @discord.option(
        "image",
        str,
        choices=["image", "thumbnail", "none"],
    )
    @discord.option(
        "show", str, autocomplete=discord.utils.basic_autocomplete(single_image_show)
    )
    async def single_image(
        self,
        ctx: discord.ApplicationContext,
        name: str = None,
        image: str = "image",
        show: str = None,
    ) -> None:
```so more like this?
sage tendon
#

yes

#

but you don't have to do = None, it'll be None by default

#

and if you want to you can leave the str away entirely in the decorator like I did, string is the default option type

shadow sigil
#

alright

shadow sigil
sage tendon
#

ah
yea I never put defaults in the function header, I just use the decorator

shadow sigil
#

also, how does the name work?

sage tendon
#

?

#

where

shadow sigil
#

in discord.option

sage tendon
#

I mean you're already using it lol

#

wdym

shadow sigil
#

i guess this is more of a question of how @discord.option works

#

does name have to be the same as the argument name in the function

sage tendon
#

no

shadow sigil
#

or is it just the first option coresponds to the first argument, second option - second argument, etc

sage tendon
#

if you set a name that's different from the parameter name, you can use parameter_name= to match it onto the parameter

shadow sigil
#

aha, okay

shadow sigil
#

adds an option with the name of the self/context parameters slugboom

solid sapphire
#

Hi! I've discovered discord.Bot.slash_group decorator, but I'm having some issues with using it. Can someone please help me?
My code:

import discord

bot = discord.Bot()


@bot.slash_group()
async def hello(ctx):
    await ctx.respond("Hello!")

DISCORD_TOKEN = ''
bot.run(DISCORD_TOKEN)

I'm getting:

Traceback (most recent call last):
  File "C:\Users\Admin\PycharmProjects\discordBots\main.py", line 7, in <module>
    async def hello(ctx):
  File "C:\Users\Admin\PycharmProjects\discordBots\.venv\lib\site-packages\discord\bot.py", line 1038, in inner
    group = cls(
TypeError: hello() got an unexpected keyword argument 'guild_ids'

sage tendon
#

just use the normal way of making slashcommand groups, never seen the decorator be used

solid sapphire
#

That is what I am going to do if I'm unable to figure out what is wrong. I've been searching for someone having the same issue and I've discovered someone suggesting using it #977541067006152764 message

sage tendon
#
group = discord.SlashCommandGroup(...)

@group.command()
async def...
shut fox
#

how to get roll id with role name?

sage tendon
#

you cant because its not unique, for all i know

#

why do you only have the name?

sage tendon
shut fox
sage tendon
#

yea, again, why do you only have the name

#

select menus can be role selections

solid sapphire
#

okay, then another question:

#

is there any way to have a slash group and a slash command named the same?
e.g.
/hello
/hello everyone

sage tendon
#

no

solid sapphire
#

I thought it might be using that decorator since it is how prefixed command discord.ext.commands.Bot.group() decorator work

#

since it decorates some callback function

sage tendon
#

you can use the docs search :>

shadow sigil
#

is there a way to stop the advancing to the next parameter when selecting an option on a slash command?

sage tendon
#

yea

#

just hit enter lol

#

dont press tab

shadow sigil
#

yeah, even if press enter it still does that

#

as well as clicking on an option

sage tendon
#

then that option is required

shadow sigil
#

i feel like you're misunderstanding what i mean by option

sage tendon
#

then tell me

#

or show, rather

shadow sigil
#

clicking on one of these makes the cursor go to the next parameter (if there is one)

sage tendon
#

that's a choice

#

and just hit back once

shadow sigil
#

i mean
i guess

#

it's just a bit annoying to have to do that

sage tendon
#

blame discord

#

typically you put the least oftenly used options at the end so that isnt usually an issue

shadow sigil
sage tendon
#

and it only happens with choices so shrug

#

imo its better to have this than not

#

would be annoying otherwise

shadow sigil
#

i tried it on mobile and how it works there is especially annoying lmao

sage tendon
#

general rule on discord, dont use mobile

shadow sigil
#

so true

fresh sierra
#

how should i typehint that and what is wrong about the wrapper ?

#
Argument of type "(ctx: LumabotContext) -> bool" cannot be assigned to parameter "predicate" of type "Check" in function "check"

```
shell radish
#

Callable[bool]

fresh sierra
#

idk if its my setting or not

shell radish
#

nvm I forgor how Callable works

#

it's Callable[context, bool]

sage tendon
#

how can you typehint the callable's return type tho

shell radish
#

context should probably be like [Union[ApplicationContext, commands.Context, bridge.Context]]

sage tendon
#

or like is it always the last parameter there

shell radish
#

[[args], return_type]

#

I don't know what language I'm using anymore

fresh sierra
#

like so you mean ?

#

because it still return that error

shell radish
#

that is what docs says check returns

fresh sierra
#

well all of that is losing me

shadow sigil
#

what does an option with type discord.SlashCommandOptionType.channel give?

sage tendon
#

all channels i suppose

shadow sigil
#

what does it give to the parameter

errant trout
#

wdym

sage tendon
#

its an enum

#

probably just some number

errant trout
lofty hedge
#

damn

sage tendon
#

unknown integration means you need to restart discord i think

shadow sigil
#

how can you check if the person using a command has a certain permission (like manage server)

echo wraith
#

.rtfm discord.default_permission

sly karmaBOT
echo wraith
#

maybe this?

#

it allows the admins to change the permission needed easily to allow more flexibility

shadow sigil
#

alright

sage tendon
#

yes, you should use that one

shadow sigil
#

also, is there a type or something for all guild channels

shadow sigil
#

type, not property or method

shell radish
shut fox
#

guys, im trying to add role but writes error:

Ignoring exception in view <RoleChoice timeout=180.0 children=1> for item <Select type=<ComponentType.string_select: 3> placeholder='Какою роль выдаём' min_values=1 max_values=1 options=[<SelectOption label='Cha-Cha Bridge' value='Cha-Cha Bridge' description=None emoji=None default=False>, <SelectOption label='Breezily Bridge' value='Breezily Bridge' description=None emoji=None default=False>, <SelectOption label='FruitBerries Bridge' value='FruitBerries Bridge' description=None emoji=None default=False>, <SelectOption label='MoonWalk Bridge' value='MoonWalk Bridge' description=None emoji=None default=False>, <SelectOption label='God Bridge' value='God Bridge' description=None emoji=None default=False>, <SelectOption label='Dao Telly' value='Dao Telly' description=None emoji=None default=False>, <SelectOption label='Telly' value='Telly' description=None emoji=None default=False>, <SelectOption label='Dao Speed Telly' value='Dao Speed Telly' description=None emoji=None default=False>, <SelectOption label='Speed Telly' value='Speed Telly' description=None emoji=None default=False>] channel_types=[] disabled=False>:
Traceback (most recent call last):
File "C:\Users\V\PycharmProjects\ilias_Projects\venv\lib\site-packages\discord\ui\view.py", line 426, in _scheduled_task
await item.callback(interaction)
File "C:\Users\V\PycharmProjects\ilias_Projects\bots\FCB\main.py", line 78, in select_callback
await athr.add_roles(role)
File "C:\Users\V\PycharmProjects\ilias_Projects\venv\lib\site-packages\discord\member.py", line 1026, in add_roles
await req(guild_id, user_id, role.id, reason=reason)
File "C:\Users\V\PycharmProjects\ilias_Projects\venv\lib\site-packages\discord\http.py", line 367, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50013): Missing Permissions

im trying fix this 2 hours but nothing

sage tendon
#

you dont have permissions to do that

#

really simple

echo wraith
echo wraith
sage tendon
#

i mean thats a basic thing about permissions on discord

#

or anywhere really

shell radish
# shut fox rly

or the person that you're trying to to modify has higher privileges than your bot

shadow sigil
#

can ctx.respond be used for ephemeral messages?

sage tendon
#

yes

shadow sigil
#

do you just put ephemeral=True in it?

sage tendon
#

yes

shadow sigil
#

okay

lapis dock
#

@frigid topaz you can have a maximum of 5 rows of components per message.
A select menu takes up and entire row. You can put 5 buttons in 1 row.

#

So maximum of 5 selects or 25 buttons or a combination

#

Also there are special select menu types for roles and channels. So you dont have to fill your own and be limited to 25 per select.

#

That might solve your issue

shadow sigil
#

can a button callback "return" a value or something like that

errant trout
#

there's view.wait which waits for a view to stop - if you manipulate this correctly, it'd more or less get the result you desire

shadow sigil
#

more or less, a function that creates a view, and if the user clicks button A, then X happens, but if the user clicks button B, then Y happens.
A and B would be the same, but X and Y differ depending on where it's called

errant trout
#

so you don't want to use callbacks for the rest of the logic?

shadow sigil
#

more so i don't know how i would use them

errant trout
#

so there's a few relevant examples here

rugged lodgeBOT
#

Here's the counter example.

errant trout
#

this demonstrates using a View class with button decorators, logic in the callback

rugged lodgeBOT
#

Here's the button roles example.

errant trout
#

this is a bit more complex using Button subclassing

rugged lodgeBOT
#

Here's the confirm example.

errant trout
#

and this is the alternative solution, which uses view.wait to do all the logic in the original function

#

(if you're familiar with Bot.wait_for, it's similar)

shadow sigil
#

huh
okay

river oriole
#

I have a SlashCommandGroup with checks but for some reason they don't run for commands in that group

That is the SlashCommandGroup

mm = SlashCommandGroup(
        name="modmail",
        description="Commands related to ModMail",
        checks=[commands.guild_only(), isStaff()],
    )

And this the isStaff predicate

async def staffPredicate(ctx: commands.Context) -> bool:
    try:
        assert CONFIG.STAFF_ROLE_ID in [role.id for role in ctx.author.roles]
    except AssertionError:
        raise notStaffMember("You are not a staff")

    return True


def isStaff() -> bool:
    return commands.check(predicate=staffPredicate)

Does anyone know why it doesn't work?

errant trout
river oriole
#

The commands itself work. But the check isnt running

errant trout
#

as in, remove the () in checks

#

i might be completely wrong though

river oriole
#

oh

errant trout
#

forgot whether it's necessary

river oriole
#

Throws this error when I dont have it as function

TypeError: guild_only() takes 0 positional arguments but 1 was given
errant trout
#

the example shows commands.guild_only().predicate instead i guess...?

#

so perhaps it takes predicates directly

#

(also aside, you don't really need the guild_only check because you could set guild_only=True instead)

river oriole
#

oh true. forgot about that

#

It fails when I dont have it as function. When I use the predicate directly for my custom one, then it needs the context as arg

shadow sigil
shadow sigil
#

hm
is it possible to send a follow up message that has the [user] used [command] rather than being a reply to the previous message

shell radish
#

no

shadow sigil
#

what shows up to other users when the first message is ephemeral, while the follow up isn't?

shell radish
#

followups to completed responses cannot be ephemeral

shadow sigil
#

...what

shell radish
#

what what?

shadow sigil
#

that doesn't answer my question and i have little clue what "completed responses" means

shell radish
#

do you know what a response to an interaction is?

shadow sigil
#

maybe?
and i was able to send a follow up that is also ephemeral

shadow sigil
#

what is View.to_components?

errant trout
errant trout
errant trout
#

(or rather, View is Pycord's way of making components easier to manage)

shadow sigil
#

is there a simple way to change the color of all the buttons when one of them is clicked?

errant trout
#

loop through view.children

#

then just interaction.edit with the updated view

shadow sigil
#

alright, thanks

tidal vessel
#

Can anyone help me with this problem?
I try to access the message containing the View and the message contains a single embed but it returns NoneType
Am I doing something wrong? Or should I access the embed another way?

Error:

Hora: 2024-08-08 20:49:34,416
Nivel: ERROR
Archivo: base_events.py
Función: default_exception_handler
Mensaje: Task exception was never retrieved
future: <Task finished name='discord-ui-view-timeout-30dc27a2a71415285a6923a7b5607e89' coro=<BotonesConfirmar.on_timeout() done, defined at C:\Users\Usuario\desktop\Bot de discord\Pruebas\components\juegos\botones_confirmar.py:46> exception=AttributeError("'NoneType' object has no attribute 'embeds'")> 
Traceback (most recent call last):
  File "C:\Users\Usuario\desktop\Bot de discord\Pruebas\components\juegos\botones_confirmar.py", line 51, in on_timeout
    self.embed = self.message.embeds[0]
                 ^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 
'embeds'
`
little cobalt
#

self.message can be None

tidal vessel
little cobalt
#

you should check for it if its None or not

tidal vessel
lapis dock
#

Can you show the line where you originally send the embed/view?

#

Message should not be None if you are sending the message at the same time as the view

tidal vessel
lapis dock
#

Strange. I guess you can pass the emved to the view as a backup

tidal vessel
lapis dock
#

Im not sure why self.message is returning None. I thought it was that you were sending it as a separate message but that is not the case. It is late for me but I can look at it tomorrow morning to see if there is a better solution.

#

As a parameter in the class?
yes

tidal vessel
shadow sigil
#

is there a way to check if a response has already been sent

errant trout
#

response.is_done()

#

(Pls read the docs)

shadow sigil
#

i get read the docs but i already checked like 3 different places where i would have expected to find something and didn't

river oriole
#

Is there a way to have options only for a prefix command and not for the slash variant when using bridgecommands?

fresh sierra
#

The purpose of bridge is to make both thing

#

But you can still handle than in the command itself

#

With if ctx.is_app :

river oriole
#

Yeah but that expects the Options then. My goal is to have a prefix command like

!tags add name content

and as slashcommand just /tags add

#

The SlashCommand should open a Modal which handles the input

sage tendon
#

yea that's not possible unless you separate the command into prefix and slash

river oriole
#

I see. Is there a way to add Commands to the BridgeGroup?

Like

@bridge.bridge_group(guild_only=True)
async def tags(self, ctx: bridge.BridgeContext):
    pass
@commands.slash_command()
async def slash_add(self, ctx: discord.ApplicationContext):
    pass
@commands.command()
async def prefix_add(self, ctx: commands.Context):
    pass
add = bridge.BridgeCommand(
    name="add",
    description="Adds a tag",
    slash_variant=slash_add,
    ext_variant=prefix_add,
)
tags.subcommands.append(add)
river oriole
#

Yeah but that adds it as BridgeCommand. I want to map it by myself. So that I can have one version with options and the other without

errant trout
#

just

#

don't use bridge then

river oriole
#

Well i want to have multiple subcommands in the group

#

Like

  • Tags delete
  • Tags list
    And only 2 subcommands should be different
errant trout
#

bridge is mainly just a wrapper for command compatibility across prefix and slash, if you're trying to customize each variant it isn't really designed for it

river oriole
#

Fair tho

errant trout
#

so it might be a little cumbersome, but for anything more complex you're better off not using it

shut fox
#

how to ping role with bot?

little cobalt
#

.rtfm discord.Role.mention

sly karmaBOT
stoic patio
#

what in the world is this

#

that error is raised when i call bot.run()

sage tendon
#

which pycord version are you on

lofty parcel
#

I swear this man gets the weirdest errors

sage tendon
#

fr

#

never seen that before

echo wraith
#

Can you please try two different bots? I wanna make something sure

stoic patio
sage tendon
#

what did you change since it last worked

stoic patio
#

idr

#

i think it was adding memory profiling for all my event handlers

#

i removed those

stoic patio
edgy nest
#

partial message should accept partial messageable

stoic patio
#

i see

edgy nest
#

if you wouldn't mind opening an issue for that

#

so someone can fix it

#

or fix it yourself and make a PR :3

stoic patio
#

lol idk how to fix it 😭

shadow sigil
#

when using defer on a slash command, is the followup message forced to either be ephemeral or not based on what the defer is

shadow sigil
#

tragic

lofty parcel