#Basic Pycord Help

1 messages · Page 26 of 1

frail ocean
#

so how do i change status

sage tendon
#

discord.Bot(...status=discord.Status.dnd, activity=discord.Activity(...))

frail ocean
#

Nope doesnt go in dnd

torpid cosmos
#

show what you have now

tranquil thicket
#

Okay partially there... how can I do autocomplete for a slash command?

frail ocean
#

Nowww

tranquil thicket
#

@target.autocomplete("team") async def target_team_autocompletion(interaction: discord.Interaction, current: str) -> typing.List[app_commands.Choice[str]]: data = [] for choice in TEAM_NAMES: if current.lower() in choice.lower(): data.append(commands.Choice(name=choice, value=choice)) return data

sage tendon
#

make a function that takes a single argument as its input, and returns a list of strings
then pass its name via the autocomple parameter WITHOUT ()

torpid cosmos
#

that link will show you how to use autocomplete

sage tendon
#

also, since i see "choices" there

#

dont use autocorrect if theres a set amount of valid choices

#

if you need that, use the choices= parameter

frail ocean
#

Found a bug

torpid cosmos
#

just because you can't figure it out doesn't mean its a bug

#

that being said

#

it also very well could be

#

what you got

sage tendon
#

lol

frail ocean
torpid cosmos
#

yeah thats almost definitely not a bug

#

show us your code

frail ocean
#

.

torpid cosmos
#

that's what you have right now? exactly?

frail ocean
#

yes

torpid cosmos
#

try turning off your code, waiting until your bot goes online, then running it again

#

@frail ocean is there any other code in your program that manages status? If not, can you send us the context or surrounding code of where it changes?

frail ocean
#

Des

frail ocean
#

There is no other code. In on ready is this line

errant trout
#

this is wrong, status is separate from activity

frail ocean
errant trout
#

(that being said, i can't get custom status working; i'm debugging it now, but you can alternatively use discord.Game or similar)

errant trout
frail ocean
errant trout
#

you should be able to, but im not sure if "custom" status is working at the moment

#

(it may also be that bots can't set that type)

frail ocean
#
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.custom, state=":poop: ") status=discord.Status.do_not_disturb)```
errant trout
#

you're missing a comma but yeah

frail ocean
#

Like that

frail ocean
sage tendon
frail ocean
sage tendon
#

i told you how to do it, i sent you a line of code

errant trout
#

well doing it in Bot is only for startup, change_presence is still its own thing

sage tendon
#

yea but same syntax

errant trout
#

oh wait

errant trout
frail ocean
oblique sable
#
async for chunk in response:
  text += chunk.text
  if edited:
    await ctx.edit(content=text)
  else:
    await ctx.respond(text)
  edited = True

or you can use a conditional expression

async for chunk in response:
  text += chunk.text
  await (ctx.edit(content=text) if edited else ctx.respond(text))
  edited = True
frail ocean
#

Other question:
How can I get if a server has premium from a bot

#

Buyed like upgraded

sage tendon
#

"premium"?

#

do you mean boosts

errant trout
#

they mean bot subscriptions

errant trout
lofty parcel
#

I also answered that question.

errant trout
#

Bruh

tranquil thicket
#

Has anyone seen this?

shell radish
tranquil thicket
#

This only happens when i deployed it to a new bot, Using my test bot token no issues

shell radish
#

weird

errant trout
#

ah

#

indeed it's a 2.5 bug from an edge case

tranquil thicket
#

lovely

errant trout
tranquil thicket
#

so is there a workaround?

shell radish
#

you can probably downgrade to 2.4.1

shell radish
errant trout
#

probably

shell radish
#

nelo, you mentioned something about already forked master. Was that resolved?

errant trout
#

oh right that merged

tranquil thicket
#

just fyi

#

tyank u

shell radish
tranquil thicket
#

mabye a silly question

#

how can i give my bot permissions

errant trout
#

as in?

tranquil thicket
#

They used to appear like a user and I could give it a role

errant trout
#

that's just the bot's role permission

tranquil thicket
#

now they dont appear on the members list

shell radish
#

did you invite with bot scope?

errant trout
#

did you install it as a user bot?

tranquil thicket
#

I dont believe so

tranquil thicket
shell radish
#

how are you inviting the bot?

#

can you send the url you are using?

tranquil thicket
#

A link like this but i cut out some of the client Id for privacy

shell radish
#

well, you can add permissions to that

tranquil thicket
#

did not know that how so

shell radish
#

in the discord dev portal, click on your bot, OAuth2, URL generator.

#

Check bot

#

then check the permissions you want

#

then copy the link

tranquil thicket
#

got it

#

nice ty

livid tulip
#

heyo, in the process of migrating from disnake. Does pycord have a guild-only specific ApplicationContext typehint?

errant trout
#

uhhh there isn't a separate one no

livid tulip
#

Disnake has GuildCommandInteraction which typehints .guild as Guild rather than Guild | None

errant trout
#

hmmm

#

in general this lib has broader typings

livid tulip
errant trout
#

Like all interactions are under the Interaction class

shell radish
#

i mean, you can make your own contexts

errant trout
#

oh true

#

that... kinda exists?

shell radish
#

if you really want

livid tulip
#

i'm afraid to ask, but how good is the typehinting on the overall lib?

rugged lodgeBOT
#

Here's the custom context example.

errant trout
#

internally it's fully typehinted

#

for the user we don't have anything special aside from some method of using Options

livid tulip
#

ic ic

errant trout
#

do they have something user facing like that?

#

i normally just flatten

shell radish
#

¯_(ツ)_/¯

#

i've had someone complain about it

#

don't remember what

errant trout
#

interesting...

livid tulip
errant trout
rugged lodgeBOT
livid tulip
#

tyvm :3

#

how would i localise a scg in a cog using #1220155366743212114 confusedbell i can't exactly type-hint a variable

#

actually scratch that, is there a way to make slash command groups like this instead;

class Cog:
    @slash_command(...)
    async def command(...):
        ...

    @command.sub_command(...)
    async def sub(...):
        ...

    @command.sub_command_group(...)
    async def sub_group(...):
        ...

    @sub_group.sub_command(...)
    async def sub_group_cmd(...):
        ...
shell radish
#

hmm no

livid tulip
#

rather than the whole py class Cog: cmd = SlashCommandGroup(...) @cmd.slash_command(...) async def sub_command(...): ...

livid tulip
livid tulip
shell radish
#

you can probably manually do it

livid tulip
#

wdym

shell radish
#

i had an idea and i realized it doesn't work

livid tulip
#

this migration is causing me physical pain

shell radish
#

you can definitely localize it

rugged lodgeBOT
livid tulip
#

yeah that's currently what i'm trying to avoid using haha

shell radish
#

i don't use localization

livid tulip
#

i sadly have to

shell radish
#

there could very well be a simple solution that i don't know

livid tulip
#

ill keep poking around

errant trout
livid tulip
#

god dammit

errant trout
#

what's your issue with the i18n method?

livid tulip
#

i wanna be able to localise via a json file -- that way i can send off my file to translators and just drop in what they send back

errant trout
#

right, which that does

livid tulip
#

huh

errant trout
#

the library i linked that doruk made

#

it rather explicitly takes json

livid tulip
#

yes, my issue is localising slash command groups

#

which it seem to not be able to do, no?

errant trout
#

it should work fine

#

they're treated the same as commands

#

...i guess it's not as obvious as im thinking, but for example

#

if you have a group /settings, subgroup user and subcommand name all these are valid keys for localization: settings, settings user and settings user name

livid tulip
#

ohh i see

#

thank you :p

errant trout
#

all good

#

(admittedly that is entirely theoretical, but i assume it works because that impl. uses command.qualified_name; if it doesn't work, i could try patch it myself to support groups)

fresh sierra
#

Hello, is there a difference between SlashCommandGroup.create_subgroup and SlashCommandGroup.subgroup ?

frail ocean
#

yes but is there a way to check it on a cmd run

fresh sierra
#

or use this

#

await fetch_entitlements()

warm jay
#
@bot.event
async def on_raw_reaction_add(payload: RawReactionActionEvent):
    if payload.emoji not in emojis:
        return

    if payload.channel_id not in channels:
        return

    SocialCreditTable[payload.user_id] += 5

    emoji = f"<:{payload.emoji.name}:{payload.emoji.id}>" if len(payload.emoji.name) != 1 else payload.emoji.name
    await payload.member.send(f"You reacted with {emoji}, good job! Plus `5` centimeters of social credits")
    print(f"Channel id: {payload.channel_id}, Emoji: {payload.emoji.name}")


@bot.event
async def on_raw_reaction_remove(payload: RawReactionActionEvent):
    if payload.emoji not in emojis:
        return

    if payload.channel_id not in channels:
        return

    SocialCreditTable[payload.user_id] -= 5

    emoji = f"<:{payload.emoji.name}:{payload.emoji.id}>" if len(payload.emoji.name) != 1 else payload.emoji.name
    await bot.get_user(payload.user_id).send(f"You un-reacted {emoji}. Bad job. Removed `5` centimeters of social credit")
    print(f"Channel id: {payload.channel_id}, Emoji: {payload.emoji.name}")

It just stopped working

little cobalt
warm jay
#

I don't know why

little cobalt
#

Did you change any permissions?

warm jay
#

For the bot? no

#

lemme check

#

Found the issue

#

Bot had no role

sage tendon
#

lol

warm jay
#

Someone removed it, idk who

fresh sierra
#

is this possible to create a custom check asynchrony’s ?

#

@commands.command()
@customcheck
async def

frail ocean
sage tendon
#

took me about 2 seconds on the docs

#

no need to ping people when you can find all the info in the docs

onyx sentinel
#

guys, how do i generate timestamp codes with the bot

#

i want it to generate codes from the moment i run the command

fresh sierra
#

hello, is there a way to use a coroutine in the command_prefix ?

async def get_custom_prefix(bot: discord.Client, message: discord.Message):
  pass
bot = commands.Bot(command_prefix=asyncio.run(get_custom_prefix()), intents=intents, owner_id=owner_bot)
onyx sentinel
sage tendon
#

Shouldn't this make a /help command automatically?

#

(no, that is not my name in there)

sage tendon
fresh sierra
sage tendon
#

command_prefix='!'
done

fresh sierra
#

That not What I asked ;​​​ )​

sage tendon
#

Yea, but its also not what I asked you

fresh sierra
#

Its for custom prefix so

sage tendon
#

why do you need to run a function to get the prefix

#

then you cant do that like that

#

its the bot's global prefix

fresh sierra
#

I know

sage tendon
#

you need to handle custom prefixes per-server differently

fresh sierra
#

No but like

#

I know What im doing dw

sage tendon
#

i doubt that, to be honest

#

if you explain what you want to do i can help better

fresh sierra
#

Because u dont know how it works ;​​​ )​

sage tendon
#

no help without info :)

#

doesnt work like that

fresh sierra
#

Yes it works…

fresh sierra
sage tendon
#

there is no reason to do that, again

#

just put the prefix there

fresh sierra
#

are u stupid ?

#

i explain you

#

that i need custom prefiux

#

and since i just swtich to an async database

sage tendon
fresh sierra
#

i need this fonction to be async too

sage tendon
#

again, you do not need to put a function there
I know you want custom prefixes per-server

This is not how you can do that, at all

#

but since you just insult me, i think you can also fix that yourself

fresh sierra
#

because you just didnt read

#

and say no it does not work like that

#

when it work like that

#

you can use command_prefix to define per guild prefix, i used that for month and it has always work

sage tendon
#

if you say so

#

it doesnt make any sense

fresh sierra
#

but im sorry for the your stupid

#

it was maybe too munch

sage tendon
#

you need to handle guild-specific prefixes within your on_message

sage tendon
#

if you want help, dont be a dick

little cobalt
fresh sierra
#

my question is how can i use an async function here

sage tendon
#

you do not use a function there because for nothing, ever, do you need to do that

#

i know you love your way, but that is not how its done

fresh sierra
#

so a custom prefix is nothing ?

sage tendon
#

that prefix field is meant for the global default prefix of your bot
It should just be a string

fresh sierra
#

and why ?

#

tell me why it's a bad thing to handle the custom prefix like that

sage tendon
#

yea, no, good luck doing it on your own

fresh sierra
#

ok

#

on my own (just without u)

#

first u didnt answer about what i ask and u just say it doesnt work when it work and say custom prefix is useless when its not so i think that not a big deal

sage tendon
#

i said thats not how you handle it. stop twisting my words.

fresh sierra
#

that like 10 times worst than my function

#

so anways

vapid carbon
#

hi how can i send an ephemeral response

sage tendon
little cobalt
vapid carbon
#

is doing ctx.response("", ephemeral=True) enough?

sage tendon
#

yes

fresh sierra
#

hello, is there a way to use a coroutine in the command_prefix ?
i was using a def fonction but since i switch to an async library, i now need to use a async def.
I was thinking about something like that :

async def get_custom_prefix(bot: discord.Client, message: discord.Message):
  pass
bot = commands.Bot(command_prefix=asyncio.run(get_custom_prefix()), intents=intents, owner_id=owner_bot)

i was before using this

def get_custom_prefix(bot: discord.Client, message: discord.Message):
    pass
bot = commands.Bot(command_prefix=get_custom_prefix, intents=intents, owner_id=owner_bot)
vapid carbon
sage tendon
#

show your code

vapid carbon
#

it is a slash command interaction, does that change anything?

sage tendon
#

it has to be

little cobalt
vapid carbon
#
if is_plan_generated:
        embed = await generate_war_plan_embed(embed=discord.Embed(), plan=plan_response)

        await ctx.respond('', embed=embed)
    else:
        await ctx.respond(f"Please add {', '.join(plan_response)} to the sheet", ephemeral=True)```
