#Basic Pycord Help

1 messages · Page 79 of 1

echo wraith
#

Yeah I fixed that I think

#

somewhere

#

sometime

sage tendon
#

first of all you should replace the permission check with @discord.default_permissions(administrator=True)

#

and guild_only is deprecated too

echo wraith
errant trout
#

oh that'd do it

#

figured it was being run in user context

sharp pawn
#

I've tried a couple of your suggestions but now the commands are beeing refreshed, tho i noticed one more thing, as u can see from the screen it shows that it has 1 mutual guild, but that one is my private server, so it's not showing the server where i added the bot

sage tendon
#

restart your client

errant trout
#

sounds like you didn't add the bot

#

make sure you use the bot scope in your invite url

sharp pawn
errant trout
#

allgood

shadow sigil
#

is it possible to make a command that requires an argument when used in the bot's dms but gives a modal instead when used in a server

echo wraith
#

but you can make it open a modal only in dms

rugged wing
#

I haven't touched my bot code in a while, I have a question about Cogs

I have one cog and there is a function outside of my class called setup(bot)
I thought I remember reading that this was required by Pycord to setup the Cog
But as I'm looking at the Cog documentation, I'm not seeing reference to this being necessary or even shown
Has this changed?

errant trout
#

when you create a cog as its own file, pycord loads it via load_extension

rugged wing
#

I am seeing that now, thank you!

shadow sigil
#

is there a way to tell whether commands aren't showing up because i'm being rate limited or because i'm doing something else wrong

#

ok, i'm doing something wrong i guess

rugged wing
#

Any idea why Im not able to use self.bot.get_channel(channel_id) from within a Cog when outside of the cog it returns the channel just fine? I'm assuming it's some misunderstanding by me about the context of the bot within the Cog?

rugged wing
#

I'm trying to grab it in one of the class functions outside of __init__

errant trout
#

or in your commands

rugged wing
#

It's in one of my commands which is a loop

errant trout
#

mmmm could you show the code

errant trout
shadow sigil
#

thanks i've already done that

rugged wing
# errant trout mmmm could you show the code
class Test_Cog(commands.Cog): 
   def __init__(self, bot):                                                                             
        self.bot = bot                                                                                  
        self.rolecheck.start()                                                                         
        self.DEV_CHANNEL_ID = int(os.getenv('PERSONAL_DEV_CHANNEL'))
                                                                                                        
        # Testing, get_channel returns None                                                                    
        # Confirmed that channel id is as expected                                                         
        channel = bot.get_channel(os.getenv('PERSONAL_DEV_CHANNEL'))                                    
        print(channel)                                             

    #@tasks.loop(time=datetime.time(hour=17, minute=29))                                                
    @tasks.loop(seconds=10.0)                                                                           
    async def rolecheck(self):                                                                          
        update_users = get_misranked_users()                                                            
        output_message = self.format_users(update_users)                                                
                                                                                                        
        # Testing, get_channel returns None                                                                    
        # Confirmed that channel id is as expected                                                         
        print(self.DEV_CHANNEL_ID)                                                                      
        channel = self.bot.get_channel(self.DEV_CHANNEL_ID)                                             
        print(channel)                                                                                  
        #await channel.send(output_message)                                                                                                         
def setup(bot):
    bot.add_cog(TestCog(bot))
sly karmaBOT
# rugged wing ```py class Test_Cog(commands.Cog): def __init__(self, bot): ...

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

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

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

rugged wing
#

Oooh that's interesting, thank you very much I will try it!

#

Seems like it works now, something like this?:

channel = self.bot.get_channel(self.DEV_CHANNEL_ID)
if channel is None:
  channel = await self.bot.fetch_channel(self.DEV_CHANNEL_ID)
errant trout
rugged wing
#

Ahhh this makes sense

#

So then there's no reason to attempt get_x within cogs?

errant trout
#

only inside __init__ / any function that would run before bot.run

#

it's still fine inside command code, task loops etc

rugged wing
#

Oh that's true

#

because if the bot stays online it will likely be cached

errant trout
#

my personal preference is you define property inside your cog instead py @property def channel(self): return self.bot.get_channel(my_id)then you can access self.channel in your code, for example

#

@property basically makes an attribute that calls that function every time you access it

rugged wing
#

Oh very neat

#

it would still have to attempt to fetch though, right?
So it would have to be async?

rugged wing
#

uhh, don't you have to await the fetch?

errant trout
#

well you do, but moreso i mean you don't need to fetch at all

#

for small bots you can pretty safely assume you have all channels cached

rugged wing
#

But isn't that the issue I'm already running into, where it isn't cached?

errant trout
#

because you were running it in __init__ no?

rugged wing
#

No, it was ouside __init__ in my loop

#

I had it both in __init__ and outside for testing

errant trout
#

well you're also starting the task inside init

rugged wing
#

Ah

#

Can I just start the task in setup?

errant trout
#

some advice from the task docs is you wait_until_ready

rugged wing
#

I did see that in the before_loop, so that would ensure my channels are cached?

errant trout
#

yes because the task won't start until the bot fires the on_ready event

rugged wing
#

Ok that makes sense

errant trout
#

wait_until_ready is useful if you need to ever guarantee the bot has fully started first

rugged wing
#

So then I can leave starting the task in __init__

errant trout
#

that's pretty standard yea

rugged wing
#

Got it

#

Makes sense, thank you!

errant trout
#

allgood

rugged wing
#

Very nice, that worked great

shadow sigil
#

how can I add/use the same command group in multiple cogs?

echo wraith
shadow sigil
rugged wing
#

If I have the name of an emoji is there an easy way to programmatically grab the id?

errant trout
rugged wing
shadow sigil
#

is there something specific you gotta do to access the value of a modal input field?
my attempts are just giving None

echo wraith
shadow sigil
# echo wraith could you share a little more on how you're doing that ?

class SplashModal(discord.ui.Modal):
    """A modal for submitting a splash."""

    def __init__(
        self,
        *args: tuple[discord.ui.InputText],
        **kwargs: dict[str, str | float | None],
    ) -> None:
        """Initialize the modal."""
        super().__init__(*args, title="Submit Splash", **kwargs)

        self.add_item(
            discord.ui.InputText(
                label="Splash",
                style=discord.InputTextStyle.short,
                placeholder="Enter splash text",
                min_length=1,
                max_length=80,
            )
        )
``````py
    splash_modal = self.SplashModal()
    await ctx.send_modal(splash_modal)

    if not await splash_modal.wait():
        await ctx.respond("splash submission cancelled.", ephemeral=True)
        return

    splash_text = splash_modal.children[0].value
#

wait i may be wrong

#

misread my logs

#

well, different issue: the modal doesn't go away when submitted, and the cancel message doesn't appear when cancelling

echo wraith
#

That's just a timeout iirc

errant trout
#

and you need to respond to a modal submission

rugged lodgeBOT
#

Here's the modal dialogs example.

errant trout
#

this includes an example for callback

shadow sigil
#

...so you're required to send a message for the modal to close?

loud kayak
#

how can i get a slash command group object by name and add a new command to it

warm monolith
errant trout
warm monolith
#

Need the tag for my feature.

errant trout
#

until then, you can get the raw data through await bot.http.get_user

warm monolith
#

don't want to call this again for every command

errant trout
#

GuraShrug you can always build the feature yourself

warm monolith
#

I think I don't know enough about py-cord for that

sage tendon
#

then wait until its part of the lib

shadow sigil
#

is it fine for a modal to just never timeout?

errant trout
#

