#Basic Pycord Help

1 messages ยท Page 67 of 1

ionic wasp
#

wym

silk spire
echo wraith
#

Not necessarily

#

Bots are user installable now

ionic wasp
#

yes im aware that self botting is against tos, im not doing any of it.
i just asked if i could receive an event if a bot message in a dm channel or similar was deleted by the person that used the command

echo wraith
#

They can delete their own messages

ionic wasp
#

They can

#

thats in a dm

echo wraith
ionic wasp
#

Yes

#

and can i get an event upon that deletion?

silk spire
echo wraith
# ionic wasp Yes

I don't remember if message delete is sent out dm channel, you can try that but I'm pretty sure it may not be sent.

echo wraith
#

For reference

ionic wasp
#

okay okay

echo wraith
#

Try also the raw one maybe

ionic wasp
#

thanks

silk spire
#

Receiving events by just having users install your app is weird and privacy invasing

Like think about it.. you install a bot to your profile and it can suddenly read your dms etc

echo wraith
silk spire
#

That's not what they're saying tho

#

They specifically said userapps#1132206148309749830 message

echo wraith
#

Yeah but it's already something

silk spire
ionic wasp
#

If the bot has an event if a command was ran, it should have an event if the message of that command was deleted

silk spire
#

Receiving events = on_message, on_message_delete = events

#

Why would it? What's so special about deleting the command response

#

That would make it possible for the dev to get the message content from a PRIVATE message

ionic wasp
silk spire
#

Doesn't matter. It was sent in a private conversation.

ionic wasp
#

mb then

echo wraith
#

@ionic wasp would you mind sharing more about your use case ? Maybe we can find an alternative solution

ionic wasp
#

i have a few games with the limitation of 1 active game per user, the game stops being marked as active if it ends or the view times out, id like it to also stop marking it as active if the message was deleted

silk spire
#

okay, that's actually a good usecase

echo wraith
silk spire
#

Is it possible to use a smaller timeout? The timeout resets on interaction ofc, so it would be easier to detect inactivity maybe?

echo wraith
ionic wasp
#

And gets annoying if the opposing player doesnt instantly respond to it, or vice versa

silk spire
#

Ah true

ionic wasp
echo wraith
#

Another option could be to tell the user that they already have a game ongoing, and send the info again. And or have a command/button to end the game.

ionic wasp
#

True i could add a button to the "you already have an active game" message that ends the previous game

silk spire
#

It not be possible to resend the ongoing game?

Or I guess the user could just delete that again and again lol

ionic wasp
#

Thats also possible, but that would require a ton more internal code and changes

#

thanks regardless, ill find a good solution

silk spire
#

Ah prettythumbsup

high spire
#

turned out to be an issue with mongodb

#

for some reason my userid stored as a collection in mongo keeps on rounding

#

maybe its cuz when I open it in vscode it converts to json?

echo wraith
#

Yeah

echo wraith
#

Discord snowflakes are 64 bit integers

sage tendon
#

you can also just store it as string

high spire
#

I think that's it I'll test it out

#

does json require this as well, or is it to do with the fact it's stored as a bson?

silk spire
#

Json rounds too when stored as int iirc

echo wraith
#

yes

deft hull
#

Is it possible to add a persistent view with parameters

sage tendon
#

only if you save those to a db

lapis dock
#

You get to initialize the view when you add it with add_view()
So you can accept custom args to the init. Like toothy said you would have to save the parameters somewhere so that you could fetch them when your bot restarts

high spire
#

await studentdata.insert_one({"name": self.fullname, "email": self.email, "discord_id": Int64(interaction.user.id)})

lapis dock
#

Make sure the column is of the correct type/length as well

high spire
lapis dock
#

Oh you are using mongo, It might have a different structure than I am used to.

lofty parcel
#

i just pass the int and mongo sets the type

#

you dont need to convert it

high spire
lofty parcel
#

oh nvm i store mine as strings doggokek

#

but i did used to send just the int

#

and it automatically converted

sage tendon
#

yea you should store it as string

ionic wasp
#

how do i limit commands to a specific guild / channelid?

errant trout
#

for channel... either filter by ctx.channel.id in the command, or if you're an admin in the guild you can set permissions in settings -> integrations

high spire
#

if anyone has the same problem in future, mongodb doesn't actually round the value automatically, it handles it

#

but when viewing it in vscode, it opened up as a json and misrepresented it even though the actual value stored was unchanged

lapis dock
#

Wow, that's not hard to debug at all (joke ๐Ÿคฃ)

deft hull
#

How do you get the jump_url of the response of an application command

sage tendon
#

response = await ctx.respond(...)
response.message.jump_url

quartz umbra
#

can dc bots have different pfps in different servers or is that ridiculous?

kind moat
#

is it intentional for pages.Paginator(pages=pageGroups) to error without show_menu=True

kind moat
# sage tendon error how
    if sum(pg.default is True for pg in self.page_groups) > 1:
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: 'NoneType' object is not iterable

discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: 'NoneType' object is not iterable```
hallow osprey
#

sorry if this is a noob question but i cant find anything on the docs
when loading a cog is it possible to reference a class in that cog? something like this:
main file ```py
bot.load_extension('cogs.views')
...
@bot.slash_command(name="hello", description="test")
async def button(ctx: discord.ApplicationContext):
await ctx.respond("", view=Views.ViewMain(), ephemeral=True) # also tried ViewMain()

**cog "views"** ```py
class Views(commands.Cog):

    def __init__(self, bot):
        self.bot = bot
    
    class ViewMain(discord.ui.View):
        @discord.ui.select(
            placeholder = "menu",
            min_values = 1,
            max_values = 1,
            options = [
                discord.SelectOption(label = "1", description="test")
            ]
        )
        async def select_callback(self, select, interaction):
            interaction.response.send_message(...)
            print(select.values)

def setup(bot):
    bot.add_cog(Views(bot))
#

i tried sending ViewMain() and Views.ViewMain() with no luck

sage tendon
#

import it

#

this is basic python, cogs arent some crazy construct, cogs are just classes

hallow osprey
#

oh ok

#

thanks

sage tendon
#

also dont put your views into a cog

#

serves no purpose, only just saw you did that

#

@hallow osprey

hallow osprey
sage tendon
#

because it doesnt do anything

#

it literally does nothing

hallow osprey
#

ok

sage tendon
#

and it makes them harder to import

lapis dock
#

Really it just makes your code cleaner

lapis dock
hallow osprey
#

is it possible to add custom emojis to buttons?

ionic wasp
hallow osprey
ionic wasp
#

Like server ones? should work

hallow osprey
#

nope

#

"invalid emoji"

ionic wasp
#

Does your bot have access to the server

hallow osprey
#

oh shit

#

mistake after mistake ๐Ÿคฆ

#

this is why i dont like programming

ionic wasp
hallow osprey
#

okay it works

ionic wasp
quartz umbra
#

Someone please tell me why this doesn't work: ```py

Wait for user response

    def check(m):
        return m.author == ctx.author and m.channel == ctx.channel and m.clean_content.lower() == "yes"
    print("waiting for user response")
    await self.bot.wait_for("message", check=check)
    print("user responded")
I'm very clearly typing yes. If i remove the yes condition it works (with whatever message I send)
silk spire
#

Maybe print clean_content in the check to see what you're comparing to

quartz umbra
#

let's see

#

okay what m.clean_content is just , what?

silk spire
#

Lmao

quartz umbra
#

and m.content

#
Tell me, does  == yes?
silk spire
#

Does your bot have access to message contents

quartz umbra
#

im dumb

#

always intents

#

that catch me out

#

intents can be annoying sometimes - it works now thx

hallow osprey
#

sorry if im annoying or something, i suck at coding
what could be wrong here?

Traceback (most recent call last):
  File "...\bot.py", line 60, in <module>
    class ViewRemote(discord.ui.view):
TypeError: module() takes at most 2 arguments (3 given)
#

this is the third view btw if that affects in any way

quartz umbra
hallow osprey
#

yeah but its just a bunch of buttons

#

i will try anyways

#

what was the paste service sorry

limber wagonBOT
#
Tags (1)

paste

#

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

hallow osprey
#

oh crap

#

how can i be so dumb

#

thanks

queen dirge
#