#

this is from withing the slash command function

sage tendon
#

well, show the result in the chat

vapid carbon
#

i only want it to be ephemeral in the else part

sage tendon
vapid carbon
sage tendon
#

yes

vapid carbon
#

this is from my testing server

sage tendon
#

restart your bot :>

vapid carbon
#

it should have the dismiss thing right?

vapid carbon
#

;-;

sage tendon
#

well, your code is right

#

so i assume you are somehow still running the old code

vapid carbon
#

await ctx.defer()
    is_plan_generated, plan_response = await war_plan()

    if is_plan_generated:
        embed = await generate_war_plan_embed(embed=discord.Embed(), plan=plan_response)

        await ctx.respond('', embed=embed)
    else:
        await ctx.respond(f"Please add {', '.join(plan_response)} to the sheet", ephemeral=True)```
#

here is two more lines before

#

i am also using defer, does that change anything?

sage tendon
#

yea

#

i think you can make the defer ephemeral too

#

and it has to be for any response to be ephemeral

vapid carbon
#

like await ctx.defer(ephemeral=True)?

sage tendon
#

yes

little cobalt
#

you have to ephermeral the defer if you send a message with it

sage tendon
#

also lil questio nof my own since i read this, how does "invisible" differ from the normal defer? doesnt it always say "x is thinking"?

vapid carbon
#

okay, so if i ephemeral the defer, will it still be a normal message when the if is true? i just want it to be ephemeral in the else part

sage tendon
#

try it and see

#

should work tho

vapid carbon
#

okay

sage tendon
#

ah, might not actually

vapid carbon
#

oop

#

what if i explicitly pass ephemeral=False in the if

sage tendon
#

try it and see but i dont think it can override that

vapid carbon
#

rip

sage tendon
#

yea actually it makes sense that the defer dictates the state

#

you can work around this though
you can save the defer as a variable, and then respond to that with an ephemeral reply

vapid carbon
#

okay do you see any way out of this? the part that is generating the plan just takes a while

sage tendon
#

first thing i'd try rn

vapid carbon
sage tendon
sage tendon
vapid carbon
#

okay and how do we respond to that?

sage tendon
#

just like you'd respond normally

#

defer_obj.respond

errant trout
vapid carbon
#

alright let me try that i really apprecite your help

#

okay it says defer object has no respond attribute

sage tendon
#

dam

#

hm..

vapid carbon
#

i just need it to be emphemeral if the plan isnt generated

little cobalt
vapid carbon
#

else has to be public

vapid carbon
#

because it seems like ctx.defer is returning None

sage tendon
#

i mean ideally you'd find some logic that runs checks on whatever inputs the user gives so you can defer 2 ways, once ephemeral and once without

#

thatd be my second idea lol

vapid carbon
#

actually the slash command is without any inputs

#

on the backed the bot checks if any entries are missing from the google sheet, and if they are i need it to softly tell the moderator whats missing

sage tendon
#

ah

vapid carbon
#

else the plan can be posted for everyone to see

sage tendon
#

my third (and a lil clunky) idea would be to respond immediately with a custom waiting text, and then if it didnt work, you reply to that ephemerally then delete the initial waiting message, and if it did work, you just edit that mesage

vapid carbon
#

ah

#

yeah that makes sense

sage tendon
#

How long even is the non-deferable response time

vapid carbon
#

not sure ;-;

sage tendon
#

hits me often too tho
needing to call APIs or smth that take 5s or so so i always need to defer, and it does take away flexibility

#

id love if defer literally just extended the timeout and didnt generate a message in chat like it does

vapid carbon
#

yeah this is connecting to two diff apis and then doing a fair bit of sorting and all to create the plan

#

@sage tendon is it possible to change the ephemerality after the initial ctx.defer() is invoked?

frail ocean
#
    proc = self._process
AttributeError: 'FFmpegPCMAudio' object has no attribute '_process'```
How can i fix this
frail ocean
little cobalt
frail ocean
#