you can set timeout=None

shadow sigil
#

ya but is it fine to do so

errant trout
#

if it wasn't fine we wouldn't let you do that

#

(tl;dr yes)

#

maybe if you have hundreds of modals at once it would theoretically be a memory bloat but that's a pretty peculiar scenario

shadow sigil
#

like i mean, you can set the timeout to none on http requests, yet that's still considered a bad idea

errant trout
#

well modals aren't http requests

shadow sigil
errant trout
#

like a hundred users triggered modals at the same time

shadow sigil
#

hmm

errant trout
#

(quite frankly modals/views in v2 aren't designed well internally, but it's not gonna blow up your pc or anything)

shadow sigil
warm monolith
#

Was that it?

errant trout
#

that should be good enough if you just want it cached

warm monolith
#

okay than pr?

errant trout
#

well an actual PR will have more depth

#

i'm saying the code you've done there should be enough to have it available on your member cache without needing to fetch

warm monolith
#

But can I install this branch locally?

errant trout
#

oh yeah

#

something like pip install git+https://github.com/bastigamedc/pycord.git@primary-guild

warm monolith
#

Okay, I'll try it right away

#

I also use the containers, is it possible to use both?

errant trout
#

Yes because cv2 is on master now

warm monolith
#

oh nice

#

Since when?

errant trout
#

A few days ago? Maybe a week I forgot

warm monolith
#

Why no #library-updates announcement

errant trout
#

Because that's master, not a release

#

2.7.... soon, sometime

shadow sigil
#

is this cursed

await (await ctx.author.create_dm()).send(f"submitted splash: {splash_text}")
echo wraith
#

You should probably not make it a oneliner

shadow sigil
#

oh okay

#

i tried ctx.author.dm_channel.send initially and that gave me an error for none type

errant trout
#

it's because User.send calls create_dm if it isn't cached already

shadow sigil
#

fair enough

#

if i had a shot for every time god damn time i forgot to await a coroutine
idie

echo wraith
shadow sigil
#

before or after i run the code

#

cause it is giving me these

RuntimeWarning: coroutine 'Interaction.respond' was never awaited
  splash_interaction.respond("submitting splash", ephemeral=True)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
echo wraith
#

maybe by some logging

#

or by vscode or your ide

errant trout
#

that's the default coroutine warning

echo wraith
#

yeah no wait

#

the asycio debug ones are different iirc

frosty trellis
#

Hi, I'm giving bot.get_message() a valid message id, but it doesnt return a message

#

the bot has access to the channel with the message and has all necessary privileges

frosty trellis
errant trout
#

yes

frosty trellis
#

alright, thanks for the help

errant trout
#

in such a case you have to await channel.fetch_message(id) if you need to retrieve data from the message

#

if you only want to edit/delete, you can use channel.get_partial_message

vital bramble
#

Hi, does anybody know if it is possible to get the Join Method of a member, as shown in the "Members" tab of a server?

echo wraith
vital bramble
#

I was afraid of that, thanks anyway 🙂

sage tendon
#

you can use a workaround to get the used invite tho @vital bramble

vital bramble
#

Yeah with cashing the invites and checking which use has gone up, right? I don't really like that approach and it's also not really that important for me anyways.

echo wraith
#

this is not guaranteed to work at any time for any reaso but it exists

vital bramble
#

nice, thanks!

viral plover
#
def is_streaming(member: discord.Member) -> bool:
    """Check if a member is streaming on Twitch/YouTube. Must have 'Dino Hub' in stream title..
    Args:
        member (discord.Member): The member to check.
    Returns:
        bool: True if the member is streaming, False otherwise.
    """
    if not member.activities:
        return False

    for activity in member.activities:
        if isinstance(activity, discord.Streaming):
            if activity.platform in ['twitch', 'youtube']:
                if activity.name and 'dino hub' in activity.name.lower():
                    return True
#

Does this make sense for checking a user's status if they are streaming on twitch/YT and they have a specific keywod, dino hub in the title?

errant trout
#

did a check on my members, it returns Twitch and YouTube

#

could just do activity.platform and activity.platform.lower() in ...

errant trout
#

for your bot? check dev portal

#

can't help ya then apensive

eternal kite
#

how many servers do my bot have to be in to require sharding?

lofty parcel
#

It's not smart to say that here lol

lofty parcel
#

It's when discord tells you to shard

#

You should probably start sharding before

eternal kite
lofty parcel
#

You will be forced

#

Otherwise it won't let you connect

#

Against tos? There are staff here and people close to it in this server?

#

How is what working

#

For what reason

#

You won't get help on how to build a self bot

#

Well you're literally asking for help

#

"How to get user token" -> to put in a self bot -> to break the tos

#

You're not very smart are you

#

Doing it for the fun and giggles doesnt make it allowed

#

Using your user token outside the client itself is against the tos

#

There's nothing to study or practice about self bots.

#

So drop it.

#

You won't receive help about self bots here.

#

So stop pushing it.

#

You dont seem to understand that using your user token outside the client is against the ToS. You won't just funnily get your user token to look at it.

#

Again. Drop it.

#

The term platform abuse refers to activities that disrupt or alter the experience of Discord users. Sending unsolicited bulk messages or interactions (or spam) is one of the most common ways the user experience is disrupted. Spam can be sent by automated accounts designed for this purpose (spambots), normal user accounts that manually execute spammy actions, as well as by user accounts modified to perform automated actions (self-bots). Making modifications to the Discord client for the purpose of spam or any other reason is not allowed under this policy.

#

Oh wow!! They said user accounts can't be automated!! What would that mean? That you can't use your user token to perform actions on a code? Maybe!!

unkempt cipher
#

-ban 958077120612032612 Intend to selfbot -FO

lofty vaultBOT
#

🔨 Banned kartoshka_ma indefinitely

little cobalt
unkempt cipher
#

wurde schon

little cobalt
#

oh nvm xd

frail basin
#

Can this ever actually be None?

#

MessageReference class

sage tendon
#

I mean it says it can't

unkempt cipher
#

its null for channel follow add messages and a few other types

#

so yes

silk spire
round heart
#
WARNING:discord.gateway:Shard ID None has stopped responding to the gateway. Closing and restarting.
Killed

I can't tell if this is the product of the bot itself getting OOM'd, or the gateway no longer responding and something in pycord (or lower-level dpy) churning until death

silk spire
#

isn't that a discord thing where is wants you to reconnect or something

torn barn
#

yes

round heart
#

So is there a way to have pycord automatically do that?

silk spire
#

Does it not? "closing and restarting"

jolly valley
#

@round heart I've been running into something similar which is why I just joined this server. Are you experiencing bad states with your bot?

echo wraith
#

-remindme 30min bad gateway states ?

lofty vaultBOT
#

Set a reminder in 30 minutes from now (<t:1754422585:f>)
View reminders with the reminders command

jolly valley
#

also.. out of curiosity is py-cord a true wrapper or does it implement discord ? if so what version of discord?

Apologies for dupe questions if these have been asked before

echo wraith
jolly valley
#

ah ok that makes sense. Yes that answers my question thnx @echo wraith

echo wraith
#

nw

#

Imma take a look at your issue later

jolly valley
#

awesome, I can provide more info just lmk

torn barn
echo wraith
#

oh k

#

-delreminder -a

lofty vaultBOT
#

Cleared 1 reminders

echo wraith
sly karmaBOT
echo wraith
#

could you try with this ?

jolly valley
#

yee, gonna try now

echo wraith
#

perfect

jolly valley
#

it worked 😭 i could cry irl