Sorry to come back to this, but I can't get it to work. When I have a command like so:
@bot_group.command(name="reload", description="Reloads cogs", guild_ids=[9621##############])
I can still see it on other servers. Does it matter that it's in a SlashCommandGroup at all? ex:

bot_group = bot.create_group(
    name = "bot", 
    description = "Bot related commands",
    integration_types = {discord.IntegrationType.guild_install}
)

I even tried making a subgroup that restricts based on what I saw on the documentation, but this doesn't work at all (people in other servers with no roles can still see it)

dev_subgroup = bot_group.create_subgroup(
    name = 'dev',
    description = 'Developer commands',
    guild_ids = [9621##############],
    default_member_permissions = discord.Permissions(permissions = 0, administrator = True)
)

Thank you!

sage tendon
#

subcommands dont count as individual commands

#

they inherit everything from the main command

#

including guild ids

queen dirge
#

Ohh my god thank you!!

pulsar ferry
#

Hey guys noob question - how can i set up a task to run at a specific time (i.e. cron) ? Trying to have something run every 3 days at 12p for example

sage tendon
lapis dock
#

I dont think we support the "Every x duration at y time"

sage tendon
#

oh yea i missed that mb

lapis dock
#

That should be a fairly simple thing to add I would think.
Allow the user to set next_iteration

#

I guess you could do something funky with change_interval
Start it with a time
Change the interval to every 3.5 days
When it runs check if it is close to the time if so, change the interval back to the time

torn barn
#

(Or allow passing seconds, minutes or hours with time)

lapis dock
#

Wait the duration then wait until the time?

torn barn
#

Yeah

#

It starts the loop every X duration

#

And then waits until Y time and runs

#

And like that continuously

#

Or maybe other param but shrug

lapis dock
#

That could even be implemented by the user if they want

#

with 2 loops

torn barn
#

Yah makes sense

#

Something like recurrent events on loops would heavily improve them lol

lapis dock
#

If I have time in the next few days I will look at tasks and see if there are some more features I can add.
I was also noticing that there is no way to have it wait until X to start the loop.

torn barn
#

Maybe using dateutil.rrule could help on tasks

#

Like, it would allow more flexibility on options for how they work

#

Plus it wouldnot make the code harder to read

queen dirge
sage tendon
#

no

lapis dock
#

No, discord did not entirely think subcommands through

queen dirge
#

Okay thank you!!

sage tendon
#

just do top level commands

#

there's no reason to bury them in a group like that

pulsar ferry
pulsar ferry
#

What is the proper way to be passing a time object?

    @tasks.loop(time=datetime.time(hour=12, minute=0, second=0))

#

doesnt seem to like this

lapis dock
#

Can you elaborate on that is not working? Also make sure you are thinking about timezones. (Just use UTC to make things easier)

echo wraith
#

from datetime import UTC fyi

pulsar ferry
#
Traceback (most recent call last):
  File "/Users/ethan/PythonProjects/EliteSweeps/main.py", line 21, in <module>
    bot.load_extension(f"cogs.{cog}")
  File "/Users/ethan/PythonProjects/EliteSweeps/venv/lib/python3.12/site-packages/discord/cog.py", line 918, in load_extension
    self._load_from_module_spec(spec, name)
  File "/Users/ethan/PythonProjects/EliteSweeps/venv/lib/python3.12/site-packages/discord/cog.py", line 787, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.errors.ExtensionFailed: Extension 'cogs.casino' raised an error: TypeError: unbound method datetime.time() needs an argument
pulsar ferry
lapis dock
#

You need to use datetime.time, with that import I think you are using datetime.datetime.time

echo wraith
#

yes

echo wraith
pulsar ferry
#

ah yep that did it

#

thanks

echo wraith
#

np

lofty parcel
#

I use datetime.datetime.datetime.datetime.time

sage tendon
#

p sure

pulsar ferry
echo wraith
#

datetime.timedate.date.dimeddate.datedtime.dt.tdate.time

kind moat
#

how can you remove attachment from bot response

sage tendon
#

pass files=[] to the edit

hallow osprey
#

how do i sleep after sending an interaction response message

sage tendon
#

sleep how

echo wraith
#

like this

hallow osprey
sage tendon
#

just asyncio.sleep

hallow osprey
#

doesnt work

#

or maybe i have skill issue idk

#

oh yeah i do

sage tendon
#

"doesnt work" gives no info about your actual problem

twilit socket
#

users: list[discord.Member]
there's no way to get a list of users on the command? a select or something? this is giving me error. I checked on the on the docs about the discord.Option and there's only discord.Member as a type visible. A discord limitation or am i missing something?

lapis dock
#

Options cannot accept multiple things, discord limitation
Some solutions

  1. Use a user select menu
  2. Create an autocomplete function that you can use , as a seperator between user names
  3. Create multiple options
deft hull
#

How can I import a cog method like send_death_message to another module?
I've tried importing the MoneyGame cog class entirely but the import failed

errant trout
#

e.g. ```py
cog = self.bot.get_cog(COG_CLASS_NAME)
await cog.some_cog_function(...)

#

(you can also do this to directly run commands in other cogs)

deft hull
#

Thanks ๐Ÿ‘

dry gust
#

Is there any way to get list of active events on server? I want to let admins (or automatic) set boosts (for exp and etc.) during some events

dry gust
#

no idea

lapis dock
#

Both of these

#

Then just loop through to see if they are active

dry gust
#

thank you!

fresh sierra
#

Is there a subgroup before invoke ?
Like there is in prefix command ?
(bump)

autumn gust
frail basin
little cobalt
sly karmaBOT
#

Tag not found.

Did you mean...
audioop
audioop-lts

little cobalt
#

.tag audioop-lts

sly karmaBOT
#

Pycord 2.6.1 may work with Python 3.13, however it is not officially supported currently and can cause various issues. Until it is supported, it is recommended to use a previous version.

You might need to run pip install audioop-lts for voice features until Pycord 2.7 includes a Python-based audioop implementation.

autumn gust
#

oh ty

#

ah wait, how do you set up slash commands to work as a member app rather than a guild app?

autumn gust
rugged lodgeBOT
#

Here's the slash users example.

autumn gust
#

ty

#
@bot.slash_command(integration_types={discord.IntegrationType.user_install}, name="ping", description="ping the bot!")
async def ping(ctx: discord.ApplicationContext):
    await ctx.respond("๐Ÿ“ Pong!")

@bot.slash_command(
    integration_types={discord.IntegrationType.user_install},
)
async def greet(ctx: discord.ApplicationContext, user: discord.User):
    await ctx.respond(f"Hello, {user}!")

I've got both of these, and none of them seem to even show up?

sly karmaBOT
# autumn gust ```py @bot.slash_command(integration_types={discord.IntegrationType.user_install...

Application Commands Not Showing Up?

  • Refresh Discord by restarting or pressing Ctrl+R (or Command โŒ˜ + R)
  • Uninstall libraries that conflict with the discord namespace (e.g. discord.py).
  • Invite your bot with the application.commands scope.
  • Load cogs before bot.run() (e.g. not in on_ready).
  • Do not override on_connect.
  • Update to the newest version of py-cord (see ?tag install).
  • Turn off User Settings > Accessibility > Chat Input > Use legacy chat input.
  • Share your code and errors.
autumn gust
#

oh shit right I forgot about the application.commands scope

#

thank you

#

I haven't done this for over a year, apologies

sage tendon
#

is your bot purely a user bot

echo wraith
#

np lmk if anything

sage tendon
#

also you should typehint your user var as discord.Member

deft hull
#

Hi, how do you get the message author in this case?

@discord.slash_command()
    async def shop(self, ctx):
        '''Buy some items.'''
        user = MoneyUser(ctx.user.id)
        view = ShopView()
        view.message = await ctx.respond(embed=ShopEmbed(user), view=view)

ShopView()

class ShopView(discord.ui.View):

    def __init__(self):
        super().__init__(timeout=None)
        self.sender = self.message.author
        self.user = MoneyUser(self.sender.id) # not to be confused with discord.User!!
AttributeError: 'NoneType' object has no attribute 'author'
ionic wasp
#

you can pass it into the view

deft hull
#

Yeah but the message returns None since ctx.respond returns an Interaction

deft hull
deft hull
#

Persistent views only work for a single message?

echo wraith
#

No

deft hull
#

Still confused on how persistent views work

autumn gust
echo wraith
autumn gust
#

I wanna make a small debug command with a few choices,

@bot.slash_command(integration_types={discord.IntegrationType.user_install}, name="debug", description="various debug things")
@discord.option("Debug Option", type=str)
async def debug(ctx: discord.ApplicationContext, choice: type):
    if type == "text file test":
        textfile = "debug.txt"
        with open(textfile, "r") as file:
            filecontent = file.read()
        ctx.respond(f"{filecontent}")
    else:
        ctx.respond("oops")

this is what I got so far, and I don't know how to make the selector, any help?

echo wraith
autumn gust
echo wraith
#

thy

echo wraith
# autumn gust huh?

It's bc of the decorator. You can use discord.option("...", choices=["a", "b", "c"])

echo wraith
echo wraith
#

Because it's with a user command

autumn gust
#

ah fair

autumn gust
#

oh that's the decorator text nvm I'm stupid

#

that doesn't show up at all?

#

(the command does just not the choice thing)

lofty parcel
echo wraith
sly karmaBOT
# autumn gust that doesn't show up at all?

Application Commands Not Showing Up?

  • Refresh Discord by restarting or pressing Ctrl+R (or Command โŒ˜ + R)
  • Uninstall libraries that conflict with the discord namespace (e.g. discord.py).
  • Invite your bot with the application.commands scope.
  • Load cogs before bot.run() (e.g. not in on_ready).
  • Do not override on_connect.
  • Update to the newest version of py-cord (see ?tag install).
  • Turn off User Settings > Accessibility > Chat Input > Use legacy chat input.
  • Share your code and errors.
echo wraith
#

try restarting discord after making changes to commands metadata

lofty parcel
#

How else would you access it inside the command

#

async def ...(ctx, debug_option: str)

sage tendon
sage tendon
#

Many things aren't filled in, but it's still a member object

echo wraith
#

Yeah you're right

#

It's user when using in private contexts

echo wraith
#

But yeah in that case it was indeed correct to use discord.Member and not discord.User

autumn gust
#
async def get_animal_types(ctx: discord.AutocompleteContext):
  """
  Here we will check if 'ctx.options['animal_type']' is a marine or land animal and return respective option choices
  """
  animal_type = ctx.options['animal_type']
  if animal_type == 'Marine':
    return ['Whale', 'Shark', 'Fish', 'Octopus', 'Turtle']
  else: # is land animal
    return ['Snake', 'Wolf', 'Lizard', 'Lion', 'Bird']

@bot.slash_command(name="animal")
async def animal_command(
  ctx: discord.ApplicationContext,
  animal_type: discord.Option(str, choices=['Marine', 'Land']),
  animal: discord.Option(str, autocomplete=discord.utils.basic_autocomplete(get_animal_types))
):
  await ctx.respond(f'You picked an animal type of `{animal_type}` that led you to pick `{animal}`!')

is this an old example or something? pasting it in to understand the code behind it errors out and doesn't show the slash command at all

little cobalt
autumn gust
#

restarted twice and still doesn't appear to even do as much as show up?

little cobalt
autumn gust
little cobalt
#

The discord client?

autumn gust
#

yes

#

refreshed the bot a 2nd time to sanity check, doesn't work either

glossy tide
#

What are the best useful libraries for Pycord bots? I found for example DiscordUtils (for Tracking Invite and music), but I don't think it's a good idea since it's abandoned. In addition, I would look for something that allows you to make welcome/level images easily.

If you know other librairies that facilitate other tasks, you can tell me too

shell radish
#

people usually use PIL/pillow/python image library to create images

lapis dock
#

TBH there are not really libraries that you would use. If you are looking for premade stuff it would be better to find the codesnipets somewhere (such as github) and copy-paste it into your own code.

lofty parcel
#

God forbid ezcord

glossy tide
shell radish
glossy tide
#

Oh okat

#

Okay

ionic wasp
#

how is this replicable, when sending a command with a attachment arg

lapis dock
# autumn gust

This is just a VS code thing. It should not effect the actual functionality of your bot.

ionic wasp
# autumn gust

to ignore those you can put # type: ignore after the line where that warning occurs iirc

sage tendon
#

or use the decorator version to do options

autumn gust
sage tendon
#

same way as with the typehint

#

they're 95% the exact same

#

check the docs and you'll see

hybrid fossil
#

Hi there!
Am I the only one for whom change_presence no longer works?

lofty parcel
#

There's some issue with activities if it hasn't been fixed yet

shell radish
lapis dock
#

squid no scolding users about grammar in the help channels doggokek

lofty parcel
shell radish
lapis dock
#

Pretty sure squid made grammerly with how much they know about grammar

versed root
#
@slash_command()
async def add_reaction(self,ctx:discord.ApplicationContext,emoji: str):
    """test_reaction"""
    try:
        await ctx.response.defer()
        message = await ctx.channel.fetch_message(1302520347651739668)
        await message.add_reaction(emoji)
        await ctx.respond("done")
    except Exception as e:
        await ctx.respond(e)

When I use the command for the first time, it can add a reaction. But when I use it the second time, it gets stuck at the add_reaction line and keeps loading. Why does this happen? Did I do something wrong?

hushed rivet
#

got this error recently - anyone know why?

frail basin
#

You should defer the interaction, which extends this window to 15 minutes.

hushed rivet
#

interesting

#

pretty sure it has a defer

#

showd up on clientside as timed out

frail basin
#

Speaking from experience, if your command defers the interaction, its probably something with your host's network

#

Is this a public or private bot?

hushed rivet
#

public, and works perfectly after a restart

#

maybe it just had a quick lapse in compute resources or smth - its on a quite small vps

frail basin
#

Do all of the interactions fail or only a few?

hushed rivet
#

theyre all fine now, i cant make it crash it only happened once in months

frail basin
#

Probably just a network blip then.

hushed rivet
#

alright, thanks

#

just wanted to know if it was a known issue in some other way lol

frail basin
hushed rivet
#

oh

#

oops, i kinda assumed it crashed

#

does pycord have error handling in that way

frail basin
#

Yeah

#

Seems like it properly caught it

frail basin
hushed rivet
#

ah, that makes sense

#

didnt even think to test it

#

thanks for the help!

silk spire
#

Those are coded into the client

ionic wasp
#

oh

#

odd

silk spire
#

Discord wants to control everything so shrug

sage tendon
#

it's just a discord sided error. it doesn't involve the bot at all. so it makes no sense for the bot to intervene in some way

autumn gust
#

and I don't see an example of a decorator autocomplete?

sage tendon
#

?

#

all in the guide and docs

#

just gotta look for it

#

and you just pass the autocomplete in there just like you already do

autumn gust
# sage tendon

wait, so instead I should do

@discord.option("autocomplete hint here", type=discord.AutocompleteContext)
#

?

lapis dock
#

Reading docs is definitely a skill. With practice you will get better at it. But it is a important part of development. You should try not to dismiss it as "I dont know how to read docs"

autumn gust
#

like autocomplete thing right now is a good example of it lmao

lapis dock
#

In the example listed above "first" is the name of the argument

sage tendon
#

autocomplete=autocompletefunction()

lapis dock
#

To convert from typehint to decorator options you just need to copy paste what you had in the Option(...)
And put it in the decorator version. @discord.option(...) and then add the name of the argument as the first argument of the decorator.

autumn gust
#

ooooooooooh wait, okay I get it now I think?

sage tendon
#

yea but just pass the type positionally, and just pass str
you really don't need the slashcommandoptiontype stuff it's kinda unnecessary

#

and no, the first string is the name of the option

tidal vessel
#

Does Pycord already have support for Python 2.13?

sage tendon
#

description is done via description=

#

all neatly described in the docs

sage tendon
little cobalt
sage tendon
#

:> as for 3.13, not quite but it works if you install audioop-lts

tidal vessel
little cobalt
#

xd

tidal vessel
#

So I'm still at 3.12 for now.

tidal vessel
sage tendon
#

not to my knowledge

#

just don't use 3.13.1

#

3.13.0 works, but .1 is just not working with some really weird error

echo wraith
tidal vessel
#

Ok thanks for the information

lapis dock
#

There are some other minor issues, something with flags for prefix commands

autumn gust
#
async def debug_options(ctx: discord.AutocompleteContext):
    animal_type = ctx.options['debug']
    if animal_type == 'Marine':
        return ['Whale', 'Shark', 'Fish', 'Octopus', 'Turtle']
    else: # is land animal
        return ['Snake', 'Wolf', 'Lizard', 'Lion', 'Bird']

@bot.slash_command(integration_types={discord.IntegrationType.user_install}, name="debug", description="various debug things")
@discord.option("pick the debug option", type=str, autocomplete=discord.utils.basic_autocomplete("text file debug"))
async def debug(ctx: discord.ApplicationContext, debug=["text file debug", "no debug"]):
    if debug == "text file test":
        textfile = "debug.txt"
        with open(textfile, "r") as file:
            filecontent = file.read()
        await ctx.respond(f"{filecontent}")
    else:
        await ctx.respond("oops")

trying to weave that example function into my code to see how it works, but it just doesn't appear to?

sage tendon
#

you ignored what I said

#

the first parameter of the option decorator is the option name, which should match the name of the argument in the function def

#

and don't do debug=(this) in the function def, just typehint it as str there

lapis dock
#

Are you planning on adding dynamic options to the command or will you only ever have text file debug and no debug?

sage tendon
#

also uh, if you want to limit it to a certain amount - yea what Wolfy said

sage tendon
autumn gust
#

yeah and what you said means nothing to me rn

sage tendon
#

what part

autumn gust
#

wdym by the first argument is a name, what do I do then?

sage tendon
#

change it to the name of the option

autumn gust
#

also, what's typehinting

lapis dock
# sage tendon

In this example you can see that the arguments for the command are ctx, first, second and the options first arguement is first the argument of the function and the first argument of the option have to match

sage tendon
#

e.g. debug in your case

autumn gust
#

wait, so this?

#

fuck wai tno that's the command

sage tendon
#

that's the other thing I said, but you need to change it in the option decorator

lapis dock
#

that is part of the solution

autumn gust
#

so, like this, yes?

sage tendon
#

no

#

debug

#

just that (as string)

lapis dock
#

No, you are confusing the actual name of the argument with the description

sage tendon
#

and you can remove the type= before str to pass the type argument positionally, saves you a few characters

autumn gust
lapis dock
#

๐Ÿ‘

autumn gust
#

so now, how to add autocomplete onto this?

sage tendon
#

well

autumn gust
#

wait so I did everything correctly except my command was fucked?

#

lmao

sage tendon
#

you gotta put your real function there but that's how

#

if you use the discord utils autocomplete thingy you need to pass the function name of your autocomplete there, NOT as string, and NOT with () after it

#

it does the matching on its own
if you plan to handle that in your own function it's enough to put your command name in autocomple=, that time WITH ()

#

might be confusing but if you read it slowly, twice, it'll make sense

autumn gust
#

I only plan to have a few debug options to test out features myself, and it's just so I don't have to look at code to remember every single one,

also, can you explain what passing the function means?

sage tendon
#

if you do autocomplete=discord.utils.basic_autocomplete(functionname) the library will automatically only match the values that start with what the user already typed, i think
if you do autocomplete=functionname() all values shown to the user depend on what you return from your autocomplete function

autumn gust
#

so wait, if I want to do autocomplete=functionname() I can do:

async def debug_options(ctx: discord.AutocompleteContext):
  return "option1"
  return "option2"
  ...

?

sage tendon
#

thats not how python works lol

autumn gust
#

right.

#

oh yeah wait isn't it

sage tendon
#

if you look at the docs, you'll see that it expects either a list of strings, floats or ints, or to be passed a function name directly (never saw that used though)

autumn gust
#
async def debug_options(ctx: discord.AutocompleteContext):
  return ["option1", "option2", "option3"]

instead?

sage tendon
#

yea

autumn gust
#

what did I miss again

sage tendon
#

ah yea i forgor something

#

remove the parentheses

#

im dumb

lapis dock
#

smh toothy doggokek

sage tendon
#

mrow

autumn gust
#

moment of truth

sage tendon
#

now type n

#

or t

autumn gust
#

still works for me!

#

that'll be a job for another day probably tbh

#

unless... hold on

sage tendon
#

just wrap it in discord.utils.basic_autocomplete

#

that should make that work

autumn gust
#

yeah, it just clicked

#

thank you!

stray cape
#

hey guys I'm getting this error many times

#

Exception occured:

  File "/home/luxkatana/pyenv/lib/python3.11/site-packages/discord/client.py", line 443, in _run_event
    await coro(*args, **kwargs)
  File "/home/luxkatana/cautious-computing-machine/main.py", line 191, in on_ready
    mainloop.start()
  File "/home/luxkatana/pyenv/lib/python3.11/site-packages/discord/ext/tasks/__init__.py", line 327, in start
    raise RuntimeError("Task is already launched and is not completed.")
RuntimeError: Task is already launched and is not completed.
#

while running my bot for a long time

#

mainloop is a task

lofty parcel
#

on_ready can fire multiple times

#

You should add a check or add a once listener instead of using the event

lofty parcel
#

.rtfm listener

lofty parcel
#

You can add in a cog

stray cape
#

just a simple cog with one listener?

lofty parcel
#
@commands.Cog.listener(once=True)
async def on_ready(self):
      await mainloop.start()
stray cape
#

aha okay

#

this'll trigger once on_ready

lofty parcel
#

Or if you don't wanna waste time just to make a cog for a listener

#

Just add a check

stray cape
#

why does on_ready get then triggered many times?

lofty parcel
#

This library implements reconnection logic and thus will end up calling this event whenever a RESUME request fails.

stray cape
#

I'm starting to understand you

#

alright thank you

stray cape
sage tendon
#

honestly just create a boolean and change it to true if on ready already ran, and then only start the task in on ready if that var is false

stray cape
#

yeah that should work too

#

much simpler

stray cape
sage tendon
#

i think just putting it in your main file should work fine

stray cape
#

oh globally

sage tendon
#

thats not global tho

lofty parcel
#

Both ways would work

#

Use whatever your want

stray cape
sage tendon
#

(why people just dont use cogs in general is still beyond me but oh well)

stray cape
#

because my project only consists of a main loop

#

and maybe one or two slash commands :p

lofty parcel
sage tendon
#

var = False
on_ready
if not var:
start task
var = true

stray cape
#

yeah ill just add a globally one

lofty parcel
#
fired = False

@bot.event
async def on_ready():
    if not fired:
            await mainloop.start()
            fired = True
limpid marten
#

toothy still at being a goat

stray cape
#

ill just keep it at this then ig

#

thx people!

stray cape
lofty parcel
#

Oh idk probably you don't have to await it

#

I haven't touched code in like 4 months

stray cape
stray cape
#

that explains but thanks guys

#

!!

#

too lazy to write a commit message

sage tendon
#

brh

limpid marten
#

this is kinda stupid and i can prolly answer this question by just double checking the docs but... how do i make an optional text thingie as in

sage tendon
#

use options

#

and i recommend the decorator version

limpid marten
#

yeah i dont think i used this correctly

sage tendon
#

you did

#

but thats not the decorator lol

limpid marten
#

i used type annotations anyways

#

seemed easier

sage tendon
#

well just for my two cents, its a lot more chaotic and messy than decorators

#

oh well

limpid marten
#

it shows up as a required option though

sage tendon
#

well you didnt pass required=False lol

#

it doesnt magically know what you want

limpid marten
#

oops

sage tendon
#

look at the docs

limpid marten
#

yup, found it, thank you

kind moat
#

use_default_buttons=False, custom_buttons=[], show_disabled=False fail to hide default buttons on default pagegroup

kind moat
#

how to get application emojis

sage tendon
#

they are not supported yet

lapis dock
#

It is on master!

round heart
#

Wen 2.7

lapis dock
fallen torrent
#

hey guys, how do i place a channel at a specific index inside of a category like

cat
  - channel 1
  - channel 2
  - channel 3

and i want to place a new channel, channel 4 at where channel 1 is

rugged lodgeBOT
sage tendon
#

I think it's position

#

additionally to passing the category

round girder
#

everytime i access discord.ApplicationContext.command.id it is not the commands actual ID and I have no idea where the number is being pulled from. what is happening here?

#

this has been an issue for literally weeks and 5 minutes ago i was legit like "what if somehow the data is wrong in the context?" and it is... for some reason

#

looking through the docs has led me to be further confused because.. shouldnt it be the correct command ID?

#

very lost rn

#

please @ me if you have anything to say

round girder
#

i may have figured out where its coming from... but im still very confused on why..

discord>my server>settings>integrations>my bot>commands>copy command id>
                         : 1013672725501448272
command id in my database: 1013672725501448272
id from ctx              : 1333583531024318562
id from cog.command.id   : 1333583531024318562
lofty parcel
round girder
#

no, for this example im literally using my help command

#

no groups

#

i dont use groups

#

groups suck

#

at least rn

#

this is on the development bot of mine, but it works fine on production

#

the only difference I can think of now that im really thinking is maybe its because my development bot has the command limited to 3 servers?

#

is the command ID different if you limit it to a set number of servers?

#

like

round girder
# round girder like

class Help(commands.Cog):
  def __init__(self, client : commands.Bot):
    self.client = client

  @commands.slash_command(
    guild_ids = ALL_SERVERS,
    name = data.commands.help.name,
    description = data.commands.help.description
  )
  @cooldown(
    1,
    data.commands.help.cooldown,
    BucketType.user
  )
  async def cb_help(
    self,
    ctx : discord.ApplicationContext
  ):
    ...
    print(f"INTERNAL1: {data.commands.help.id()}")
    print(f"EXTERNAL1: {ctx.command.id}")
    print(f"INTERNAL2: {self.cb_help.id}")
    ...


  def setup(client : commands.Bot):
    client.add_cog(Help(client))

when run:

CONSOLE:

INTERNAL1: 1013672725501448272
EXTERNAL1: 1333583531024318562
INTERNAL2: 1333583531024318562
#

the ALL_SERVERS is a list of IDs for my dev bot and null for the prod bot

#

it works fine there so im guessing thats the issue

#

ill see if i can just use these weird new IDs

lapis dock
#

I believe so, I think each server gets its own command and ID
Ideally you should not be working with the ID because the name of the command needs to be unique anyways and is more reliable.

#

I dont think it is possible to change the name without changing the ID either so essentially the name is the non-changing ID

round girder
#

well that sucks

#

ID literally becomes meaningless then

#

isnt the purpose of ID to IDentify

lapis dock
#

Yeah, but it sounds like in your case you can just use the command name as the ID. Because that will also identify the command.

arctic oar
#

Ever since the Discord patch on Feb 3 with the re-written Media Proxy (not sure if this is even related)

My bots been responding very slowly (30sec+) when sending images as files, does anyone know how to fix this?

wary silo
#
embed = discord.Embed(title=embed_title, color=appctx.author.color, footer=discord.EmbedFooter(page_range))
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: module 'discord' has no attribute 'EmbedFooter'

what may cause this? running on synology nas container manager, py3.11.4 py-cord 2.6.1, no install any other discord related packages. i can see EmbedFooter at embeds.py on my computer
i've run this code around 1.5 years age, it's no problem at that time

#

it's fine if i use set_footer, just curious

sage tendon
#

maybe you're not supposed to access it directly

#

also you're running python 3.13 lol

wary silo
#

got it

#

that's in my computer XD, it's 3.11.4 in container, i know it can't run in 3.13 now, cus of the audioo(somethin like this) problem

#

EmbedFooter is fine in 3.12.9, another version on my computer, so maybe some problem with contaner's version, but i don't use alpine version

quartz umbra
#

this seems really dumb but uh are you actually able to do this?? (where on_message is registered normally)

for message in messages:
        await on_message(message)

?

sage tendon
#

what

#

why?

quartz umbra
#

it would just be easier for a little something im doing

#

if that was possible

sage tendon
#

what are you doing

quartz umbra
#

so im doing some processing in on_message to like update to a db, and im just making a helper function to bulk-process a bunch of messages at once

#

in case the bot is offlien or smth

sage tendon
#

i mean sure, try it
if it doesnt work (not sure how listeners work exactly) just put all your on_message code into a seperate function you can then call normally

quartz umbra
#

yeah ig

#

it would be cool if it worked

silk spire
#

Why wouldn't it work, It's still a normal python function

quartz umbra
#

for future reference: no it doesn't work

silk spire
#

Any errors?

quartz umbra
quartz umbra
silk spire
#

All the decorator does it add it to an internal dict and return the function

quartz umbra
#

lets see

#

nvm its my logic

quartz umbra
#

i'll update you when i fix it

sage tendon
#

thats also why you cant directly call slash command functions

#

the decorator changes the attribute to be a SlashCommand object

silk spire
#

We're talking about listeners tho

sage tendon
#

i doubt its any different for listeners

silk spire
#

What would it return?

#

A Listener object? Commands return the object to allow setting an error handler etc

sage tendon
#

hm yea seems listeners leave it intact

silk spire
#

slash commands could implement __call__ to somewhat keep the original behaviour lol

sage tendon
#

there's something like that

edgy nest
silk spire
#

Ohh, nice!

round girder
#

reloading extensions is not working for me. ill run client.reload_extension after saving a file and.. it wont reflect changes made in the cog file

#

please @ me

sage tendon
#

reloading cogs with slash commands isn't really working properly iirc

fresh sierra
round girder
#

sometimes it works fine but lik 70% of the time im left there like bruh

fresh sierra
round girder
# fresh sierra await bot.sync_commands

doesnt this.. only do things on discord's side? im talking about, for example, changing the color of a command's embed from red to orange and it not working (unless i restart the bot)

fresh sierra
#

But I understand your thing now so yeah itโ€™s not about discord slash command

#

Can you pls show the code, itโ€™s gonna help us understand

round girder
#

ima just listen to Toothy and trust that its not working for whatever reason

sage tendon
#

i was talking about slash commands not properly resyncing
code changes itself should work, although im not sure if unchanged slash commands even load properly again

if you really wanna test this, make a cog that only has a prefix command and try the same thing there

wary silo
flat wind
#

Hello !
why does the user.mutual_guilds do not return all mutual guilds but only some ?
to get the user info, I used get_or_fetch_user method

silk spire
#

Cache

#

It relies on guilds and members cache:

[g for g in bot.guilds if g.get_member(user.id)]

Also it only gets the servers they share with your bot, not you.

mighty otter
#

Is it possible to use modals without making a class?

lapis dock
#

Technically yeah, you just have to set m.callback manually

mighty otter
#

can you please giv4e a short example snippet because when i do that it doesnt close the modal popup and says "Something went wrong." (its from a button btw)

little cobalt
lapis dock
#

Yeah, that sounds like a problem with your code. Can you show what you tried

stray pasture
#

Is the new monetization by Discord still only required in US ?

sage tendon
#

supported* yes
I think maybe UK too but nowhere else afaik

stray pasture
#

oh I found the complete list

#

I still don't have to support it ๐Ÿ˜„

#

perfect

sage tendon
#

that's only the supported locales

#

not countries where it works

stray pasture
#

ooh what is the differences ?

sage tendon
#

oh wait

#

no they just worded it dumbly

#

bruh

#

also I think for some reason bot monetisation is different to server monetisation regarding which countries it works in

stray pasture
#

for the link I found it here

#

But is it safe to assume if my country is not there that I donโ€™t have to do it ?

sage tendon
#

why would you have to do anything lol

stray pasture
#

otherwise they terminate my app ahahaha

sage tendon
#

because you have premium stuff already?

stray pasture
#

I just needed to verify on stripe and send valid gouvernement id to stripe

#

Yeah I have premium, but not throught discord

sage tendon
#

ah yea

#

yea no then you don't need to do anything, I mean, you can't

stray pasture
#

yeah the fees are now 15 % for growth tier instead of 2.9% + 0.3 ahaha

#

for use the stripe in both ways

#

instead of having 2 $ fees for lifetime, I will notw have 11 $ ๐Ÿ˜„

mighty otter
# lapis dock Yeah, that sounds like a problem with your code. Can you show what you tried
            async def modal_callback(interaction):
                modal = Modal(title="Enter Your Player's Name")
                modal.add_item(InputText(label="Player Name", placeholder="Enter player name", min_length=4, style=InputStyle.singleline))

                await interaction.response.send_modal(modal)

                await modal.wait()
                player_name = modal.children[0].value.strip()  # Extract the input text

                select.options = get_player_options(player_name)
                select.disabled = False

                player_embed.description = f"Selected Player: **{player_name}**\nChoose from the list below!"
                await interaction.message.edit(embed=player_embed, view=view)
lapis dock
#

You are not ever responding to the modals interaction. You should move everything after .wait into the modals callback. And then respond to the interaction with an edit message instead of editing the message separately. Then you can remove the modal.wait.

This would be a bit simpler if you just sub classed the modals.

steep garden
#

Hi ! I'm working on a realtime transcription of voice calls bot. To reduce latency, I want to start transcribing the audio as soon as possible and not once everything have been saved. I see there is a connect_websocket in the Voice client implementation but there is no documentation. Does anybody knows how it works ? Or maybe any other way than waiting for the callback function of start_recording so I can start the transcription while the audio is being recorded ? Thanks in advance !

lapis dock
#

Best that I can say is good luck, I know there have been other users that have done (or tried to) in the past.
I might be able to look into a bit more later but no guarantees.

lofty parcel
#

I believe there's something about transcription in #creations

lapis dock
#

#creations message

steep garden
#

Nice thanks ! ๐Ÿ™

fallen torrent
#
    async def delete_slot_autocomplete(self, ctx: discord.AutocompleteContext):
        slotsdb = SlotsDB()
        slots_channels = []
        for slot in slotsdb.get_all_slots():
            channel = slot.get("slot_id")
            if channel is not None:
                slots_channels.append(discord.utils.get(ctx.interaction.guild.channels, id=channel))
        return slots_channels```
ive got this autocomplete, but what input_type should i set for Option, doing discord.TextChannels seems to override the autocomplete, i only want it to show the autocompletes text channels
naive ferry
#

I change to using a venv, and now im getting this error?

Traceback (most recent call last):
  File "/home/stigstille/Bots/BurgyBot/discordBot.py", line 1, in <module>
    import discord, pygsheets
  File "/home/stigstille/Bots/BurgyBot/burgybot/lib/python3.13/site-packages/discord/__init__.py", line 27, in <module>
    from . import abc, opus, sinks, ui, utils
  File "/home/stigstille/Bots/BurgyBot/burgybot/lib/python3.13/site-packages/discord/abc.py", line 58, in <module>
    from .voice_client import VoiceClient, VoiceProtocol
  File "/home/stigstille/Bots/BurgyBot/burgybot/lib/python3.13/site-packages/discord/voice_client.py", line 55, in <module>
    from .player import AudioPlayer, AudioSource
  File "/home/stigstille/Bots/BurgyBot/burgybot/lib/python3.13/site-packages/discord/player.py", line 29, in <module>
    import audioop
ModuleNotFoundError: No module named 'audioop'
#

i dont even use any VC things

raw beacon
#

.tag audioop

sly karmaBOT
#

Pycord 2.6.1 may work with Python 3.13, however it is not officially supported currently and can cause various issues. Until it is supported, it is recommended to use a previous version.

You might need to run pip install audioop-lts for voice features until Pycord 2.7 includes a Python-based audioop implementation.

lapis dock
stray pasture
#

is there a Python Library for Top.gg that works with py-cord ? The official one is with discord.py

lofty parcel
stray pasture
lofty parcel
#

You can simply uninstall d.py or ignore the dependency when using pip install

#

Weird cause their github repo only shows aiohttp as a req

stray pasture
lofty parcel
#

It's probably because they subclass shit from d.py to make a custom client

stray pasture
#

maybe I jsut copy paste the code I want ahaha

#

I just want to update the server count

#

๐Ÿ˜„

#

not that complicated

lofty parcel
#

I mean you could also just send a raw request by yourself

stray pasture
#

yes I think I will do that

#

thank you ๐Ÿ™ƒ

errant trout
#

fwiw you can make any arbitrary request on a bot using bot.http.get_from_cdn(url)

lapis dock
silk spire
#

Yeah it doesn't seem to use anything from dpy or any package other than aiohttp anymore

echo wraith
#

I just did it manually, when I used to use topgg. Their python sdk sucks

stray pasture
#

Will probably call the endpoint directly

granite python
#

``AttributeError: 'Bot' object has no attribute 'add_command'. Did you mean: 'all_commands'?

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

Traceback (most recent call last):
File "C:\Users\pbris\PycharmProjects\PythonProject\zeusbot2.0\main.py", line 13, in <module>
bot.load_extension('cogs.Moderation')
File "C:\Users\pbris\PycharmProjects\PythonProject\zeusbot2.0.venv\Lib\site-packages\discord\cog.py", line 918, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Users\pbris\PycharmProjects\PythonProject\zeusbot2.0.venv\Lib\site-packages\discord\cog.py", line 801, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.errors.ExtensionFailed: Extension 'cogs.Moderation' raised an error: AttributeError: 'Bot' object has no attribute 'add_command'`` Could anybody, by chance, lend me some of their knowledge to understand what may be causing this? I can post the code as well but don't want to flood this text channel if it's more complex and needs to be posted in it's own ticket.

sage tendon
#

can you show the code in your cog

granite python
#

Yes, all of it?

sage tendon
#

you didnt show the initial error so i can only assume you are using bot.add_command

granite python
#

``class Moderation(commands.Cog):
def init(self, bot):
self.bot = bot
print('added cog')

@commands.command(name='kick', description='Kicks a user from the server.')
async def kick(self, ctx: discord.ApplicationContext, member: discord.Member, reason: str):
    await member.kick(reason=reason)
    await ctx.respond(f'Kicked {member.name}: {reason}!')

@commands.command(name='ban', description='Bans a user from the server.')
async def ban(self, ctx: discord.ApplicationContext, member: discord.Member, reason: str):
    await member.ban(reason=reason)
    await ctx.respond(f'Banned {member.name}: {reason}!')

@commands.command(name='unban', description='Unbans a user from the server.')
async def unban(self, ctx: discord.ApplicationContext, member: discord.Member, reason: str):
    await member.unban(reason=reason)
    await ctx.respond(f'Unbanned {member.name}: {reason}!')

@commands.command(name='timeout', description='Timeout for a user from the server.')
async def timeout(self, ctx: discord.ApplicationContext, member: discord.Member, duration: int,  reason: str):
    if duration >= 0:
        await ctx.respond(f'Please choose a time greater than 0.')
        await asyncio.sleep(duration)
    duration = timedelta(minutes=duration)
    await member.timeout_for(duration)
    await ctx.respond(f'{member.name} timed out for {duration} minutes. Reason : {reason}!')

def setup(bot):
bot.add_cog(Moderation(bot))``

sage tendon
#

what's your pycord version first of all

sage tendon
granite python
#

2.6.1

granite python
#

Traceback (most recent call last): File "C:\Users\pbris\PycharmProjects\PythonProject\zeusbot2.0\.venv\Lib\site-packages\discord\cog.py", line 796, in _load_from_module_spec setup(self) File "C:\Users\pbris\PycharmProjects\PythonProject\zeusbot2.0\cogs\Moderation.py", line 37, in setup bot.add_cog(Moderation(bot)) File "C:\Users\pbris\PycharmProjects\PythonProject\zeusbot2.0\.venv\Lib\site-packages\discord\cog.py", line 666, in add_cog cog = cog._inject(self) ^^^^^^^^^^^^^^^^^ File "C:\Users\pbris\PycharmProjects\PythonProject\zeusbot2.0\.venv\Lib\site-packages\discord\cog.py", line 574, in _inject raise e File "C:\Users\pbris\PycharmProjects\PythonProject\zeusbot2.0\.venv\Lib\site-packages\discord\cog.py", line 568, in _inject bot.add_command(command) ^^^^^^^^^^^^^^^

sage tendon
#

uninstall and reinstall pycord

granite python
#

Can do, 1 moment

#

Done

sage tendon
#

does it work?

granite python
#

Still recieving same error...

#

The commands all worked prior to moving them to a cog so that's where I am lost

sage tendon
#

are you using discord.Bot in your bot definition?

granite python
#

Yes

sage tendon
#

hm

#

oh you need to use @discord.slash_command for slash commands

granite python
#

bot = discord.Bot(debug_guilds=[-])

sage tendon
#

i think commands.command is only prefix

granite python
#

I have a guild just removed for this

sage tendon
#

?

granite python
#

Referring to the debug_guilds sorry

granite python
#

You rock man! That did it, thank you so much!

round heart
#

Can I make .utils.get() case insensitive?

hexed herald
#

is it possible to return something that was written in modal to another view?

#

like
View A -> button triggers Modal -> user types in modal -> Modal returns to View A

frail basin
#
modal = MyModal()
await interaction.response.send_modal(modal)
await modal.wait()
print(modal.children[0].value)
#

Something like that

hexed herald
#

ty, I'll try it

little cobalt
hexed herald
#

yeah, I did a await interaction.response.defer()

little cobalt
hexed herald
#

do I have to send an message?

#

I thought I could get away with an defer

little cobalt
#

You have to send a message

hexed herald
#

dang it, I'll add an message to it

little cobalt
#

Just do a Hidden message

little cobalt
lapis dock
hexed herald
little cobalt
silk spire
eternal kite
#

is it possible to have two subcommands with the same name but different command group?

lapis dock
#

/hello world
/goodbye world
Do you mean like this?

eternal kite
#

and also /world /hello world

lapis dock
#

Yes to both.
You just can't have
/hello AND /hello world

eternal kite
#

but how should i call them manually if both functions have the same name?

lapis dock
#

What do you mean?

eternal kite
#

if for some reason i need to call any of the function individually how should i do it

lapis dock
#

Name the functions different things and do name="buy" in the decorator

sage tendon
#

what even are you doing inside of the commands lmao

eternal kite
#

game shop and trading market

sage tendon
#

what even is _import_

eternal kite
sage tendon
#

yea duh but what does it do

eternal kite
#

same as typing import slash at the top of your file

sage tendon
#

why aren't you importing it normally tho

eternal kite
#

fancy wovtp_creepysmile

sage tendon
#

ah yes

round heart
echo wraith
#

Is it possible to listen to audit log event creation ?

lofty parcel
#

Afaik yes?

#

.rtfm on_audit

sly karmaBOT
#

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

rugged lodgeBOT
echo wraith
#

Yes

#

thx

lofty parcel
granite python
#

Anyone have any suggestions on a library to use for the time in a reminder system? I saw a few things from 2023 but I know things change, so it'd be greatly appreciated!:)

lapis dock
#

python-dateutil for datetime input
time-str for duration/timedelta input
These are ones that I am currently using but I have not done a lot of extensive testing yet. Overall datetime input on discord is hard. 2023 stuff is not that outdated either, no major changes in date formats so no reason to change things that work

granite python
#

Awesome, much appreciated!

round heart
errant trout
#

still abysmal discord straight up wont release their built-in datetime picker

lapis dock
#

Yeah, at this point I might prioritize that over modal improvements

#

Especially because I just realized that they have it built in to both PC and mobile already for event creation

sage tendon
#

and message search

real glacier
#

hi, why there is no guild in user object?
error: role = discord.utils.get(user.guild.roles, id=....) ^^^^^ AttributeError: 'User' object has no attribute 'guild'

async def on_raw_reaction_add(payload: discord.RawReactionActionEvent):
    channel = Fake_Pompoki.get_channel(....)
    user = Fake_Pompoki.get_user(payload.user_id)
    guild = Fake_Pompoki.get_guild(payload.guild_id)
    if payload.channel_id == channel.id:
        if str(payload.emoji) == ":pmpm_hold_dice:":
            role = discord.utils.get(user.guild.roles, id=....)
            print(role)```
silk spire
#

get_user

#

You already have the guild, so just use guild.roles or, better yet, guild.get_role(roleid)

#

But payload.member is also available for reaction add

nocturne jewel
#

discord is having any issue with connection?

lapis dock
#

You dont show enough of the error.
Although if you are on the master branch (dev branch) we removed support for python 3.8, not sure if that is related

nocturne jewel
sage tendon
#

I'd first check if your vps has conn problems

#

seems more likely

#

also, i really wouldnt voluntarily use EOL python versions

lofty parcel
tidal pecan
#

I'm trying to get a good answer about whether discord.Message.id for any given message is Universally Unique. I've read about "snowflakes" and all that, but according to Discord that's supposed to be a string because the number is too big to put into an int, but in py-cord that value is factually an int. I flat-out don't believe that, in 2025, there aren't more messages in all of Discord than there are possible values in an int!

Apart from that, lots of posts on Reddit and StackOverflow insist that each individual message in every DM and in every Guild/Channel/Thread has that ID number which is allegedly a Universally Unique Identifier in spite of fitting inside a simple int.

So while working on a bot with commands to set up event listeners, I need to ensure that the message ID stored in my database is going to catch the message which was specified from the slash-command. What am I missing here, about uniquely identifying one special message, where my brain wants me to store all of the Guild/Channel/Thread/Message snowflakes and then using that whole chain of IDs to locate the message I'm looking for?

sage tendon
#

I dont see why a long number wouldn't fit inside an int though

errant trout
#

just one minor thing to keep in mind: if you start a thread from an existing message, the thread will have the same ID as the message

sage tendon
#

there isn't a universal "int size" really

#

but generally IDs are often treated as strings because they are long and you dont do math with them

errant trout
#

they explain it on docs

Internally, Discord stores IDs as integer snowflakes. When we serialize IDs to JSON, we transform bigints into strings. Given that all Discord IDs are snowflakes, you should always expect a string.
...
Because Snowflake IDs are up to 64 bits in size (e.g. a uint64), they are always returned as strings in the HTTP API to prevent integer overflows in some languages.

tidal pecan
#

Ah, and the int in Python3 is not limited to word-size. I just finally thought to look that part up. Thanks, @errant trout and @sage tendon

errant trout
#

allgood

round heart
sage tendon
#

๐Ÿค“

tidal pecan
buoyant eagle
#

is it possible to make the bot send a message when its getting off, and on?

sage tendon
#

off is dificult, on of course

buoyant eagle
#

i need to use discord.on_disconnect()?

sage tendon
#

no because then you are already disconnected lol

little cobalt
#

@buoyant eagle

buoyant eagle
sage tendon
#

i mean ig you could send a raw request

#

maybe

buoyant eagle
sage tendon
#

i mean you can do it there, but youll have to do it a different way than just channel.send because you dont have a bot anymore really

buoyant eagle
#

so webhhok is the answer?

echo wraith
buoyant eagle
#

ok thanks

round heart
#

Maybe on_disconnect, you could reconnect back to send the message Troll

tidal pecan
#

I have to assume that you're shutting down in response to a slash-command. If you were hoping to send messages in the event of a fatal error/exception then I don't think there's any recourse. Otherwise, just put your broadcast announcement in the slash-command before the disconnect or shutdown call.

echo wraith
#

I mean

#

You could wrap your process with another one

#

Or have a global catch

#

Or idk

#

But pycord should almost never crash entirely

tidal pecan
# echo wraith But pycord should almost never crash entirely

My point is that if the bot is disconnecting for reasons you can't or didn't account for ahead of time, you're boned. If the bot is just going down because you deliberately brought it down for a restart, then all you have to do is add your message broadcast one line ahead of your shutdown call XD

echo wraith
#

That's what I meant

tidal pecan
#

Fair enough. I just wasn't sure what the context of the disconnect was, so I specified the case where my idea wouldn't work.

surreal flicker
#

Hello, I have a bot that is offline after a certain time, but the script is running. However, I noticed that the processor is being used to the maximum (see image). This has been bothering me for over a year and I still can't figure out where the problem is...can someone help me?

If it helps, here is my requirements.txt:
py-cord==2.6.1
captcha
aiomysql
cryptography

I would appreciate any help! โค๏ธ

sage tendon
#

how many cores does the VPS have

#

because with percentages above 100%, it means that the % is relative to a single core being used
e.g. if one core is used to 100% it would show 100%
if 2/4 cores are used to 100% each it would show 200%

and while that is the case i still think constant core usage is still not good lol
what does your bot do?

surreal flicker
surreal flicker
sage tendon
#

that shouldnt be possible given it shows more than 100% cpu usage lolw

surreal flicker
surreal flicker
sage tendon
#

might be time for a better VPS then if its at its limit lol

#

do you regularly run some heavier actions tho

surreal flicker
#

or it shouldn't be

surreal flicker
frail basin
#

Is it a VPS even? 68.5MB of used space seens suspiciously low

raw beacon
#

probably just a docker container with pterodactyl

surreal flicker
#

yes

frail basin
#

Thats what im thinking

#

You can have a buffer on ptero

#

Which is why it goes above 100

tidal pecan
#

I'm not sure if it's bad form to ask a separate question while the last one is still unresolved?

surreal flicker
frail basin
#

Meaning that in reality, instead of 100%, you get 110%, 120% etc

surreal flicker
#

Ahh, got it

tidal pecan
#

On the current topic, I think it's worth mentioning that I run a real hardware debian box with a lAMP stack hosting 5 domains with multiple subdomains each, multiple python versions, firewall, SSH service, MySQL with 8 or 9 schemas and plenty of data each, and that only uses about 259MB of system RAM. So I think if you're running a VPS with a python script and consuming 300+MB of RAM, you're either caching a lot of stuff you shouldn't be or else that display about CPU/RAM/Storage is lying to you.

lapis dock
sage tendon
#

300mb really isnt that much for a discord bot

#

especially if its in 700 servers

#

my single server bot already uses 75mb

tidal pecan
# sage tendon 300mb really isnt that much for a discord bot

Fair enough. Just seems insanely high, even with caching like member-intents, when everything that Discord actually transmits is a UTF-8 encoded string.

Is it generally OK for folks to ask another question when there's one currently under discussion? I'm struggling with an issue that I can find nothing about via websearch and Discord search in this channel.

sage tendon
#

sure

surreal flicker
lapis dock
tidal pecan
lapis dock
#

Is your bot actually slow during times?

tidal pecan
# lapis dock If you are worried you can open a thread instead

I just don't want to get off on the wrong foot with folks here XD

So when my bot is joined to any given Guild, Discord automagically creates a Role specially for that bot. The role's name can be changed and the bot can be added to additional roles, but those additional roles can also be removed. So what I want to be able to do is get a handle directly on that one super-special bot role. I just can't figure out how.

surreal flicker
surreal flicker
lapis dock
lapis dock
tidal pecan
surreal flicker
sage tendon
#

did you check the logs

lapis dock
sage tendon
# tidal pecan Handle is just jargon. I tend to mix and match programming terms because I prog...

You can check whether a role is a bot role via https://docs.pycord.dev/en/stable/api/models.html#discord.Role.is_bot_managed
and if a role is bot managed and your bot has it, that has to be your bot's role

rugged lodgeBOT
lapis dock
#

And

lapis dock
#

Ah toothy was faster ๐Ÿ˜…

sage tendon
#

is the ingration ID == bot user ID?

#

if yes wolfy's way is faster

tidal pecan
# rugged lodge

Hey now, I tried to RTFM. I just didn't get out my fine-toothed beard comb and go over all the methods available on all the class instances involved XD

sage tendon
#

reading the docs involves that kind of stuff :)

lapis dock
#

Nah, rtfm isn't an insult here it is just the name of the docs command

#

-# at least most of the time

tidal pecan
lapis dock
#

Your good, you have been very enjoyable to work with XD

surreal flicker
sage tendon
surreal flicker
#

Oh sorry

#

I don't have access to them, but I'll implement logging and see what happens.

sage tendon
#

you cant see the logs of your own bot?

surreal flicker
#

Or maybe I'll just contact the support

surreal flicker
sage tendon
#

or vps

#

tf

lapis dock
#

Exceptions should be visible in the console

surreal flicker
#

Idk

lapis dock
#

If you can't even see print statements it might be time to switch hosts

surreal flicker
#

Yeah...well, I'll see what can I do

#

Thank you very much!

little cobalt
#

How would I log events, commands etc.? I saw some use logging but that one catches every event from the bot

sage tendon
#

i do my own logging tbfh

tidal pecan
little cobalt
sage tendon
#

.... what

#

oh you mean to a file

#

nah pm2 handles that

lapis dock
sage tendon
#

(info)

#

i think

frail basin
#

It opens a websocket between your browser and the docker container

#

So if you arent there to witness the crash, you wont have logs.

#

(unless you implement it yourself)

#

Some hosts went around this by forking pterodactyl and adding their own crash detection

lapis dock
#

It's been a long time since I have used pterodactyl, I assume it is easy to setup file based logging though

frail basin
#

Not as a client

#

You have to modify the egg (the "wrapper" around the docker image)

#

Which can only be done from the admin side

lapis dock
#

Hmm, well that is unfortunate

round heart
#

Adding nothing to the earlier conversation, my bot is using 422M

tidal pecan
#

Any way to get py-cord to shut down gracefully when using the run/debug-run buttons and the stop button in PyCharm? I'm seeing a couple of different options other than bot.run (which I use now), but I'm not sure I really need all the overhead of my own event loop. I've tried putting bot.close() immediately after bot.run (and I verified that this code is executing by adding an additional console-out print after close()), so it fires as soon as the blocking method exits, but I still get a bunch of runtime exceptions every time I hit that stop button.

round heart
#

I don't get the runtime exceptions, it usually just hangs for a bit. I just press stop (or CTRL-C, in my prod environment) twice

tidal pecan
#
    # bot = discord.Bot(intents=intents)
    bot.run( DISBOT_APP_TOKEN )
    asyncio.run( bot.close() )
    print('bot run done')```

```D:\Development\Projects\voidCaster\Discord\Bots\serverHelper\venv\Scripts\python.exe D:\Development\Projects\voidCaster\Discord\Bots\serverHelper\bot.py 
We have logged in as DEV - Server Helper Bot
bot run done
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x0000012E295DBF70>
Traceback (most recent call last):
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python39_64\lib\asyncio\proactor_events.py", line 116, in __del__
    self.close()
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python39_64\lib\asyncio\proactor_events.py", line 108, in close
    self._loop.call_soon(self._call_connection_lost, None)
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python39_64\lib\asyncio\base_events.py", line 751, in call_soon
    self._check_closed()
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python39_64\lib\asyncio\base_events.py", line 515, in _check_closed
    raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x0000012E295DBF70>
Traceback (most recent call last):
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python39_64\lib\asyncio\proactor_events.py", line 116, in __del__
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python39_64\lib\asyncio\proactor_events.py", line 108, in close
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python39_64\lib\asyncio\base_events.py", line 751, in call_soon
  File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python39_64\lib\asyncio\base_events.py", line 515, in _check_closed
RuntimeError: Event loop is closed

Process finished with exit code 0```
#

Same exceptions both with and without bot.close(), also with and without COGs loaded. It's a Win10 system with PyCharm Community.

sage tendon
#

i mean idk what to say lmao, i dont get those

#

you are using VISUAL STUDIO FOR PYTHON?

tidal pecan
# sage tendon you are using VISUAL STUDIO FOR PYTHON?

I use Visual Studio for work. Mostly C# and C++. I don't recall if I had to manually select to add in Python, but I don't use VS for anything but C# and C++. Frankly, I don't even use it for that, unless you count compiling with it after writing my code in EditPad XD

#

SAME WITH PYCHARM FRANKLY

sage tendon
#

cursed

#

but yea unless you want those gone you really dont need to do anything
maybe pycharm ignores console output when shutting down except for the final line

#

oh wait you do use pycharm

tidal pecan
#

Meh. I kind of do want them gone. I've been programming long enough that every time I see Traceback I'm OCD to read it all. Wastes quite a bit of time when I'm tinkering with function signatures and auto-fill features in this particular bot.

sage tendon
#

why is your python exe in a visual studio folder

tidal pecan
# sage tendon oh wait you do use pycharm

The exe is in a venv directory. It's the first line of the Traceback. I don't know why it's falling back to the original installation. Never got into studying the guts of Python execution lifecycle.

sage tendon
#

cursed

#

id just fresh reinstall python atp lol

tidal pecan
#

You sure it's not an issue with Python on Windows or even with PyCharm Community as opposed to wtf-ever they call their licensed version?

#

If I had my way I'd be using that sexy SSH-runtime feature to debug in the actual linux environment where the production bot will finally sit, but I can't have my way because I don't have the cheddar for that sweet sweet license.

sage tendon
#

lol

#

if youre in a uni you can get pycharm professional for free btw

tidal pecan
modern trail
#

Is it not possible to send a paginator to a channel outside the context of a slashcommand? I tried doing something like this:

await some_channel.send(view=paginator)

but nothing is sent. I added a content="test" to be sure it's not an issue with something else and it happily sends "test" to the channel, still with no paginator. The same paginator works fine when sent with await paginator.respond(ctx.interaction)

sage tendon
#

your uni doesnt need to do anything you just need to have a uni mail i think

tidal pecan
modern trail
#

yes, i have a job scheduled that would post the paginator to a channel, without any user interaction involved. So there is no ctx for me to use

#

paginator.send expects a command invocation context

#

i thought what i did above might work because the paginator class inherits from discord.ui.View

#

but alas

tidal pecan
#

Did you try constructing a discord.ApplicationContext from the ground up?

modern trail
#

i haven't, i considered it, but figured that would be a very hacky thing to do, so it wasn't the first thing i tried. assuming it's even a reasonable thing to do

tidal pecan
sage tendon
#

i mean you send the paginator in response to SOMETHING right?

modern trail
sage tendon
#

when do you then

modern trail
#

i have a scheduler that sleeps in the background and sends it at the scheduled time. no user interaction involved. I just want to have my bot post a leaderboard to a channel every friday at 4pm automatically, without me having to do the command to do it manually

sage tendon
#

okay but afaik paginators are limited to the invoking user anyway

modern trail
#

that's the impression i got, but i don't understand why. Seems unnecessary to limit paginators that way

sage tendon
#

because it's 99% of their use case lol

#

you dont want other people interfering with how you navigate a menu

modern trail
#

well nothing is stopping you from allowing that in the normal use case

sage tendon
#

Shrug_3 i mean either you write your own custom paginator or you subclass it and change what you need to change
both might be somewhat complex tho

lapis dock
#

Pretty sure you can change that

modern trail
#

change what?

lapis dock
#

author_check defaults to true

sage tendon
#

oh yea you're right, in Paginator.edit, user is optional

#

hm

lapis dock
#

You can set it to false

sage tendon
#

yea okay but that doesnt fix the whole ctx being required issue lol

modern trail
#

yes, and that's how i have it. That's already how my users interact with leaderboards

sage tendon
#

ahh

lapis dock
#

Ok, maybe I did not read the whole issue... :3

modern trail
#

now i want to avoid having to post the leaderboard every friday at 4 manually

#

i figured i'd simply automate the invocation of the command, but then i realized paginators only expect a user interaction context or w/e

#

which seems crazy to me

sage tendon
#

niche use cases will have problems Shrug_3

modern trail
#

i'm surprised this is even considered niche. surely i can't be the first person that wants to automate the post of a paginator

sage tendon
#

first one i know of
:>

#

i mean the first alternative i could think of is just making a message with a "show leaderboard" button that everyone can click on when they want to, and always get the current leaderboard
but i think thats not what you want exactly

lapis dock
#

Tbh the person who made ext.pages had an abrupt disconnection from the Pycord community. It has been attempted to rework but is hard to do without breaking changes

sage tendon
#

gotta love the "this was made by one crazy guy who left and now its rendered unmaintainable"

#

it happens so often

modern trail
#

yea that is not ideal. I'm really surprised my idea didn't work. I figured it would work like a view just like any other view. granted i don't know much about views

lapis dock
#

It should not be to hard to subclass and override the send method as a workaround

sage tendon
#

yea i thought of that too but idk how much of the internals of the paginator rely on ctx which would make removing it hard

#

but thats really the only easy thing you can try