Send me pls

little cobalt
#

or what is the other module?

frail ocean
#

PyNaCl?

#

discord.errors.ClientException: ffmpeg was not found.

#

But i installed it

sage tendon
#

meme

frail ocean
#

?

#

Got it

little cobalt
#

What was it?

#

@frail ocean

frail ocean
#

Restarting the program xD

frail ocean
#

After set the variable

#

@little cobalt

frail ocean
#

What does that mean

User
    raise ApplicationCommandInvokeError(exc) from exc

discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: OpusNotLoaded: ```
red mist
#

well it seems like Opus ain't loaded

#

As it's a discussion related to this issue

frail ocean
#

Bruh

fresh sierra
#

is there a way to access to all guild of a shard ?

#

like self.bot.guilds_shard

frail ocean
fresh sierra
#

because i didnt find anything on the doc

frail ocean
#

As example

fresh sierra
#

like i have a loop with a for guild in guilds, and since i dont want it to be done 10times for each guild, i need it to be done only in the guilds shard

warm jay
#
@bot.event
async def on_raw_reaction_add(payload: RawReactionActionEvent):
    print("Detected Add")
    if payload.emoji not in emojis:
        return

    if payload.channel_id not in channels:
        return

    SocialCreditTable[payload.user_id] += 5

    emoji = f"<:{payload.emoji.name}:{payload.emoji.id}>" if len(payload.emoji.name) != 1 else payload.emoji.name
    await payload.member.send(f"You reacted with {emoji}, good job! Plus `5` centimeters of social credits")
    print(f"Channel id: {payload.channel_id}, Emoji: {payload.emoji.name}")

The bot has correct permissions, the reacting still is not getting called

fresh sierra
warm jay
#

The bot literally has admin

fresh sierra
fresh sierra
warm jay
#

Lemme see

fresh sierra
warm jay
# fresh sierra So ?

The top is before. After reacting, I ran the command again, and it's not getting called. (The other person that works on the bot sees the console)

#

Okay, so

fresh sierra
#

u lost me to be honest

lofty parcel
#

Most likely the interaction timed out and the error handler couldn't send a message

#

Raise the error instead of trying to send a message with it

warm jay
#

Alright

#

I can do that

warm jay
lofty parcel
#

Yes but it is erroring before that

#

Completely remove the ctx.respond for now

warm jay
#

Alright

#

Did that. Letting it update.

lofty parcel
# warm jay

That means your slash command is taking more than 3 seconds to respond

warm jay
#

The on_raw_reaction_add and on_raw_reaction_remove

lofty parcel
#

yet that's not what's wrong

#

A slash command they're using to send it (I assume) is taking more than 3 seconds

warm jay
#

Huh

lofty parcel
#

Or button or any interaction...

warm jay
#

Slash commands

#

I have one command that has buttons

#

But that command was not ran

#

All other commands are responding in time

lofty parcel
#

You'll have to find it

#

About your event, do you have intents? I think you need intents for reactions

warm jay
#

what intents do I need

lofty parcel
warm jay
#

Just added intents = discord.Intents.default()

lofty parcel
#

that should be enough I think

warm jay
#

Would it be

intents = discord.Intents.default()
bot = discord.Bot(intents=discord.Intents.all())

or

intents = discord.Intents.default()
bot = discord.Bot(intents=intents)
warm jay
warm jay
#

alrighty

#

trying that now

#

It worked once...

#

So now i have bot = discord.Bot(intents=discord.Intents.default()).
The bot noticed me react once, and that was it??

#

No errors

#

whyyyyyyyyyyyyyyyyyyyyyy

little cobalt
warm jay
sage tendon
red mist
sage tendon
#

yes

onyx sentinel
#

guys pls help me: i want to log in a discord channel when the bot starts and when it stops, i already did the part where it logs when the bot is online using on_ready and now i need the other part, here is my code for now:

async def on_ready(self):
        await bot.change_presence(status=discord.Status.dnd, activity=discord.Game(name=f"Pycord 2.5"))
        print(f"Logged in as {self.user} (ID: {self.user.id})")
        print("------")

        try:
            global lastMessageId
            timestamp = datetime.datetime.now().timestamp()
            canal = bot.get_channel(1220424323400208524)
            lat = round(bot.latency * 1000)
            embed = discord.Embed(title="Bot online!", description=f"Started: <t:{int(timestamp)}:R>", color=discord.Color.green())

            if lat <= 50:
                button = Button(label=f"{lat} ms", emoji=":goodping:",style=discord.ButtonStyle.grey, disabled=True)        

            elif lat <= 200:
                button = Button(label=f"{lat} ms", emoji=":midping:",style=discord.ButtonStyle.grey, disabled=True)

            elif lat > 200:
                button = Button(label=f"{lat} ms", emoji=":badping:",style=discord.ButtonStyle.grey, disabled=True)


            view = View(timeout=None)
            view.add_item(button)     
            
            message = await canal.send(embed=embed, view=view)

            lastMessageId = message.id

        except discord.NotFound:
            print("Uptime channel not found")
red mist
#

.rtfm task

onyx sentinel
#

witch one should i use?

errant trout
fresh sierra
#

Hello, since im using an async database with my bot in python, i have a lot of those error :

ERROR:asyncio:Task was destroyed but it is pending!
task: <Task pending name='pycord: on_message' coro=<Client._run_event() done, defined at /home/container/.local/lib/python3.11/site-packages/discord/client.py:392> wait_for=<Future pending cb=[Task.task_wakeup()]>>
#

does someone has an idea about what should i look for ?

deft kestrel
#

any examples of this form?

sage tendon
#

that's called a modal

frail ocean
#

Can someone tell me why Music bots in py are so buggy? I kick him out of the voice and then when you make a query whether player is playing.
Player is still playing

sage tendon
#

ask the devs of those bots?

#

what does that have to do with pycord at all

frail ocean
sage tendon
#

if you mean your own bot, yes

frail ocean
sage tendon
#

vc disconnect ig

frail ocean
sage tendon
#

shrug find out

frail ocean
#

😳

north rapids
errant trout
errant trout
#

well not discord but the big ones got c&d'd by yt and other platforms ages ago

#

that aside, in general the regular maintainers don't do much with voice

frail ocean
errant trout
#

anyone more interested in those systems is free to contribute to the relevant libraries themselves

sage tendon
#

fabio its not so hard from the context you gave

#

if vc disconnect event, stop the player associated with that channel

lofty parcel
#

watch him ask for an example

little cobalt
#

Is someone creating a help thread and deleting it again?

#

I saw 6 times a new one and it was gone

lapis dock
#

I just closed a bunch, discord might have been glitching

frail ocean
grizzled loom
#

All yours

frail ocean
#

xDDD HAhaa

bronze mist
#

How do I add a description for the argument?

#
@bot.slash_command(name="choose")
async def choose(ctx:discord.ApplicationContext, *, choices:str):
    """The bot chooses an item from a comma separated list."""
    ...

this is what I have right now

frail ocean
bronze mist
#

ohh, it's a discord.Option class

#

thanks!

frail ocean
#

Np 😄

#

And in the command u can check that:

if choices == "choice1":
  await ctx.respond("Lala")
#

@bronze mist

little cobalt
bronze mist
little cobalt
#

you dont need the * at the slash commands

bronze mist
#

yup, i just did from discord import option

sage tendon
#

also little tip you don't need the name argument in the slash command decorator

#

it automatically takes the function name

frail ocean
little cobalt
deft kestrel
#

i prefere match

#

its faster

#

i dont know how,

sage tendon
#

thats just a wrong statement

shell radish
sage tendon
#

exactly why its wrong

stray pasture
#

It is possible to do a add_role or remove_role to a member and get the received response form discord?

errant trout
#

Or do you mean you want the raw response...?

stray pasture
#

With the rate limit information

errant trout
#

Hmm we generally don't keep it

#

Rate limits are automatically handled so you generally don't need to worry about them

#

If you really want you could probably edit role.py to keep the raw response data

#

But rate limit info would be in the headers which further complicates things

stray pasture
errant trout
#

Probably

#

Is there a specific reason you need it?

stray pasture
# errant trout Is there a specific reason you need it?

yes ! I currently have recurrent timed role in my bot. With these you can add/remove a role for all members of your server each x time interval(minimum 1 minutes). I just realized that could be problematic for big servers or if some server have a lot of these timed role at the same time.

To solve the issue, I want to implement a system where I do 1 request per server (and skip the guild that are currently rate limited for that route). I am only interested for the member.add_roles and member.remove_roles for that processing. Not all request

exemple: I have guild A, B, C
I process A, B(skip B because rate limited), C, A,B ...

errant trout
#

Oh dear

stray pasture
#

yeah ahaha 😄

errant trout
#

Hmmm

#

Do you expect this to be used in large/many servers?

stray pasture
#

yes it is already in 2600 servers

errant trout
#

Hmmmmmmmmmm

#

The thing is, role ratelimits are pretty short

#

Like, a couple seconds

#

In practice it's something like 5/5sec? But like all ratelimits are per-route and dynamic, then the client has auto retry so you don't notice anything apart from the short delay and info log

#

But then the issue comes with this being used at scale, there's a chance the higher level ratelimits are enforced or the bot gets temp banned

stray pasture
#

yeah per route and per top level parameters. So in my case the add/remove roles from member have different rate limit for each guild

stray pasture
errant trout
#

Well, in this lib it won't let you go over the limit anyway

#

But if you push them too much (e.g. hitting the hardcap limit) then it's possible there's some automatic pushback against your bot

#

Again, this is very hard, but not unheard of (and something like editing the roles of every member every minute might attract attention in itself)

stray pasture
#

Then if that case, I could stop before hitting that hardcap limit no ? in the response discord tell you how manym ore you can to with the time

stray pasture
#

of the interval

#

now it is 1 minutes, but will probably put something like 1 hour at least

errant trout
#

If it's one hour you shouldn't have to worry at all

#

Maybe have some queue system that spaces out every X edits for larger servers

stray pasture
#

Do you think it is a good idea to process 1 event per Guild in alternance ? To make it more fair if one Guild take like all the rate limit at a certain time

errant trout
#

Well the thing is you can do multiple guilds at the same time

#

As they have their own ratelimits

#

But bear in mind the global ratelimit is 50 reqs per second so you don't wanna do too many

stray pasture
#

I see, I could put them in some queue and process them at like 40 req per second (just to be safe with other events of the bot)!

#

so it does not the limit to often

errant trout
#

also bear in mind that, at a minimum, the amount of seconds it will take to complete is equal to the amount of members

stray pasture
#

yeah I know ! it cannot run very fast, but as long as it ocmplete it should be fine 😄

errant trout
#

Well, for example

#

3600 members and 1 hour interval would be rather disasterous

#

Hm lemme just test first

stray pasture
#

I see ! I can maybe put the minimum interval based on the Guild size 😄

errant trout
#

Ok yeah, small test on 34 members took 32 seconds

#

So you really gotta consider how this scales

stray pasture
#

this is not the main feature of the bot, so maybe I can say that it might take some time and they got to deal with it 😄

errant trout
#

Fair enough

#

If you do wanna do a dynamic minimum interval, id recommend 2*membercount

stray pasture
#

Thank you for your help !

errant trout
#

All good

mellow spire
#

if i create and send a button then how long the button should work?
because I saw in the ticket tool bot when I use a command where the user can press the delete button then that button will work for a long like
bot send the button then if the user presses it after a week it works

mellow spire
#

and hours

shell radish
#

i don’t know what libraries other bots use so I don’t know for sure

#

in pycord, you use persistent views

mellow spire
#

js and py

mellow spire
shell radish
mellow spire
#

ok

shell radish
#

there are like a total of like 10+ different js and python discord libraries

mellow spire
#

Oh

grizzled loom
grizzled loom
#

show me what you're using to send it and i'll help looking. only did this with paginator buttons myself

#

is this what you were looking for?

round girder
#

ive been getting many many (10+ in the last 24h) random bot shutdowns due to the connection being severed from my bot on discord's end. i haven't heard of anything breaking API stuff from here or discord, so was curious if anyone knew what was up? last time i updated that bot was about 2 months ago.. been smooth sailing since up until yesterday

little cobalt
lapis dock
#

could you send the exact error message

little cobalt
#

also that ^

round girder
round girder
# lapis dock could you send the exact error message

have to keep clearing output just to restart all the systems and the bot itself. im mostly getting WinError 10054 but also have gotten others similar. for example "cannot write to a closing transport". none of the files in either traceback lead to files written by me. they originate within pycord files, then to aiohttp/requests

lapis dock
#

I have not seen that before. If it happens again please send the full error here but that might just be a discord issue

#

then to aiohttp/requests
you probably should not be using requests in your bot. (aiohttp is fine)

round girder
#

funny how it just happened again

#

incoming AIO error

round girder
# lapis dock could you send the exact error message
future: <Task finished name='Task-275' coro=<ConnectionState._delay_ready() done, defined at C:\...\Python\Python311\Lib\site-packages\discord\state.py:567> exception=ConnectionResetError('Cannot write to closing transport')>
Traceback (most recent call last):
  File "C:\...\Python\Python311\Lib\site-packages\discord\state.py", line 581, in _delay_ready
    future = await self.chunk_guild(guild, wait=False)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\...\Python\Python311\Lib\site-packages\discord\state.py", line 1259, in chunk_guild
    await self.chunker(guild.id, nonce=request.nonce)
  File "C:\...\Python311\Lib\site-packages\discord\state.py", line 523, in chunker
    await ws.request_chunks(
  File "C:\...\Python\Python311\Lib\site-packages\discord\gateway.py", line 701, in request_chunks
    await self.send_as_json(payload)
  File "C:\...\Python\Python311\Lib\site-packages\discord\gateway.py", line 646, in send_as_json
    await self.send(utils._to_json(data))
  File "C:\...\Python\Python311\Lib\site-packages\discord\gateway.py", line 642, in send
    await self.socket.send_str(data)
  File "C:\...\Python\Python311\Lib\site-packages\aiohttp\client_ws.py", line 153, in send_str
    await self._writer.send(data, binary=False, compress=compress)
  File "C:\...\Python\Python311\Lib\site-packages\aiohttp\http_websocket.py", line 690, in send
    await self._send_frame(message, WSMsgType.TEXT, compress)
  File "C:\...\Python\Python311\Lib\site-packages\aiohttp\http_websocket.py", line 646, in _send_frame
    self._write(header + mask + message)
  File "C:\...\Python\Python311\Lib\site-packages\aiohttp\http_websocket.py", line 663, in _write
    raise ConnectionResetError("Cannot write to closing transport")
ConnectionResetError: Cannot write to closing transport```
#