#

thanks ya'll. you guys rock

#

been debugging this for a while now and couldn't find a way to replicate it, but it's behaving as it should from what I see. I'll drop in here again if I encounter any issues with it

echo wraith
#

sure no problem

round heart
round heart
old lantern
echo wraith
old lantern
#

And yet it's been closed and marked as completed. I'll try to get the logs the next time it happens

#

Any reason why a @bot.command won't get registered? The (changed) bot's been running for a few hours already

echo wraith
sly karmaBOT
#
Error

Flag 'delete' is required and missing

old lantern
echo wraith
old lantern
rugged lodgeBOT
old lantern
wheat tiger
#

How did they manage to do this?

#

emoji on the left side of 2 text fields (or maybe one with \n)

#

also there is another accessor component (which is a button here)

echo wraith
wheat tiger
fresh sierra
wheat tiger
wheat tiger
#

a big image split in 4 parts and uploaded to bot

#

then merge these 4 in a text field side-by-side to text

errant trout
#

eh they can just wrap it into a function and call it a day, easy enough to generate

#

in terms of pokemon they can upload 500 x 4 to the bot and then split the other 500 across servers. but that bot was only a proof of concept used for CV2 demonstration and not one of the huge pokemon bots

silk spire
#

Discord doesn't recommend doing that btw

#

It was just for the showcase

vital bramble
#

Why don't modals reset their _stopped future when resending them? Is that a feature or a bug?

echo wraith
#

modals are such a mess...

vital bramble
#

So there is no deeper reason behind that design choice?

frail basin
vital bramble
#

I just don't want to break anything when I change it myself

vital bramble
lapis dock
#

Im not sure if it is intended to reuse a modal instance

vital bramble
#

Then why is it so difficult to copy them?

#

Because there are definitely use cases where reusing makes it a lot easier/is necessary

lapis dock
#

Yeah, I guess there is nothing stopping you from doing that

#

I guess it was just an oversight :/

vital bramble
#

Well, there IS the question of WHEN the future should be reset. When the modal is sent or maybe even before that (directly after receiving it?). Maybe that was the problem.
But I also think, that the modals in pycord are not designed to be reused, but they should be.

autumn gust
#

why is this code throwing a AttributeError: 'NoneType' object has no attribute 'value' error?

autumn gust
#

wait that's from multiple reboots

#
Ignoring exception in on_connect
Traceback (most recent call last):
  File "C:\Users\domin\AppData\Local\Programs\Python\Python313\Lib\site-packages\discord\client.py", line 412, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\domin\AppData\Local\Programs\Python\Python313\Lib\site-packages\discord\bot.py", line 1214, in on_connect
    await self.sync_commands()
  File "C:\Users\domin\AppData\Local\Programs\Python\Python313\Lib\site-packages\discord\bot.py", line 742, in sync_commands
    registered_commands = await self.register_commands(
                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        global_commands, method=method, force=force, delete_existing=delete_existing
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    )
    ^
  File "C:\Users\domin\AppData\Local\Programs\Python\Python313\Lib\site-packages\discord\bot.py", line 541, in register_commands
    desynced = await self.get_desynced_commands(
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        guild_id=guild_id, prefetched=prefetched_commands
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    )
    ^
  File "C:\Users\domin\AppData\Local\Programs\Python\Python313\Lib\site-packages\discord\bot.py", line 364, in get_desynced_commands
    elif _check_command(cmd, match):
         ~~~~~~~~~~~~~~^^^^^^^^^^^^
  File "C:\Users\domin\AppData\Local\Programs\Python\Python313\Lib\site-packages\discord\bot.py", line 278, in _check_command
    as_dict = cmd.to_dict()
  File "C:\Users\domin\AppData\Local\Programs\Python\Python313\Lib\site-packages\discord\commands\core.py", line 943, in to_dict
    "options": [o.to_dict() for o in self.options],
                ~~~~~~~~~^^
  File "C:\Users\domin\AppData\Local\Programs\Python\Python313\Lib\site-packages\discord\commands\options.py", line 358, in to_dict
    "type": self.input_type.value,
            ^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'value'
#

there we go

round heart
#

"many people sharing one physical body" ... I saw a movie about that once >.>

autumn gust
#

it's such a bad portrayal it's laughable

round heart
#

Oh, I'm talking about the one I found in my dad's room

errant trout
#

(i think)

autumn gust
#

I expected you to be talking about split, everyone brings it up

errant trout
#

i.e. either add a full @option decorator or just type it like user: discord.User

lapis dock
#

Defi...

round heart
#

😬 Sorry, I'm making an adult joke.

autumn gust
#

ah, I see.

round heart
autumn gust
#

it's apparently entertaining just, not very good rep for did

wheat tiger
errant trout
#

well it does as it's designed, but it was something made over an hour or so in a ddevs event stream and only covers the original pokedex

errant trout
#

ah ic www

wheat tiger
#

they were all yapping

round heart
#

It was interesting watching it get built. But sucks they had to be hacky with the images... should've been a learning moment that they should add a large image element on the left.

errant trout
#

their reasoning is that they're giving users control over vertical layout, while horizontal layout is strictly on discord

#

because they want to be somewhat vaguely consistent, though i can understand it being frustrating

wheat tiger
errant trout
#

fields is not happening, they're considering maybe some sort of second column but that's about it

wheat tiger
#

cuz on mobile it looks trash

errant trout
#

multiplatform is essentially the reason yeah

wheat tiger
#

when devs assume the gonna put 3 text fields horizontally, and later realize they all gonna be vertical and look more ugly on mobile 😔

errant trout
#

dv8 is pretty focused on accessibility and so the old methods embeds use is out of the question

wheat tiger
#

not a big deal cuz most of dyno's setting are on Dashboard

errant trout
#

eh they could get away with most of it

autumn gust
wheat tiger
errant trout
autumn gust
#

ah, thanks

errant trout
#

allgood

errant trout
wheat tiger
#

we should get some more things to tweak

errant trout
#

there will be

autumn gust
round heart
#

As long as they continually update cv2, it's fine. But I will probably continue using Embeds for more simplistic stuff.

errant trout
#

you just reference that in your code

autumn gust
#

ah

#

OH

errant trout
#

yeah LOL

autumn gust
#

oh my god I'm stupid I'm so sorry lmaoo

errant trout
#

no worries

autumn gust
#

turns out all of this was for nothing, footers can't ping anyway

errant trout
#

oh LOL

#

gotta use -# in description or something

#

/ whatever your last field is

wheat tiger
#

;-;

errant trout
#

what the hell, sure

autumn gust
#

so even that wouldn't work

errant trout
#

new field with name="", value="-# some text"

wheat tiger
autumn gust
wheat tiger
errant trout
errant trout
#

inline=False

autumn gust
#

and that's perfect, thanks!

errant trout
#

allgood

lofty parcel
wheat tiger
red cedar
#

for some reason my embed paginator is returning ‘this interaction failed’ after changing the page? pages work fine but getting that annoying little message for no reason. no error shown in console too. https://paste.centos.org/view/ce36c168

lofty parcel
sage tendon
#

do you know there's a prebuilt thing for pagination

lofty parcel
#

You're updating the cached message

#

And yeah, you could use the built in paginator

red cedar
#

thank you both ^

fluid lark
#

Why is it that when I run

vc = await ctx.author.voice.channel.connect()

The bot just hangs until it eventually times out?

lapis dock
#

It is probably due to a bug that has been fixed on the master branch

sly karmaBOT
#