im pretty sure that the connection is being closed by discord. it might sometimes cause the winerr, and sometimes cause this

#

im going to upgrade to 2.5 and restart again to check if fixed

lapis dock
#

I was looking through the pas t instances of this and the only somewhat solution I wound was that your internet is not good. I dont think this is something that is controllable.

#

You could run a ping command and see if you are geting higher than nromal numbers

round girder
#

after upgrading i ran into some problems and now my cog loader is not recognizing imports

#

ModuleNotFoundError: No module named 'typing_extensions'

#

typing_extentions is built in so im confused whats going on here

little cobalt
#

Can you show the pip list pls

sage tendon
#

(run pip list in a cmd prompt)

sage tendon
#

well, what was it

sage tendon
#

going 2.4>2.5 should not break anything lol

round girder
sage tendon
#

what?

round girder
#

trying to replace options with typing_extention.Annotations as i saw that looked like a fix in the update note

sage tendon
#

still, not related to upgrading from 2.4 to 2.5
It's a minor update aka it shouldn't (and didn't) include breaking changes

sage tendon
#

just use the @option decorator, my personal suggestion

#

cleanest and easiest

round girder
sage tendon
#

i mean, i had the same setup as you

#

nothing changed

#

what is even the exact error or whatever you get

round girder
#

discord.errors.ExtensionFailed: Extension 'cb_command_edit_raw' raised an error: TypeError: Invalid class <class 'discord.ext.commands.context.Context'> used as an input type for an Option

sage tendon
#

yea i mean you got something messed up in your code lol

#

its trying to read the context as the input type

#

what could've happened is that a fix fixed unintended behaviour which you used lol

#

show your code for your options

round girder
#
@commands.slash_command(guild_ids = DEVELOPER_SERVERS, name = _edit_raw.name, description = _edit_raw.description)
@cooldown(1, _edit_raw.cooldown, BucketType.user)
async def edit_raw(self, ctx : commands.Context,
      key : discord.Option(str, "Data Key", name = "data", choices = ["yellow","banned", "blue","currentrank","ranklevel","highrank", "skins"], required = True),
      data_ : discord.Option(str, "Data Entry", required = True),
      user : discord.Option(discord.User, "User To Edit", required = False)
):
#

i used the docs to make this header

sage tendon
#

and if you wanna typehint options, just use the @option decorator
Then you can just typehint the option as the type it is in the actual function header

little cobalt
#

why do you have commands.Context at a slash command?

sage tendon
#

oh, yea
has to be discord.ApplicationContext

round girder
#

thats weird, youre right

#

2 commands had it

#

weird that it functioned with commands.Context for v2.4

#

now it at least starts

sage tendon
#

well, as i said, was probably unintended behaviour that was fixed with 2.5

#

:3

round girder
round girder
sage tendon
#

example

round girder
# sage tendon example

thanks lol, i have like ~75 commands and most use my style, but that looks so clean like you mentioned. unfortunately, im having issues with my prod bot, but ill fix options for the next update. i appreciate your feedback

sage tendon
round girder
#

bot just fell offline, no console output

#

i have logging mode on and nothing was printed from pycord nor my logs

#

on_ready had/has not been called

round girder
#

what line do you mean?

sage tendon
#

oh it's during startup?

round girder
little cobalt
#

keep in mind, if you restart your bot with 75 slash commands that you get a ratelimit really fast and your commands are not gonna show up

sage tendon
round girder
round girder
little cobalt
sage tendon
#

like I have 40 commands or something and sometimes my test bot restarts like 10 times a minute and nothing changes

#

so I am highly sure unchanged commands don't count

little cobalt
#

Limit is 200 command every day

sage tendon
#

you have to sync them yes, but not register new ones

#

yea, register.

#

40 times the same command with no option changes is still the same command

round girder
#

just got the error again (cannot write to closing transport) and the bot is now up and running seemingly fine

sage tendon
#

but if you change an option its a different command and needs to be registered

sage tendon
round girder
#

i would agree this is potentially a wifi/internet connection, however my bot is hosted on my webserver in AWS, so unless theres a big problem with internet down there, its not that

sage tendon
#

but don't you get the error on your pc (too)?

round girder
round girder
little cobalt
errant trout
#

taking a jab

round girder
errant trout
#

isee

#

in any case never typehint ctx/context args

#

how many guilds is the bot in?

round girder
#

i fixed it, i had used commands.Context instead of discord.ApplicationContext

round girder
round girder
errant trout
#

...seeing that your error is in chunk_guild, that's the relevant question

round girder
#

around 2.1k - 2.5k, honestly i dont keep up with it as i never expected it to be so popular

#

i have no shards though if thats what youre asking

#

"im not sharded" if thats the proper way to say it

errant trout
#

You don't use autoshardedbot?

round girder
#

no, wha ¯_(ツ)_/¯

errant trout
#

...please do

sage tendon
#

shouldn't you shard at the latest at 2k servers?

errant trout
#

It's forced at 2.5k, you're recommended to start earlier

round girder
#

just got the ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host error

errant trout
#

If you're actually in 2.5k servers then discord is literally rejecting your bot

round girder
#

looks like the next update just got moved up

errant trout
sage tendon
errant trout
#

yeah it's not particularly hard

round girder
#

just curious, if its so simple why isnt it just automatically done to every bot? (from the client side)

errant trout
#

because it's not intended for smaller bots

round girder
#

is there any downsides to using it anyways, other than a larger amount of resources?

errant trout
#

(strictly speaking, every bot is "sharded", just at 1 shard)

#

enabling multiple shards when you don't have many servers supposedly degrades performance, or something, idk there's just no reason to

round girder
#

in the page you sent, it states that discord will contact me when its time, and they havent yet. should I anyways?

errant trout
#

at your server count, definitely

#

(discord contacts you at 150k guilds)

round girder
#

also im really confused about the concept of sharding, i remember reading about it maybe 2 years ago but i still have no idea what it realy does and why its neccesary

round girder
errant trout
#

if you want you can read the full documentation on it here

#

it's basically splitting the bot across several processes, which each recieve their own events

#

many large libs make this easier for the user by handling that under-the-hood and routing everything for you

#

for pycord, you can read about sharding-specific parameters and attributes here

round girder
#

so what im hearing is basically "your bot has so many guilds! this wil make your computer cry because its so hard to process all of that. but now, you can split up the connection so it somehow is.. reads paper less efficient?"

errant trout
#

it's not for your computer, it's for discord

#

when the client is in so many guilds, sending all requests and all events down a single line is inefficient

round girder
#

okay i think i understand now

#

why do they blow it out of proportions by giving it a big scary name and a whole api page.. thats all i needed to know to understand what/why/how

errant trout
#

because that's how documentation works...

round girder
#

thats not what i meant

#

also lets say i had another bot that im migrating to my web server soon, this second bot is coming up on 900 guilds (as of about a month and a half ago). should I shard it yet? i dont know when to shard essentially

errant trout
#

you wouldn't need to, no

sage tendon
#

You can at 1000, you dont have to until 2500

errant trout
#

discord gives such a large window because every bot has different needs

sage tendon
errant trout
#

some bots will start struggling earlier than others, so they'll start sharding at a lower guild count

#

a very lightweight bot could make it to 2500 guilds without issue and then be forced to shard anyway (in theory)

round girder
#

my 900-guild bot had a lot more daily interactions than my 2.2-2.5k one (like 4- 6 times as many), should I shard at 1000?

errant trout
#

i'd say, give it a go and see if there's any significant changes

sage tendon
#

Also dumb question about sharding; does every shard run on its own CPU thread? or how is it realised

round girder
#

would the changes be noticable? (response time)

round girder
#

but im no expert

#

from what ive seen from other systems, if sharding is similar, no

#

but im guessing that would be the way to go eventually

#

(on your end)

sage tendon
#

well i asked nelo :)

round girder
#

damn i see

#

anyways thanks for the help, if the issue persists ill come back again. will shard within a day or so

errant trout
sage tendon
#

i thought asyncio specifically does its stuff on another thread?

#

hm

errant trout
#

asyncio does have some threadsafe functions, but most of it is singlethreaded

#

(hence threading is its own library)

sage tendon
#

ahh

stray pasture
#

Is there a way in pycord to make your shards run in different server ?

sage tendon
#

I would literally just try to run the bot on multiple servers with the same code

#

idk if thats how it works but thats how it should work imo

stray pasture
#

I see I will try ! Thank you

errant trout
#

uhhh in theory, as long as you manually specify the shard_ids

stray pasture
errant trout
#

....congratulations, you discovered the purpose of autoshardedbot

stray pasture
#

I though it only does it for the same machine, not multiple one

errant trout
#

well yeah AutoShardedBot is designed to run in a single process for the user, and it'll determine the recommended shard count from discord and set it

#

if you want something more hacky then just throw shard ids in and hope it works

#

and at higher shard counts, you have to start shards concurrently in order to avoid ratelimits

stray pasture
#

I see thank you !

sage tendon
#

imo autosharded should work across multiple devices

#

prolly harder but doable surely

lapis dock
#

i think Vincent was working on clustering for v3 (but not anymore) which would be the term for "sharding on multiple machines"

edgy nest
#

definitely doable

#

just specify shard_ids & number of shards

#

only thing is cache won't be shared