pip install -U git+https://github.com/Pycord-Development/pycord
-# Note: The Master Branch May Have The Newest Features But It May Also Have More Bugs
The docs for the master branch: https://docs.pycord.dev/en/master/

fluid lark
lapis dock
#

Do you have any errors?

fluid lark
#

I'm not sure why

#

But I didn't change anything and it just started working

lapis dock
#

Might have been discord having temporary issues

fluid lark
#

Thank you

fresh sierra
#

-help

round heart
#

Is there a good way of deleting a small number of messages at once?
There's a channel.purge() but seems to require a check function.. is there any way to pass in a list of message ids or something?

fresh sierra
#

but you could use channel.delete_messages

rugged lodgeBOT
round heart
#

Ah-hah. Thank you

valid panther
#

Is there any way to detect messages from voice channels?

frail basin
valid panther
frail basin
#

Do you have the messages intent enabled?

sage tendon
#

does pycord even support that yet
or did that release after 2.7

torn barn
#

it does not need to support it

#

it’s just doing VoiceChannel.send

#

as long as VoiceChannel is a Messageable

valid panther
#

For example, if I want to create a command to delete text messages from either normal chat or voice channel chat, should I also include VoiceChannel?

sage tendon
#

see if voice channels appear that way

echo wraith
#

Pycord should already support that afaik

sage tendon
#

and you dont need required= if its true

valid panther
#

That work good

sage tendon
#

does it not show voice channels with just TextChannel?

errant trout
#

no because they aren't TextChannel

sage tendon
#

could you do it with channel_types?

vernal fiber
#

any ideas for features for my bot

round heart
#

Isn't there a generic class that includes TextChannel and VoiceChannel etc? 😐

sage tendon
#

Messageable ig?

#

but thats a bit broad

lapis dock
#

That would include category and more if I am not mistaken

echo wraith
#

You're right

silk spire
#

abc.VocalChannel is a thing iirc?

#

There is abc.Connectable

lapis dock
#

But they want text channel as well

errant trout
#

why is this even still being discussed, the answer is channel_types

lapis dock
#

I don't even know what the original question was XD

silk spire
#

same

echo wraith
#

Idem

upbeat remnant
#

Hey guys, I have something weird going on.
One of my cog's is constantly asking for the ctx parameter when calling the command in discord, but it's not happening for any of my other commands.

It's only happening with this one cog, and I'm not sure what I'm doing to cause it. Source added as image 'cause too poor for Nitro xD

sly karmaBOT
little cobalt
upbeat remnant
little cobalt
#

Something like that is pretty hard to read ;3

upbeat remnant
#

Yeah, sorry. Slow brain in the morning didn't think of that. Link provided 🙂

little cobalt
#

I see you import CommandGroups from a cog?

upbeat remnant
#

Yeah, I didn't know multicog was a thing, so I've been using a little hacky approach. Will be converting to multicog soon.

little cobalt
#

Py-cord got something for that

#

.tag multicog

sly karmaBOT
#

To split slash command groups across multiple cogs with Pycord, you can use pycord-multicog. Install it via pip install pycord-multicog. Initialize your bot by using from pycord.multicog import Bot. Define command groups in one cog and extend them in others using @subcommand. For example:

# Cog1.py
class Cog1(commands.Cog):
    group = SlashCommandGroup("group")

    @group.command()
    async def subcommand1(self, ctx):
        await ctx.respond("This is a normal subcommand.")

# Cog2.py
from pycord.multicog import subcommand

class Cog2(commands.Cog):
    @subcommand("group")
    @slash_command()
    async def subcommand2(self, ctx):
        await ctx.respond("This subcommand is in a different cog.")
upbeat remnant
#

The issue I found with multicog was adding subcommand groups.

Example:
All RSS related commands are in separate class files within the same module folder.

The rss command group is defined in rss_feeds.py along with a subcommand group, feeds resulting in the command /rss feeds add, etc.

I then want to create, in the template cog, the /rss template subcommand group.

Either way, as far as my understanding goes, I'd still need to import another cog to access the rss command to then add a subcommand group, or is my understanding incorrect?

#

Unless I define the subcommand group in rss_feeds and then use the @subcommand decorator to add the commands to it, I guess. Brb, giving it a try

fresh sierra
fresh sierra
#

Is it to use group and subgroup ?

#

If yes you should just do
subcommand(group subgroup) with a space between

upbeat remnant
#

Original issue was that commands when used in discord were asking for the ctx parameter (ApplicationContext) but only for the one cog.

fresh sierra
#

Are you passing self outside a cog ?

upbeat remnant
fresh sierra
#

I don’t think also at the end you need the bot.add application vommand

#

If ur using bot.load_extension

upbeat remnant
#

I wasn't using multicog at all this morning, so that might be the issue. I'm currently refactoring to use multicog 🙂

fresh sierra
#

Create all of ur group in one file which will be run before all the other cog

upbeat remnant
#

OKay, I'll give that a try and come back if the problem persists. Thanks.

uncut quartz
#

after i've deferred a response, is it possible to then respond with just a view? (for components v2)

#

when I try, i get the error about the existence of content / embeds

lapis dock
#

can you share the error, you should not be having this issue unless you are actually supplying content or embeds

uncut quartz
#

one sec, lemme recreate it rq :)

errant trout
#

it sure would be a shame if i messed up the validation somehow

errant trout
#

reinstall

#

or rather, install master

uncut quartz
#

alr one sec

#

awesome, it works!! tysm <3

errant trout
#

allgood

patent meadow
#

im having an issue running the example code on the github page. It doesnt seem to register a command for me. Is there something special I have to do other than run this with the bot in my server?

import discord

bot = discord.Bot()

@bot.slash_command()
async def hello(ctx, name: str = None):
    name = name or ctx.author.name
    await ctx.respond(f"Hello {name}!")

bot.run("token")
#

im using python 3.13.5 and created a fresh venv with only pycord installed

#

did discord break the api recently maybe?

torn barn
#

refresh the discord client

patent meadow
#

thank you lmao

torn light
rugged lodgeBOT
#

Here's the slash autocomplete example.

torn light
#

Okay.
Thanks.
If there are any other options, please let me know.
-# Please ping me when you reply to me. I use a translator and can't see all messages

eternal kite
#

can there be two selects in one discord message?

errant trout
eternal kite
#

thanks

errant trout
#

But if you go above 5 selects, the library will switch you to CV2 which will disable content and embeds

eternal kite
#

alr

placid ferry
#
        embed = discord.Embed(
            title=f"[{artist_name} in {ctx.guild.name}]({artist_url})",
            url=artist_url,
            color=discord.Color(0xFFFFFF),
        )

im hoping this is fine? its still dpy but this server is far more helpful than the dpy one

errant trout
#

title won't take markdown

sage tendon
#

breh

errant trout
#

you only need the visible text, url will do what you want

sage tendon
placid ferry
placid ferry
#

i regret not starting with pycord at the start of it

sage tendon
#

switching isn't much effort, from experience

placid ferry
#

😭 ive never switched thats the issue though

sage tendon
#

all the core stuff is the same, the only difference are command decorators, and maybe options? but not sure there

placid ferry
#

ayye it works now

placid ferry
sage tendon
#

oh you're using a client mod that's why I thought it looked like cv2

placid ferry
#

LMFAO

sage tendon
# placid ferry oh yea decorators is a thing i rely on

well yea but it's basically just changing the name to another if I remember right, and not needing a lot of weird stuff like manual syncing and stuff

ig read the guide and you can tell how much is different, been a long time since I used dpy