rare marlin
#
@tasks.loop(minutes=1)
async def check_birthday(self):
     await self._check_birthday()
     print(1)

async def _check_birthday(self):
     now = datetime.datetime.now()
     for guild in self.bot.guilds:
         today_birthdays = await db.get_birthday_date(now.day, now.month)
        
        
         embed = discord.Embed(
             title="🎉 Happy Birthday! 🥳",
             description="Let's celebrate with them:",
             color=discord.Color.gold()
         )
         file_path = os.path.join(os.getcwd(), "img", "birthday.jpeg")
         embed.set_thumbnail(url="attachment://birthday.jpeg")

         birthday_info = ""
         for user_id in today_birthdays:
             member = guild.get_member(user_id)
             if member:
                 birthday_info += f"🎈 {member.mention}\n"
                 next_birthday = datetime.datetime(now.year, now.month, now.day)
                 if next_birthday < now:
                     next_birthday = next_birthday.replace(year=now.year + 1)
                 else:
                     print("Next birthday is today.")
                 days_until_birthday = (next_birthday - now).days
                 birthday_info += f"Next birthday in {days_until_birthday} days\n\n"

                
                 channel_id, role_id = await db.get_birthday_channel(guild.id)
                 birthday_role = discord.utils.get(guild.roles, id=role_id)

                 if birthday_role:
                     await member.add_roles(birthday_role)
                     await asyncio.sleep(86400)
                     await member.remove_roles(birthday_role)
             else:
                 print(f"Member with ID {user_id} not found on server {guild.name}.")

         embed.add_field(name="Birthday Members", value=birthday_info)

        
         channel_id = await db.get_birthday_channel(guild.id)
         channel = guild.get_channel(channel_id)
         if channel:
             await channel.send(embed=embed, file=discord.File(file_path, "birthday.jpeg"))
         else:
             print(f"No channel found on the server {guild.name} for the sender of the birthday message.")``` no embed is sent XD idk why
rare marlin
errant trout
#

did you forget to expand the variables? py channel_id, role_id = await db.get_birthday_channel(guild.id) ... channel_id = await db.get_birthday_channel(guild.id)

rare marlin
#

where?

#

sry ups

errant trout
#

really you should run this once at the top of your guild loop

#

because right now you're running it twice for every member your bot is checking

rare marlin
# errant trout because right now you're running it twice for *every member* your bot is checkin...
class Birthday(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.check_birthday.start()

    @tasks.loop(minutes=1)
    async def check_birthday(self):
        now = datetime.datetime.now()
        for guild in self.bot.guilds:
            today_birthdays = await db.get_birthday_date(now.day, now.month)

            embed = discord.Embed(
                title="🎉 Happy Birthday! 🥳",
                description="Let's celebrate with them:",
                color=discord.Color.gold()
            )
            file_path = os.path.join(os.getcwd(), "img", "birthday.jpeg")
            embed.set_thumbnail(url="attachment://birthday.jpeg")

            birthday_info = ""
            for user_id in today_birthdays:
                member = guild.get_member(user_id)
                if member:
                    birthday_info += f"🎈 {member.mention}\n"
                    next_birthday = datetime.datetime(now.year, now.month, now.day)
                    if next_birthday < now:
                        next_birthday = next_birthday.replace(year=now.year + 1)
                    else:
                        print("Next birthday is today.")
                    days_until_birthday = (next_birthday - now).days
                    birthday_info += f"Next birthday in {days_until_birthday} days\n\n"

                    role_id = await db.get_birthday_channel(guild.id)
                    birthday_role = discord.utils.get(guild.roles, id=role_id)

                    if birthday_role:
                        await member.add_roles(birthday_role)
                        await asyncio.sleep(86400)
                        await member.remove_roles(birthday_role)
                else:
                    print(f"Member with ID {user_id} not found on server {guild.name}.")

            embed.add_field(name="Birthday Members", value=birthday_info)

            channel_id = await db.get_birthday_channel(guild.id)
            channel = guild.get_channel(channel_id)
            if channel:
                print("Sending birthday message to channel:", channel.name)
                await channel.send(embed=embed, file=discord.File(file_path, "birthday.jpeg"))
            else:
                print(f"No channel found on the server {guild.name} for the sender of the birthday message.")
                print("Birthday message not sent due to missing channel.")```
errant trout
#

uh....

#

what does db.get_birthday_channel actually do

#

because you seem to misunderstand your own code

#

does it return a channel id, role id, both in a tuple, something else?

rare marlin
#

You get the role and so on, but the channel is also there but it doesn't send everything in, everything is also in the database!

errant trout
#

right....

#

so at the moment, you're doing this py role_id = await db.get_birthday_channel(guild.id) birthday_role = discord.utils.get(guild.roles, id=role_id) ... channel_id = await db.get_birthday_channel(guild.id) channel = guild.get_channel(channel_id)do you not see a problem here?

rare marlin
#
@tasks.loop(minutes=1)
    async def check_birthday(self):
        now = datetime.datetime.now()
        for guild in self.bot.guilds:
            today_birthdays = await db.get_birthday_date(now.day, now.month)

            channel_id = await db.get_birthday_channel(guild.id)  # Fetching channel ID once per guild

            embed = discord.Embed(
                title="🎉 Happy Birthday! 🥳",
                description="Let's celebrate with them:",
                color=discord.Color.gold()
            )
            file_path = os.path.join(os.getcwd(), "img", "birthday.jpeg")
            embed.set_thumbnail(url="attachment://birthday.jpeg")

            birthday_info = ""
            for user_id in today_birthdays:
                member = guild.get_member(user_id)
                if member:
                    birthday_info += f"🎈 {member.mention}\n"
                    next_birthday = datetime.datetime(now.year, now.month, now.day)
                    if next_birthday < now:
                        next_birthday = next_birthday.replace(year=now.year + 1)
                    else:
                        print("Next birthday is today.")
                    days_until_birthday = (next_birthday - now).days
                    birthday_info += f"Next birthday in {days_until_birthday} days\n\n"

                    channel = guild.get_channel(channel_id)
                    if channel:
                        print("Sending birthday message to channel:", channel.name)  # New print statement
                        await channel.send(embed=embed, file=discord.File(file_path, "birthday.jpeg"))
                    else:
                        print(f"No channel found on the server {guild.name} for the sender of the birthday message.")
                        # Additional print statement after the if-else statement
                        print("Birthday message not sent due to missing channel.")
                else:
                    print(f"Member with ID {user_id} not found on server {guild.name}.")``` her is mein new code
#
No channel found on the server test server for the sender of the birthday message.
Birthday message not sent due to missing channel.
Member with ID None not found on server test server.
Member with ID 0 not found on server test server.
Member with ID 0 not found on server test server.
Member with ID 24 not found on server test server.
Member with ID 3 not found on server test server.```
errant trout
#

(also are those meant to be real users or did you create fake data)

rare marlin
errant trout
# rare marlin yes

ok so 1) convert all IDs to int when you use get_channel, get_member etc.

errant trout
#

because those are obviously not discord user IDs

shell radish
#

pretty sure None is not an ID

errant trout
#

probably some weird data in their db

sage tendon
#

yea i think the whole db function is a mess lol

#

from what i can see

errant trout
#

json superiority frfr

minor crescent
#

how can I create command groups while inside cogs

edgy nest
#

#969574202413838426

minor crescent
#

i thought i could ask here it's just a quick question 😭

edgy nest
#

oh

#

this isnt general

#

mb

minor crescent
#

lmao

edgy nest
minor crescent
#

tanks

river gulch
#

I justed changed a normal reply into a Paginator using paginator.edit(message=msg) where paginator is just a paginator object and msg is a pervious ctx.respond() message
Now my Paginator doesn't respond to any user interactions? What fixes that?

river gulch
#

Unfortunately that would ruin the way the bot looks and I really would like to edit the prior message to become a paginator?
No other options?

errant trout
#

ah wait are you saying you switched to paginator.edit?

#

you can fix it by either setting author_check=False or upgrading to master

river gulch
errant trout
#

author_check is inside Paginator

river gulch
#

alright, thank you, I'll see if it works

errant trout
#

just note that disabling it will mean that any user can use the buttons

river gulch
errant trout
#

fair enough

#

...im not sure if paginator.edit works with ephemerals

#

but if it does then sure go for it

river gulch
errant trout
#

allgood

errant trout
#

@signal trench To get a command by name, you want bot.get_application_command

signal trench
#

okkay thankss

hazy turret
#

Is it possible to add and remove a complete cog while a bot is running?
So that you can expand the bot without having to restart the entire bot?

hazy turret
# little cobalt Yes you can

How can I do it?
When I try it this way, the slash command is still displayed although I get the message that the cog has been unloaded.
And when I try to load it again, I always get an error:

Application command names must be unique

@bot.command(name="unload", hidden=True)
@commands.is_owner()
async def unload(ctx, *, module: str):
    try:
        bot.unload_extension(module)
        await ctx.send(f"`{module}` unloaded.")
    except Exception as e:
        error_msg = traceback.format_exc()
        await ctx.send(f"Error unloading `{module}`: {error_msg}")```
little cobalt
#

I wonder if sync the command is still working x3

hazy turret
#

In Cog with a prefix command it works without problems but with the slash command it causes problems.

I have also tested whether it makes a difference if the slash command is declared globally or only for a guild, but that doesn't make any difference either.

little cobalt
#

Add the command to the sync

hazy turret
little cobalt
#

Get the command from the cog, unload the cog and sync the command

hazy turret
hazy turret
# little cobalt Get the command from the cog, unload the cog and sync the command

I have no success with this either 😄

@bot.command(name="unload", hidden=True)
@commands.is_owner()
async def unload(ctx, module: str, command_name):
    try:
        command = bot.get_command(command_name)
        bot.unload_extension(module)
        await bot.sync_commands(commands=command)
        await ctx.send(f"`{module}` unloaded.")
    except Exception as e:
        error_msg = traceback.format_exc()
        await ctx.send(f"Error unloading `{module}`: {error_msg}")```
little cobalt
#

I can help you later

fresh sierra
#

i might not understand the doc i guess,

xp_group = discord.SlashCommandGroup(name=xp_.name, description=xp_.description, guild_only=True)
    @xp_group.command(name=xp_.setup.name, description=xp_.setup.description)
    @is_owner_or_has_perm("administrator")
    async def setup(self, ctx: discord.ApplicationContext):
#

and i have an Extension 'Slashs.XP.setup sub' raised an error: AttributeError: 'function' object has no attribute 'command'

round girder
fresh sierra
hazy turret
grizzled loom
#

might be worth opening a topic for it, sharing error and code

deft kestrel
#

How to do Error handling for specific checks? I created some checks and I'm aware that it raises CheckFailure when a check fails, but how to respond with a message on a failure of a specific check?

I don't want to do this in the "predicate" code for the check itself because then the response message will also be sent on the Help command (with verify_checks enabled)

sage tendon
#

cant you pass a message to checkfailure?

deft kestrel
#

Not that I know of? Wdym

sage tendon
#

show your code

deft kestrel
#

This is my allowed_in_channel check, it checks in the database whether commands in ctx.channel are allowed

def allowed_in_channel():
    def predicate(ctx):
        if ctx.guild is None:
            return True

        guild_config = GuildConfig(ctx.guild.id)
        command_channel_id = guild_config.command_channel_id

        if command_channel_id:
            return ctx.channel.id == command_channel_id
        else:
            return True

    return commands.check(predicate)
#

Now when this check fails I want to respond with a specific message, but only when this check fails and not others

sage tendon
#

okay first of all why do you have a function in a function lol

deft kestrel
sage tendon
#

and as for your question, I dont really think you can and checks aren't really made for that
Handle it within your command code

fresh sierra
#

With else: raise or ctx.respond

fresh sierra
#

Like this check if its’good channel

deft kestrel
fresh sierra
#

So if he is not in the good Channel, ir will be tell

deft kestrel
#

I just don't want the help command's output to send all responses on CheckFailure. I only want to reply with an error message on the command itself

#

e.g.
!ping -> "You can't do this command in this channel."
!help -> Only show Help response but not that error message

but I do want the Help command to have verify_checks. So the user doesn't see commands he can't use.

sly ember
#

ticket closing button doesnt work, if i restart the bot it works once but on the next ticket i get that error

fresh sierra
#

Just not appear

deft kestrel
#

Alright thanks

errant trout
#

That page includes an example for CheckFailure if you scroll down

deft kestrel
#

But this is on any check failure right? Is there a way to respond differently depending on which specific check failed?

errant trout
#

(Also on that page)

errant trout
sly ember
deft kestrel
#

Ah, subclass of commands.CheckFailure instead of what I've been trying with Exception. I missed that. Thanks!

errant trout
#

Your error is with your own code

sly ember
errant trout
#

Idk man it's your code

sly ember
#

i mean i can try, one sec

errant trout
#

I'm making a guess based on your error

sly ember
errant trout
#

Right... so what arg do you think should be passed

sly ember
#

bot ✅

errant trout
#

Congrats

sly ember
#

🥳

sage tendon
#

oh god, i remember using that color scheme

#

btw, you dont have to typehint an argument you're never gonna use anyway lol

sage tendon
#

and i highly recommend you make a db handler class
because look at how nested your stuff is getting

#

7 deep

steep cliff
#

I’ve you really wanna get fancy, use an ORM like SQLAlchemy

sage tendon
#

also, you don't need an "else" if you return in the initial if clause anyway

sly ember
# errant trout Congrats

iam still getting the same error, after bot restart the button really closes the ticket but then i get the error again

        bot.add_view(ticketsystem.MyView(bot))
        bot.add_view(ticketsystem.MyClass(bot))
errant trout
#

The same error or a new one

sly ember
# errant trout The same error or a new one
Traceback (most recent call last):
  File "C:\Users\lenov\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 414, in _scheduled_task
    await item.callback(interaction)
  File "c:\Users\lenov\Desktop\cogs\cogs\ticketsystem.py", line 307, in callback
    async with self.bot.pool.acquire() as conn:
AttributeError: 'MyClass' object has no attribute 'pool'
errant trout
#

I feel like you're making the exact same mistake

sage tendon
#

please dont call it myview and myclass lol
thats like the least descriptive names possible

errant trout
#

Why not just do interaction.client like above

round girder
round girder
grizzled loom
#

bangs head on the table

#

ofc there is an error from the py-cord module when you get a closing transport message.

Also:
When you look through a clean window you can, most of the times, see the world outside. More news at 10.

There still has to be something causing it and the most common source is how and what you do in your code.

Furthermore, it is totally possible that operations work for a long time and some blocking part in your code doesnt have a harmful effect normally, then when a guild with a butload of members runs the same command, you loop through all of them and do sh -> BAM.

This however can only be seen when looking at your code. so make a topic and provide more information or live with it.

sage tendon
#

also, you are quite literally the only one here with that issue

grizzled loom
#

and the flaw was on my end, not with pycord

#

pycord only provided the error

#

Thanks for the backup though @sage tendon

errant trout
#

look at the first line of your callback

round girder
rugged lodgeBOT
shell radish
#

@lapis dock not cool

lapis dock
#

Sorry, found the answer although this is a lot easier than self.bot._connection._messages XD

#

Question for those who want it: How to access cached messages

shell radish
#

:p

dusty zinc
#

which permissions do i have to give my bot to get rid of this error
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: PermissionError: [WinError 5] Access is denied

shell radish
#

that's your windows, not discord

dusty zinc
#

oh mb

#

so i just have to run as administrator?

shell radish
#

i don't use windows

#

idk

dusty zinc
#

running as administrator should grant it higher permissions

shell radish
#

i suppose that could work

dusty zinc
#

running as administrator does not seem to work

lapis dock
#

I think it is something in your code, can you send the command you are runing

minor crescent
#

is it possible to create an attachment option in a slash command and make it optional? i tried using

attachment = discord.Option(discord.Attachment, description="")

but it's still marked as required

dusty zinc
# lapis dock I think it is something in your code, can you send the command you are runing

this is the code for the command i used when the error occured: ```py
@bot.slash_command(description = "Summons a goose on Villeravn's computer!")
async def goose(ctx):
global goose_count
if goose_count < goose_limit:
goosecmd = subprocess.Popen(['"C:\Users\ville\Documents\programing\python\discord\bots\goosebot\DesktopGoose v0.31\GooseDesktop.exe"'])
goose_count += 1
await ctx.respond(f"Summoned new goose on villeravn's computer, total number {goose_count}")
await asyncio.sleep(90)
subprocess.Popen.kill(goosecmd)
goose_count -= 1
await ctx.respond(f"Goose despawned :slight_frown:, total number {goose_count}")
elif goose_count >= goose_limit:
await ctx.respond(f'Already at max count, total number {goose_count}')

lapis dock
minor crescent
#

normally i just make it = instead of : and it becomes optional

minor crescent
dusty zinc
lapis dock
lapis dock
# dusty zinc which permissions do i have to give my bot to get rid of this error ```discord.e...
minor crescent
dusty zinc
lapis dock
#