placid ferry
#

i'll def look into it then once im done workjing on this cog (unfortunately might take all day since I have to test it on production instead of my testing bot)

sage tendon
#

plus everyone here will help you if you have problems switching to pycord :3

placid ferry
#

do you know how to fetch the artist cover art for lastfm? ive never been able to get this to work for some album covers and artist cover art

#

but fmbot seems to have no issue with it

sage tendon
#

there's probably an API

placid ferry
#

im using their api thats the thing

#

but

sage tendon
#

ah
well then it's somewhere in there surely :)

placid ferry
#

it doesnt seem to fetch all the cover arts

#

part of me wants to look thru lastfms repo and see since its oss but at the same time its .NET and C# and i dont know jack abt either

sage tendon
#

you are reading their docs right

placid ferry
errant trout
#

what are you using LOL

sage tendon
#

docs are the key to using any API or package

#

if you don't read docs you're screwed usually

placid ferry
errant trout
#

yea

placid ferry
errant trout
#

yeah but like

#

is it a python library, or are you using their api directly

placid ferry
#

OH

#

pylast

#

and

#

their api

#

so kinda both

sage tendon
placid ferry
#

i use pylast for the authentication stuff i think thats all though

#

the rest os their api

#

yea

#

so

sage tendon
#

we'll go through their API docs and you'll find it somewhere 100%

placid ferry
#

literally one thing uses pylast

#
        self.network = pylast.LastFMNetwork(
            api_key=self.api_key, api_secret=os.getenv("LASTFM_SECRET")
        )
        self.db = None

just this

errant trout
#

so like, is the request not returning an image at all or does it return some generic url

placid ferry
sage tendon
#

well as I said as a developer you read docs or you'll be in huge pain

placid ferry
#

one second

errant trout
errant trout
placid ferry
#

this

errant trout
#

i.e. if lastfm themselves isn't returning it then you kinda just have to roll with it

sage tendon
#

well if that's the image returned by the API I guess you're out of luck

#

depends if multiple requests have the right picture sometimes and sometimes default, that'd be something to look into

#

like for the same song

placid ferry
#

so i checked the url, and whatever lastfm uses https://i.scdn.co/image/ab67616d0000b2732d4aa8abd5ebeb4657e609e0 is what the url shows for the current song, so its not from lastfm so i guess i'll check that

#

hmmmm

#

ion even know what this thing is

errant trout
#

that's spotify's cdn LMAO

sage tendon
#

wow

placid ferry
#

wait really??

#

OH

#

scdn

sage tendon
#

so chances are the given album is not on Spotify or smth lol

placid ferry
#

im slow

#

no the url i sent

#

is how fmbot shows it

sage tendon
#

oh

placid ferry
#

which is the correct cover

#

my bot on the other hand

#

it sends this https://lastfm.freetls.fastly.net/i/u/300x300/2a96cbd8b46e442fc41c2b86b821562f.png

#

😭 jus realized thats a really long subdomain

errant trout
#

maybe just print the raw request data and see what it looks like

placid ferry
#

star

sage tendon
#

are you sure the album has art on lastfm

placid ferry
#

it does not

sage tendon
#

well there you go

placid ferry
#

i figured that out after you told me it was spotifys cdn that url belonged to

#

or

#

nelo

obsidian stratus
#

How do we use the new copy text feature in components v2?

rugged lodgeBOT
obsidian stratus
#

Do we also have Container.copy_text

errant trout
#

yes

rugged lodgeBOT
obsidian stratus
#

Oh okay, thank you 😃

errant trout
#

View.copy_text will copy the contents of all TextDisplay items in your View, including Containers and Sections

#

this is the same behaviour as Right Click -> Copy Text on CV2 messages

obsidian stratus
#

Ohh

placid ferry
#

@errant trout can footers have hyperlinks in CV2?

echo wraith
placid ferry
#

oh

echo wraith
#

also no need to ping Nelo someone will reply

echo wraith
placid ferry
#

sorryyy blobsweatsip

echo wraith
placid ferry
echo wraith
#

use this

placid ferry
#

can i

#

do them under footers

echo wraith
#

-# [some link](https://discord.com)

placid ferry
#

or does footers stay at the bottom

#

since its a footer

echo wraith
#

There's no such thing as footer in cv2, again

#

it's just text

placid ferry
#

I'm not using CV2 rn so thats why i was asking

echo wraith
#

in normal embeds you can't

placid ferry
#

fawk

#

oh well

placid ferry
#

yayay, i finally figured out the spotify api stuff

lofty parcel
#

Compact mode dang

brazen mango
#

I use compact mode and light mode

shell radish
#

by using light mode, you are contributing to global warming

wheat tiger
#

using light theme is a sin

viral plover
#

Anyone know how to get everyone in a Discord server with a specific tag / every member who has the server tag applied

sage tendon
#

bot.http.get_user(uid)["primary_guild") i think

#

you will need to iterate through everyone, its not in 2.6 (obv), and im not sure if master has it properly built in
but that is the way i did it

viral plover
viral plover
sage tendon
#

i really dont follow the PRs or what happens on the master branch, no idea

sage tendon
echo wraith
sage tendon
#

yea its not properly on master yet either

viral plover
#

yea I think we are just gonna check when they sign up and when the giveaways rolls

normal iris
#

Hi, is py-cord compatible to python3.13? Because i had issues with the audioop library being deprecated

lapis dock
#

You need to use the master branch for 3.13 support. Or you can install audioop-lts

normal iris
sage tendon
#

yes

patent meadow
#

Im trying to change the message the bot says when it defers a command. is this possible?

@bot.slash_command()
async def defer(ctx):
    await ctx.defer()
    time.sleep(3)
    await ctx.followup.send("Done!")
#

Right now it says Bot is thinking...

errant trout
#

also never use time.sleep with a discord bot, you should import asyncio and await asyncio.sleep instead

patent meadow
#

thank you ill do that

patent meadow
# errant trout also never use `time.sleep` with a discord bot, you should import asyncio and `a...

im having trouble using asyncio.to_thread(). I want to make the docker sdk async but just for testing im using still using time.sleep()

@bot.slash_command()
async def defer(ctx):
    await ctx.defer()
    await asyncio.to_thread(time.sleep(3))
    await ctx.followup.send("Done!")

this throws discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: 'NoneType' object is not callable

errant trout
#

e.g. in this example it would be (time.sleep, 3)

brazen mango
#

Wouldn't it be simpler to just use await asyncio.sleep(3) instead?

errant trout
tardy bluff
#

When using the basic slash commands example no slash commands seem to be available. What am I doing wrong?