Is it possible that your exe completes before 90 seconds?

dusty zinc
lapis dock
#

If you look higher in the error you should see either your open line or kill line. Can you confirm what one it is

dusty zinc
# lapis dock If you look higher in the error you should see either your open line or kill lin...
  File "C:\Users\ville\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\bot.py", line 1130, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "C:\Users\ville\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\commands\core.py", line 376, in invoke
    await injected(ctx)
  File "C:\Users\ville\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\commands\core.py", line 139, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc```
dusty zinc
lapis dock
#

I'm not entirely sure. You might have some luck in the python discord .gg/python but this is not Pycord related.

dusty zinc
lapis dock
#

Sorry I could not help more

dusty zinc
#

cant expect 1 person to know absolutely everything

keen relic
#
Traceback (most recent call last):
  File "D:\Night Club\.venv\Lib\site-packages\discord\ext\commands\core.py", line 180, in wrapped
    ret = await coro(*args, **kwargs)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "d:\Night Club\command\clean.py", line 28, in clean
    await embed_message.send_embed("Cleared all messages.")
  File "D:\Night Club\.venv\Lib\site-packages\discord\ext\bridge\context.py", line 99, in reply
    return await self.respond(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\Night Club\.venv\Lib\site-packages\discord\ext\bridge\context.py", line 92, in respond
    return await self._respond(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\Night Club\.venv\Lib\site-packages\discord\ext\bridge\context.py", line 168, in _respond
    message = await self._get_super("reply")(*args, **kwargs)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\Night Club\.venv\Lib\site-packages\discord\ext\commands\context.py", line 405, in reply
    return await self.message.reply(content, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\Night Club\.venv\Lib\site-packages\discord\message.py", line 1826, in reply
    return await self.channel.send(content, reference=self, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\Night Club\.venv\Lib\site-packages\discord\abc.py", line 1651, in send
    data = await state.http.send_message(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\Night Club\.venv\Lib\site-packages\discord\http.py", line 373, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In message_reference: Unknown message```
keen relic
#

bot sending this error

oblique sable
#

Hey, how can I send an audio file (mp3) as a voice message, like the one sent from mobile?

#

Using py cord

junior ember
#

async def join(ctx: commands.Context):
^^^^^^^^
NameError: name 'commands' is not defined

#

what does this mean

#

💀

lapis dock
#

Do you import commands?

junior ember
#

like

#

it wouldnt let me

#

from discord.ext import commands
ImportError: cannot import name 'commands' from 'discord.ext' (unknown location)

lapis dock
#

Can you show pip list

junior ember
#

aiohttp 3.9.3
aiosignal 1.3.1
attrs 23.2.0
DateTime 5.5
frozenlist 1.4.1
idna 3.6
multidict 6.0.5
pip 24.0
py-cord 2.5.0
pytz 2024.1
setuptools 69.2.0
yarl 1.9.4
youtube-dl 2021.12.17
zope.interface 6.2

lapis dock
#

If you recently updated Pycord can you restart your ide

junior ember
#

hm

#

now it gives me

#

raise ClientConnectorCertificateError(req.connection_key, exc) from exc
aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to host discord.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1000)')]

lapis dock
#

You need to update your certificate some how. I could not find anything quickly. You could ask in .gg/python where they might have more experienced people

frail laurel
#

How to handle a concept of local variables, I mean the ones that are custom to a specific user.
Let's say I have a slash command, and I don't want the user to execute the same command once again if he didn't click the button in the previous one. So yeah, I can create a variable with conditional just for that, but it's "global" it isn't specific to a user, in case where someone else will execute the command it could be blocked because someone else could've typed command already

shell radish
#

in python

frail laurel
# shell radish do you know what dictionaries are?

yes, but I've never seen someone using them in the context of a slash command, I mean veryfing if the same comand was typed out just a second before
and was wondering if pycord has something built-in to make it all easier (with freeing-up the data after it's no longer in use)

shell radish
grizzled loom
#

please ping on response, may take me a while to get back here though.

deft kestrel
#
Traceback (most recent call last):
  File "C:\Users\fagol\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 131, in wrapped
    ret = await coro(arg)
  File "C:\Users\fagol\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 1013, in _invoke
    await self.callback(ctx, **kwargs)
  File "C:\Users\fagol\Downloads\BBA\main.py", line 189, in gengemini
    await ctx.edit(embed=embed, view=RegenerateGemini(message, ctx))
  File "C:\Users\fagol\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\interactions.py", line 464, in edit_original_response
    params = handle_message_parameters(
  File "C:\Users\fagol\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\webhook\async_.py", line 648, in handle_message_parameters
    payload["components"] = view.to_components() if view is not None else []
  File "C:\Users\fagol\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 219, in to_components
    children = sorted(self.children, key=key)
AttributeError: 'RegenerateGemini' object has no attribute 'children'

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

Traceback (most recent call last):
  File "C:\Users\fagol\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 1130, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "C:\Users\fagol\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 376, in invoke
    await injected(ctx)
  File "C:\Users\fagol\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 131, in wrapped
    ret = await coro(arg)
  File "C:\Users\fagol\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 1370, in _invoke
    await command.invoke(ctx)
  File "C:\Users\fagol\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 376, in invoke
    await injected(ctx)
  File "C:\Users\fagol\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 139, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'RegenerateGemini' object has no attribute 'children'```
lapis dock
#

you view should look something like this

class myView(discord.ui.View):
  def __init__(self, arg1, arg2):
    self.arg1 = arg1
    self.arg2 = arg2
  @discord.ui.button(...)
  async def callback(self, button, interaction):
    interaction.respond(self.arg1)

Is that what you mean

deft kestrel
#

that

#
class RegenerateGemini(discord.ui.View):
    def __init__(self, prompt, ctx):
        self.prompt = prompt
        self.context = ctx
    @discord.ui.button(label="Regenerate", style=discord.ButtonStyle.primary, emoji='🔃')
    async def button_callback(self, button, interaction):
        button.disabled = True
        button.label = "Regenerating..."
        embed = discord.Embed(title="Text Generation (AI Chatbot)",
                        description="![loading](https://cdn.discordapp.com/emojis/1221856535257546752.webp?size=128 "loading") Regenerating Response...",
                        color=0x3498db)
...
#

yes ik im using ctx

sage tendon
#

...why?

deft kestrel
#

my generate needs the ctx from the command calling itself

sage tendon
#

you get all the context you need from the button interaction

deft kestrel
#

hmmm

#

god i need to read the docs more

#

😭

#

OOP is my worst enemy

sage tendon
#

OOP really isn't hard

#

you just need to know how it works

#

and why are you not sending the entire view

fickle salmon
#

I pass in self to my views, but not ctx 🙃

lapis dock
deft kestrel
#

i have not made interaction classes bro

#

i am stupid as fuck

sage tendon
#

you need to call the super class' constructor

#

else the view wont actually be made

deft kestrel
#

oh

sage tendon
#

you are sublcassing a view to make your own view
so you need to let the view class run its stuff, which is what you do with that

deft kestrel
#

so put super thingy inside subclass?

sage tendon
#

make it the first statement in the constructor

deft kestrel
#

im so used to doing this without classes so excuse my stupidness

#
class RegenerateGemini(discord.ui.View):
    def __init__(self, prompt):
        super().__init__()
        self.prompt = prompt```
#

?

sage tendon
#

yea

deft kestrel
#

ok that worked

#

ty

#

ily

#

please kiss me

#

whats the docs link for the fucking button interaction context

lapis dock
#

.rtfm discord.Interaction

glossy latch
#

how to solve unknown interaction error ?

shell radish
#

send full traceback

glossy latch
#

I don't have rightnow this error but sometimes it gets this error

shell radish
#

there could be many sources that cause this error so it is hard to say

glossy latch
#

Oh okey thx

hazy turret
frail laurel
sly karmaBOT
#

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

rugged lodgeBOT
#

Item not found.

sullen crane
#

does pycord have ability to control webhook?

lapis dock
#

yes, look here for more info