@bot.command(description="Sends the bot's latency.") # this decorator makes a slash command
async def ping(ctx): # a slash command will be created with the name "ping"
    await ctx.respond(f"Pong! Latency is {bot.latency}")```
sly karmaBOT
# tardy bluff When using the basic slash commands example no slash commands seem to be availab...

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.
tardy bluff
#

Ah, I just needed to refresh discord

flat wind
#

Hello !
Is it possible to call something like self.my_function in an autocomplete callback ?

frail basin
flat wind
#

okay got it, thanks !

sage tendon
#

I am trying to do a generic "redo command" view that i can just add to the end of views, and which will just re-call the command. I've got this far

#

However, the invoke constantly throws this error despite ctx.command being set properly inside of the original command callback. how?

edgy nest
#

save it from the old context and reset it when the button is pressed

sage tendon
#

save it where? in the init?

edgy nest
edgy nest
#

or just before you change .interaction

sage tendon
#

holy fucking shit that was all i was missing

#

thanks

edgy nest
#

👍

sage tendon
#

now :) next lil problem
the command im invoking may defer at times - but since its intended for a slash command context, it doesnt pass invisible=False
is there a way to force this without changing the command code?

edgy nest
sage tendon
#

okay erm
it all works like i want now, but i can only re-run the command once x3
the second time around, i get the same error with command being none

terse zephyr
#

How can I make it so I can run a command from my bot in any dm, not just a dm with the bot? Some apps I have installed allow me to run their commands when I’m talking with friends in dms, but mine doesn’t. How do I do this?

errant trout
#

make sure it's enabled on dev portal, then grab your bot's install URL and add &integration_type=1

terse zephyr
#

Ok I'll try that

terse zephyr
#

in a dm

#

the bot IS running

errant trout
rugged lodgeBOT
#

Here's the slash users example.

terse zephyr
#

oh i see

tidal vessel
#

Hi guys, I have a question: how can I get a user's banner in the server where the command is used? In the documentation, it says to use fetch_user() and it works, but it returns the global banner, and I want to get the banner the user has set in the server (in case they have Nitro).

I tried with Member but it returns None Can someone explain this to me better? Or maybe I missed something else in the documentation.

errant trout
lethal loom
#

Hi, how we become a new pyxord update wirh the New functilnallyties

wide jasper
#

Hi guys, is it possible to check if someone has the "guild tag" like in my case in the image "QKZ"

sage tendon
#

yes
if you're on 2.6 it's a bit hacky tho

#

bot.http.get_user(id)["primary_guild"] I think

echo wraith
#

But yeah that's it

cerulean laurel
#

where do i put the "timeout=none" thing

#

if i do discord.ui.View(timeout=none) in the first yellot brackets my bot crashes

sage tendon
#

pass it to the super init

#

and it's detailliert :)

cerulean laurel
#

sry what?

sage tendon
#

pass timeout=None to the super init call

cerulean laurel
#

so "super(timeout=None).init()"

sage tendon
#

no, to the init

cerulean laurel
#

so after the init

sage tendon
#

super().__init__(timeout=None)

#

to the init

cerulean laurel
#

oh thx

#

also my code crashed and it said it can only have 2 positional arguments but 3 were given

sage tendon
#

show the traceback and your code

cerulean laurel
#

Thats the crash if u mean that:

Ignoring exception in view <Annehmen_Button timeout=180.0 children=1> for item <Button style=<ButtonStyle.primary: 1> url=None disabled=False label='Annehmen' emoji=<PartialEmoji animated=False name='😎' id=None> sku_id=None row=None>:
Traceback (most recent call last):
File "C:\Users\USER\AppData\Roaming\Python\Python313\site-packages\discord\ui\view.py", line 426, in _scheduled_task
await item.callback(interaction)
~~~~~~~~~~~~~^^^^^^^^^^^^^
TypeError: Annehmen_Button.button_callback() takes 2 positional arguments but 3 were given

sage tendon
#

oh, yea, you are missing the button argument in your callback
it goes between self and the interaction

cerulean laurel
#

button argument?
sry i had a break and just came back to my bot

sage tendon
#

just add it between the self and interaction arguments of the button callback

cerulean laurel
#

i mean how do you write this argument

sage tendon
#

just button or something

#

the name doesnt matter

#

you can also name it _ if your IDE says you aren't using the argument

cerulean laurel
#

sry i cant follow you

#

got it thx

flat wind
#

Hello !
About this in the API. Am I wrong or is it just impossible to create a forum thread ?
Here in the docs we have the "content" value : https://docs.pycord.dev/en/stable/api/models.html#discord.ForumChannel.create_thread
I also have this error when I try with "content" variable : In message: This field is required

But if I try with message :
TypeError: ForumChannel.create_thread() got an unexpected keyword argument 'message'.

Am I doing something wrong ?

sage tendon
#

show your code

errant trout
#

the argument is indeed content, not message

flat wind
# sage tendon show your code
if channel.type == ChannelType.forum:
                    new_thread = await channel.create_thread(
                        name=translated_name[:100] if translated_name else thread.name[:100],
                        content=starting_message,
                    )
                        
                else :
                    # Create the thread in the target channel
                    new_thread = await channel.create_thread(
                        name=translated_name[:100] if translated_name else thread.name[:100],
                        message=starting_message,
                        auto_archive_duration=thread.auto_archive_duration,
                        slowmode_delay=thread.slowmode_delay,
                        invitable=thread.invitable,
                        type=thread_type,
                    )
errant trout
flat wind
errant trout
#

oh wait

errant trout
#

because you're using it in both content and message, which is wrong

#

content in ForumChannel.create_threadshould just be a string, while message in TextChannel.create_thread is expected to be a full message

#

(because you don't create forum posts from an existing message)

flat wind
#

oh okay !! that's why ! mb

errant trout
#

allgood

flat wind
#

will check it but it should be it

sage tendon
#

anyone know how i can shorten this without killing readibility

#

Also I think master has a bug, I (obviously as you can see) have a banner, but member.display_banner is None for me

#

does indeed print None when used on me even though i have a banner

#

I think the issue is that the banner (according to the docs) is only available via Client.fetch_user, and well, that cant work for Member. The lib currently doesnt fetch the user object when realizing there is no guild-specific banner, it just returns it from the user object within member (if you know what i mean) where it is not if it hasnt been fetched

#

should i make this a github issue

tidal vessel
silk spire
#

The guild specific banner is given over the gateway IIRC

#

the global banner needs to be fetched yes

sage tendon
#

Yea so first of all discord should get its shit together
but it is a lib oversight that the user isnt fetched before returning the (not cached) banner

silk spire
#

The lib shouldn't fetch or cache it when it can't update it imo

tidal vessel
#

So is there a way to get a member's banner? Not the global banner.

sage tendon
#

member.display_banner

#

but itll be none if there's only a global banner

#

yea i think ill make a github issue brb

rugged lodgeBOT
tidal vessel
#

But it is None, also as I said I tried with the API and it still returns None in the banner, it is very strange or maybe I am doing something wrong, I don't know

silk spire
#

You sure the user had a guild specific banner? And did you fetch member or user

#

fetching member doesn't return the global banner

tidal vessel
silk spire
#

That's Guild.fetch_member yeah

sage tendon
silk spire
#

Did you fetch is via pycord?

tidal vessel
#

And it doesn't work

#

I don't understand kek

errant trout
#

can't repro?

#

oh display_banner

#

ah

#

eh......

sage tendon
#

:3

#

either the library forcefully fetches it when querying display_banner, or the docs need to be updated, or the name should change

errant trout
#

pretty sure it's because the member banner is overriding the user banner

sage tendon
#

wdym?

errant trout
#

but avatar is designed in the same way so maybe not...?

sage tendon
#

remember User.banner is only available on fetch

#

and as far as i could tell the lib returns member.display_avatar or user.banner (whatever it is called exactly in the code)

#

and since the banner isnt cached cause it wasnt fetched, 💥

#

well not boom but None

errant trout
#

we will keep display_banner because fetch_member does return user.banner, but add a warning on docs saying the behaviour is different from cached members

#

then just fix the issue with fetching member not storing user.banner properly

sage tendon
#

wait so
the intended behavior is now having to fetch the member then?

errant trout
#

yes

#

(after it's fixed)

sage tendon
#

ok thx

#

i think my first proper bug find :3

silk spire
#

Oh it does now

#

Finally

sage tendon
#

Is there some more space saving way to do this? I haven't done that much with CV2 yet but I've always done it like this so far, and bigger CV2 views take up quite a lot of space like that

#

or better, is this even the intended way of using it or is the container.add_x the intended solution

silk spire
#

You can use the add methods but imo your current code looks better

view = discord.ui.View().add_item(
    ui.Container(color=...).add_text(
        "Hello world"
    ).add_item(
        ui.MediaGallery().add_item(
            "url here"
        )
    )
)

Or maybe defining them separately cleans it up a bit

container = ui.Container(...)
container.add_text("...")

gallery = ui.MediaGallery()
gallery.add_item("url")
container.add_item(gallery)

view = ui.View(container)
hard haven
#

What is the best way to restart a bot using a command?
Tank you!

fresh sierra
#

.tag restart-cmd

sly karmaBOT
#

The only good way to restart your bot is to shut it down and have your process manager handle it. You can shutdown your bot by running Bot.close().

Do use

  • Run your bot in a process manager such as:
  • Systemd
  • Openrc (Gentoo, Devuan)
  • Runit (Void Linux)
  • Supervisord
  • Upstart (Old Ubuntu)
  • Docker
  • Manually reboot it

Do not use

  • A bash loop (it can eat your C-c by rapidly spawning python and if your bot fails it won't stop it from constantly failing)
  • subprocess.call (you will eat your memory up by not letting your old processes die)
  • os.exec
    Tag Credit: discord.py server
hard haven
fresh sierra
#

To sync the command ?

#

because you might not even need to restart te bot to do what you want

hard haven
#

I am creating a text-to-speech bot and would like to restart all related programs.

fresh sierra
hard haven
#

It's a little difficult to connect to the server running the bot, so I'd like to restart it remotely using a command if possible...

fresh sierra
hard haven
#

    Python v3.12.10-final
    py-cord v2.6.1-final
    aiohttp v3.12.15
    system info: Windows 11 10.0.26100
sage tendon
sage tendon
frail basin
#

It will detect that it "crashed" and restart it

#

Systemd works too

hard haven
#

OK,I'll try!
Thank you!

sage tendon
#

qwq

#

why restart tho

frail basin
#

Would it cause isses if I called bot.add_view on the same view twice?

echo wraith
#

.tag tas

sly karmaBOT
echo wraith
#

Nah but honestly

#

ViewStore is such a mess

frail basin
#

as far as I can tell from looking at the library code, the second call should override the first

echo wraith
#

I have absolutely no fuckery of an idea

frail basin
#

the custom ids and the message id are the same so it looks fine?

#

I basically want to add a command that reloads all persistent views from the database

sage tendon
#

I still have yet to find out what custom IDs are even for

fresh sierra
#

doing that since a long time and never had any issue with it

silk spire
# sage tendon I still have yet to find out what custom IDs are even for

That and the component_type is all Discord sends about the component with the interaction create event when someone uses your interactable components

The lib then needs to find the corresponding item and view with the same id and dispatch it accordingly

sage tendon
#

so i guess the library tracks which view object was sent with what message, and so that works even if you dont add the view to the bot & set custom IDs?

silk spire
#

Yeah the lib stores all views until the timeout

sage tendon
#

My bot automatically colors embeds (and now CV2 components) via a user's accent color.

Now, i noticed that someone who has an entirely purple profile has this color as accent_color
why is that? doesnt the custom-set theme color override that? second screenshot is their profile

errant trout
sage tendon
#

im already doing that, dw

#

im just wondering why it seems to be, well, wrong

torn light
#

I want to use message_command on servers where there is no bot. Is this possible, or am I misunderstanding something?

rugged lodgeBOT
#

Here's the slash users example.

sage tendon
#

breh how do you all remember all the examples and tags

errant trout
#

eh i just used it the other day

errant trout
errant trout
#

not profile colors

sage tendon
#

Yea, but their banner is nowhere near that color either qwq

errant trout
#

it may be whatever they have set under their image banner

sage tendon
#

(its purple)

#

wdym

errant trout
#

if you don't have an image banner set

sage tendon
#

oh right
oof, so discord doesnt use the banner or profile color when you have a custom banner... and to change that color you need to delete your banner.. god that is dumb

errant trout
#

yeah it's a tad convoluted

sage tendon
#

i wish we could just access the profile theme colors

errant trout
#

this also returns None if they're using the automatic banner colour based on their PFP

sage tendon
#

accent_color? oh ffs

errant trout
#

yep

#

if they're a member, you could try fallback to Member.color to get their guild role rolour

#

or run some img library to pick a colour from their pfp yourself

sage tendon
#

yea ill have to see if it works for most people or if i need to change it
thx

errant trout
#

allgood

tribal magnet
#

can I get help?

#

discord.ext.commands and discord.commands are very confusing.

#

When creating a Cog file:

from discord.ext import commands

class Name(commands.Cog):

On the other hand, when creating a slash command in same file:

from discord.commands import slash_command

@slash_command(...)
async def ...

I want to understand the difference between the two.

After reading the docs, it seems that Cogs only exist in discord.ext.commands.
However, slash commands are available in both.

errant trout
#

ext.commands is a legacy part of the library that existed BEFORE discord added slash commands

#

Slash commands are fully compatible with functions in ext.commands, but it is not required

rugged lodgeBOT
#

Here's the slash cog example.

errant trout
#

That example, and several of the others in that folder, should demonstrate different usages of slash commands

tribal magnet
errant trout
#

If you do not want to make prefix commands (e.g. !help) then yes, it is not required

tribal magnet
errant trout
#

Yep (you can also just shorten it to from discord import slash_command)

tribal magnet
errant trout
tribal magnet
#

Can I ask one more question?
There is commands.NoPrivateMessage() in my code , but I found in the docs, it seems to exist only in discord.ext. What should I do in this case?
It looks like commands.CommandInvokeError can be replaced with discord.ApplicationCommandInvokeError

errant trout
#

from discord.ext.commands import NoPrivateMessage etc

#

...though, that's not a very good answer from me

#

what you really want is contexts

rugged lodgeBOT
errant trout
#

this will let you restrict it to a certain context, e.g. discord.InteractionContextType.guild

tribal magnet
#

I think there’s really no need to insist on avoiding discord.ext.
That was my mistake. It was helpful, thank you

errant trout
#

no worries

sage tendon
#

I'm trying to convert an automatic slash command generator to using groups

At the end, I have self.bot.add_application_command, do i still need that when i already add it to an existing group?

fresh sierra
sage tendon
#

well

echo wraith
#

well

sage tendon
#

it is actually erroring tho so 1s

#

yea i cant do that

#

do i just need to add the groups as commands, once they're done?

fresh sierra
#

if ur current solution is not working

sage tendon
#

oh yes

#

1s

fresh sierra
#

on my side, im doing that:

sage tendon
#

nope, doesnt show up

#

okay hold the phone, i got a 400 error

#

something is getting to discord

fresh sierra
sage tendon
#

transgender is one of my subcommands

fresh sierra
#

group command will try to add it too i think

sage tendon
#

which then

fresh sierra
#

if the 1st one is not working with group.command maybe only the group.add_command

sage tendon
#

oh fuck yea it works

#

thx

#

also something i learnt: if a group has no subcommands, it acts as standalone command

fresh sierra
#

like

command_function.cog = self
command_function.parent = group
group.add_command(command_function)
sage tendon
#

so gonna explode the command limit

#

200 right?

fresh sierra
#

but a group count for 1 command

sage tendon
#

oh goood

#

this little code to create like 40 commands lol

fresh sierra
#

component v2 ?

sage tendon
#

yea its like 15 each

sage tendon
#

completely unnecessary for this but :3

fresh sierra
#

command looks strange asf

#

like just sending a view

#

seems off

sage tendon
#

well

#

its just 3 command groups (i forgot one) that uses the api there to apply all kinds of filters

#

and well, you only need the url for that

fresh sierra
#

no but ur code is normal

#

its just that im not used to just sending a view instead of building embed or smth like that

#

i wonder how it will looks like with view less component

sage tendon
#

well im constructing the cv2 components inside of the view

fresh sierra
#

yeah ik

sage tendon
#

ngl i kinda dislike that single images also need to be wrapped in a mediagallery

fresh sierra
#

tbh i find component v2 a bit wierd

#

like all you need to do so simple things

#

embed are so much easier so having to switch make me feel soooo lazy

sage tendon
#

final result

fresh sierra
#

since he is in jail

sage tendon
sage tendon
wheat tiger
errant trout
#

that's just an option in pycharm

#

forgot what exactly though

wheat tiger
errant trout
#

nah toothy hates vsc

#

maybe you could find an extension that does something like that? but i wouldn't know

wheat tiger
#

or u too hate it ;-;

errant trout
#

Nah I don't mind it

#

I do all my pycord PRs on github.dev which is a browser version of VSC (vscode.dev) with proper github integration

#

Too lazy to open a desktop IDE

frail basin
wheat tiger
lofty parcel
#

Or an extension

wheat tiger
#

search of inlayHints in settings, there are many options to tweak for every supported language

lofty parcel
#

Fun. Thanks lol

wheat tiger
sage tendon
#

it only shows sometimes tho (else it'd be clutter) but I haven't found the rule yet

lapis dock
#

The one downside is it makes your lines longer than the max line limits, without actually doing so.

echo wraith
#

@frail kayak What distro are you on ?

frail kayak
echo wraith
frail kayak
echo wraith
#

also

#

.tag venv

sly karmaBOT
#

Sometimes you want to keep libraries from polluting system installs or use a different version of libraries than the ones installed on the system. You might also not have permissions to install libraries system-wide. For this purpose, the standard library (as of Python 3.3) comes with a concept called "Virtual Environment"s to help maintain these separate versions.
The main benefit is to avoid package conflicts and unnecessary packages

Read more in the guide

frail kayak
#

yeah i hate venv

echo wraith
#

you should use it, still

sage tendon
#

venvs are very useful

frail kayak
#

turned off some programs, restarted terminal and it worked, thanks

echo wraith
sage tendon
#

not if you only have one project

echo wraith
#

yes if you only have one project

frail kayak
#

I do not disagree its useful and necessary just sometimes have troubles with this "concept"

sage tendon
#

if you use a proper IDE you don't even have to think about it

echo wraith
frail kayak
#

and it does it when it wants

#

if only you've seen my face trying to install packages properly that day I setup it

#

anyway thanks for help, gotta go enjoy cv2

echo wraith
#

have fun haha

sage tendon
#

what

cerulean laurel
#

what does that mean/what do i have to change?
discord.errors.ExtensionFailed: Extension 'cogs.sendsomething' raised an error: ValidationError: Command names and options must follow the regex "^[-_\w\d\u0901-\u097D\u0E00-\u0E7F]{1,32}$". For more information, see https://discord.com/developers/docs/interactions/application-commands#application-command-object-application-command-naming. Received "Send Embed"

Discord Developer Portal

Build games, experiences, and integrations for millions of users on Discord.

echo wraith
cerulean laurel
#

ok but why

#

i mean the reason why i used the extra name thing was to make it big and with space

echo wraith
cerulean laurel
#

and no way to bypass that with unicode or smthing like that?

echo wraith
sage tendon
#

not without subcommands

cerulean laurel
echo wraith
cerulean laurel
#

oh ok thx

sharp pawn
#

Hello, i know this question is not directly linked with pycord but did someone had issue with aiohttp blocking the event loop when it raises an aiohttp.ConnectionTimeoutError?

This issue is occurring in production enviroment, initially it happened every 24 hours more or less, to try to solve it i added a custom session:

import aiohttp

_session: aiohttp.ClientSession | None = None


def get_session() -> aiohttp.ClientSession:
    global _session
    if _session and not _session.closed:
        return _session
    timeout = aiohttp.ClientTimeout(total=30, connect=10, sock_connect=10, sock_read=20)
    connector = aiohttp.TCPConnector(limit=100, ttl_dns_cache=300)
    _session = aiohttp.ClientSession(timeout=timeout, connector=connector)
    return _session

async def close_session():
    global _session
    if _session and not _session.closed:
        await _session.close()
        _session = None

This change seems to work just fine but today the issue appeared again after 5 bot working days

Here you can find the logs: https://pastebin.com/d4E52uEL

After this error occurs it seems like my main loop gots blocked, i can't invoke commands and no errors are shown when i do, the bot responds with interaction error like if the bot is offline, even if so i still got logs from background activities like scheduled cogs and tasks

(More or less the bot sends 80+ request per hour)

rugged lodgeBOT
flat wind
#

Hello !!
Is it possible to connect to a new shard without restarting the bot ?
I saw the AutoShardedClient.get_shard() and the discord.ShardInfo.connect() but if the new shard does not exists when the bot started, the get_shard will just return None. Am I wrong ?

#

I get a new shard every week / 2 weeks and currently restart the bot after I get a new shard. I would like to avoid the downtime by adding a new shard without restarting the bot

lofty parcel
sage tendon
#

Yea I also would think its not possible. But this made me think: How do huge bots like dyno do it? Their growth is quite steep, and they cant be restarting every 1000 guilds (or whatever the shard max is)
So there surely must be a way

lofty parcel
#

That handle a set of shards

shell radish
#

pods

lofty parcel
#

Idk that's what they call them

hexed herald
#

maybe smth special for them, large bot's have some extras, don't they?

shell radish
hexed herald
#

¯\(ツ)

errant trout
#

The next step after shards is usually "clusters" of shards

flat wind
echo wraith
#

Kubernetes

lofty parcel
#

But they call them pods

#

Or i think pods deploy and manage the clusters

#

Some Kubernetes shit

round heart
valid panther
#

Do users who use commands in discord.InteractionContextType.private_channel need permissions to view emojis?

sage tendon
#

No

#

is that a user app? might be a discord bug

valid panther
#

Yes, it works correctly on the server, but in private conversations it only works on the button. It's very strange.

sage tendon
#

thats cv2 right?

#

there is currently a known bug where bots can use any emoji sent with cv2 buttons

#

so what you have with the emojis in the text might be a side effect of that

valid panther
#

and there is no effective solution for that at present ?

#

:((

sage tendon
#

can you try send those exact emojis with a regular text-only response?

#

and see if it still happens

valid panther
#

My emojis are currently uploaded to the server, but my idea is to upload them to the app in the future, where you can have up to 2k emojis. But since it's a bot and not a team, the trial version or stable version remains the same.

valid panther
sage tendon
#

just a pure ctx.respond("<emoji>")

#

in a message without cv2

echo wraith
#

-Remindme 3d wtf

lofty vaultBOT
#

Set a reminder in 3 days from now (<t:1756135129:f>)
View reminders with the reminders command

sage tendon
#

you and your reminders

echo wraith
#

:)

frail basin
#

am I safe to do this to generate mock users?

user = discord.User._copy(bot.user)
user.name = "MockUser"
user.global_name = "AmoxMockUser"