#Basic Pycord Help

1 messages · Page 69 of 1

autumn gust
#

a small bit

errant trout
#

i'll just throw out some example then

autumn gust
#

I have figured out autocomplete

errant trout
#

discord has no way of selecting multiple options in 1 arg

#

so instead of using a list of then, you make a separate bool arg for every spec

#

and have them all as default=False

#

it's kinda finicky, but that's more or less the only way

autumn gust
#

how does one make bool arguments again? just like uhh CPU=bool?

errant trout
#

no that's the type

#

i.e. where you put str

autumn gust
#

OH WAIT

errant trout
#
@option("CPU", bool, default=False)
@option("GPU", bool, default=False)```etc. etc.
autumn gust
#

ya, I just noticed

errant trout
#

ah, if im not mistaken

#

args have to be lowercase

#

on discord's side

autumn gust
#

got it

#

how do you define multiple embeds in discord.embeds?

#

or is it just discord.embed() x5 for me

errant trout
#

send/respond have an option for a list of embeds

#

up to 10, maximum 6000 characters across your entire message

autumn gust
#

so ctx.respond(embeds)?

#

but how does one define embeds

errant trout
#

embeds=[...]

#

which is a list of discord.Embed

autumn gust
#

ohhh wait so

autumn gust
#
embed1 = discord.Embed(...)
embed2 = discord.Embed(...)
...

embeds=[embed1, embed2, embed3, embed4, embed5]
errant trout
#

yep

autumn gust
#

got it

#

uuuuuuh, stupid question: how do you define color?

#

just throw in the hex code for it and call it a day?

raw beacon
#

discord.Embed(..., color=)

autumn gust
#

ya, but what to put inside of color

raw beacon
#

yes, the hex

#

like, discord.Embed(..., color=0x171515)

autumn gust
#

color=e62929 gets yellow underlined, color=#e62929 makes the rest of the code a comment

raw beacon
#

use 0x instead of #

autumn gust
#

ooooh, ty

errant trout
#

0x is how you do hexadecimal in python yeah

#

otherwise the discord.Color class also supports RGB and HSV values

hard heath
#

I have a question. I was experimenting with slash commands, but according to the official guide, in slash commands instead of using ctx.send () a ctx.respond is used. I would like to know if there is any difference, because apparently you can also use the ctx.send.

raw beacon
#

iirc .respond works for both undeffered and deffered

lofty parcel
#

.send sends a plain message to the channel. it doesn't count towards responding the interaction

pulsar ferry
#

is there an easy way to only allow the user who called the function to use the buttons on a view? i know i can use ephemeral but want everyone to still see it

raw beacon
pulsar ferry
#

yeah so something like this?

        if interaction.user.id != self.user_id:
            # Optionally, you can send a message or disable the button
            await interaction.response.send_message("You're not authorized to interact with these buttons.", ephemeral=True)
            return

#

was wondering if there was just an out of box decorator

raw beacon
obsidian stratus
#

How to change message cache size?

#

Specifically for delete and edit events

errant trout
#

default is 1000

pulsar ferry
#

how would i delete the message?

errant trout
#

interaction.delete_original_response

pulsar ferry
#

await interaction.delete_original_response() ?

#

gives discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook

#

ultimatley what i am trying to do is give use a view that is ephmeral, then when they click the button update it but have it go public... is taht possible or is approach to delete and respond with new message?

errant trout
#

delete_original_response only works if you've already responded - defering counts as a response

pulsar ferry
errant trout
#

.response.defer()

#

(probably ephemeral too)

pulsar ferry
#

hmm something not right

#

i first have this

    @rps.command(name="unranked")
    async def rps_new(self, ctx):
        """Start a new unranked Rock-Paper-Scissors game."""
        view = RPSGameView(self, game_id=None, league="unranked", tip=None)
        await ctx.respond(view=view, embed=view.get_embed(), ephemeral=True)
#

so am doing ctx.respond with the view

#

then in the view

class RPSGameView(View):
    def __init__(self, rps_cog: RPS, game_id: int, league: str = None, tip: float = None):
        super().__init__(timeout=None)
        self.rps_cog = rps_cog
        self.game_id = game_id
        self.league = league
        self.tip = tip

        self.embed = discord.Embed(title=f"Choose your Move!", color=discord.Color.blue())
        # Add each detail as a separate field, with Game ID first
        self.embed.add_field(name="Game ID", value=f"{self.game_id or 'New'}", inline=True)
        self.embed.add_field(name="League", value=self.league.lower() if self.league else "None", inline=True)
        self.embed.add_field(name="Tip", value=f"💰 {self.tip if self.tip else 'No tip'}", inline=True)

        # Add the choices (buttons) to the view
        choices = [("🪨", "rock"), ("📄", "paper"), ("✂️", "scissors")]
        for emoji, choice in choices:
            button = Button(label=choice.capitalize(), style=discord.ButtonStyle.primary, emoji=emoji)
            button.callback = lambda interaction, choice=choice: self.handle_choice(interaction, choice)
            self.add_item(button)

    async def handle_choice(self, interaction: discord.Interaction, choice: str):
        """Handles user's game move choice."""

        await interaction.response.defer()
        await interaction.delete_original_response()

#

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

#

the delete actually seems to work but then the send message later doesnt

pulsar ferry
errant trout
#

eh

errant trout
#

interaction.respond normally handles it

pulsar ferry
#
        await interaction.response.defer()
        await interaction.delete_original_response()

        await interaction.response.send_message(embed=self.embed, view=self)

errant trout
#

then yeah just change it to interaction.respond, it chooses the appropriate function

pulsar ferry
#

ah that did it!

#

thanks

errant trout
#

(which is interaction.followup.send, the main point is convenience)

echo wraith
#

Yeah no but you can't block a user from going to the discord shop thing and subscribing to a tier

#

Like one way around it's easy

#

The other way I don't see how one would do it

errant trout
#

idk skill issue

echo wraith
#

I mean I don't really care cause the payment developer terms don't apply to me anyways

#

It would be weird to create a test entitlements for everyone that subscribes through your website

nocturne jewel
#

how to auto accept these kind of requests? when someone try to join

raw beacon
#

why would you want to auto accept them

#

their sole purpose is to be manually reviewed and accepted / rejected

lapis dock
#

I dont think join applications have been added to the API yet
Also it is unclear how they will change (or if they will exist) when guilds are discontinued

maiden bloom
#

When I release premium features I want to give the first x servers that purchase it an additional month free. Is there any way to do this without telling the user to make sure their membership doesn’t renew? I was planning on giving them a test entitlement after the first month has passed

maiden bloom
lofty parcel
#

Monetization is still very simple

sage tendon
#

The experiment is being killed in favour of the features being added as regular server features

#

and good riddance imo

torn barn
#

those are member application forms that were used for clans

#

just, for normal guilds

lapis dock
torn barn
#

i know because i've made a clans pr for dpy and i had to do objects for it

lapis dock
#

just to clarify when I said "added to the API" I meant the documented bot accessible API

sage tendon
#

what the fuck is that link

lapis dock
#

for the userdoccers, unofficial community discord docs

lapis dock
fresh sierra
#

is this intended ?
💥Exception: can't subtract offset-naive and offset-aware datetimes

days_in_guild = (datetime.datetime.utcnow() - member.joined_at).days
days_account_age = (datetime.datetime.utcnow() - member.created_at).days
#

shouldnt they both be the same ?

sage tendon
#

do both cause that error

fresh sierra
#

thats why im a bit surprise, why would they be different

sage tendon
#

probably because one is from user and one from member

#

and joined_at says its an aware datetime object

#

created_at doesnt

fresh sierra
#

i dont really see why one would ned to be aware and the other naive

lapis dock
#

This is what is seems like is happening. Discord is sending a timezone aware string for one of the fields but not the other. It is probably best to just get the UTC time of whatever is returned

errant trout
#

oversight, created_at uses utils.snowflake_time while joined_at uses utils.parse_time

lapis dock
#

which is prefered? Snowflake time I assume?

errant trout
#

well snowflake_time is for converting snowflakes, parse_time is for time strings

#

i.e. created_at just converts the user ID

#

parse_time uses fromisoformat which calculates the timezone from the included offset

echo wraith
#

-remindme 1d fix this datetime thing

lofty vaultBOT
#

Set a reminder in 1 day from now (<t:1740694004:f>)
View reminders with the reminders command

shell radish
#

ironic that it sends a datetime to fix a datetime

echo wraith
#

Yeah

fresh sierra
#

trying to fix for 1h a bug when there is no bug, you just forget that you fucking set a forbidden role and mandatry role features......

lapis dock
silk spire
#

Also, datetime.utcnow() is deprecated and removed in 3.13(?)

raw beacon
#

its just .now() now

echo wraith
#
from datetime import datetime, UTC

datetime.now(tz=UTC)
silk spire
#

still deprecated in 3.13?

echo wraith
# fresh sierra nah, the joined_at only

Both cause the error for me, and the issue is not on pycord's side afaik. It is datetime.utcnow() that is naive, not created_at or joined_at. You should use datetime.now(tz=UTC) as I exemplified above.

echo wraith
#

-reminders clear

lofty vaultBOT
#

Your reminders in this server:
113661592: #1132206148309749830: 'fix this datetime thing' - in 13 hours and 51 minutes from now (<t:1740694004:f>)

Remove a reminder with delreminder/rmreminder (id) where id is the first number for each reminder above.
To clear all reminders, use delreminder with the -a switch.

echo wraith
#

-delreminder -a

lofty vaultBOT
#

Cleared 1 reminders

fresh sierra
echo wraith
#

Like

#

joined at is most likely returned as an iso time string from discord's api

#

while joined at is not returned, it is the time embedded into the user id

fresh sierra
#

Ok I see

sour widget
#

I am a bit confused, when I do this

    async def reminder_cmd(self,
                           inter: discord.ApplicationContext,
                           name: str = discord.Option(input_type=str, required=True, description="The name of the reminder.", name="name"),
                           time: str = discord.Option(input_type=str, required=True, description="The time of the reminder, for better description use `/help time_formats`", name="time"),
                           description: str = discord.Option(input_type=str, required=False, description="The description of the reminder.", name="description"),
                           file: discord.Attachment = discord.Option(input_type=discord.Attachment, required=False, description="Any file", name="file"),
                           ):

the file looks like this (screenshot 1)

when I do this

file: discord.Attachment = discord.Attachment,

attachment works correctly, but it is said that description is not provided, so I think it is possible to do. And Attachment is a valid argument for the input_type parameter in Option() so I am confused what I am doing wrong

#

I can just use decorators, but maybe I made a silly mistake somewhere here

sage tendon
#

do you know how python works lol

#

Your issue is that you need to typehint the options, not set them as defaults
you are doing var = discord.Option(...) but you need to do var: discord.Option(...)

#

regardless i'd recommend using the decorator variant of defining options, personally
its much cleaner in the code, and less prone to errors imo

#

also, the first argument should be ctx, not inter (kind of conventional in pycord)

#

@sour widget

little cobalt
#

why is there a = and not a : ?

sage tendon
#

thats exactly the issue i just explained lol

sage tendon
#

also, just a tip, required is True by default, and you dont need to pass the name if its the same as the argument name (this is only true for the typehint version tho)

lapis dock
#

-# I dont know if it works for all types but I am pretty sure that arg = Option(...) is valid

sage tendon
#

it shouldn't be for all I know

wheat tiger
silk spire
nocturne jewel
#

discord is having any issue with connection?

sage tendon
#

no

wheat tiger
#

but wasn't able to find that

sage tendon
#

find what

wheat tiger
#

Discord API provides the endpoint

#

(read the docs)

sage tendon
#

"but pycord doesnt support any of that yet"

wheat tiger
#

¯_(ツ)_/¯

#

that's what I meant

sage tendon
#

yea but like what do you want lol

#

pycord doesnt support it

wheat tiger
sage tendon
#

i figured

wheat tiger
# sage tendon i figured

So the feature is somewhat like this. I am making a quotes channel setting, when someone forwards the msg (if it's a forwarded msg) it will fetch the msg metadata and will make a ss out of it by using Pillow

sage tendon
#

yea thats great and all but pycord doesnt support it

wheat tiger
sage tendon
#

try print(message.flags.value << 14)

#

if that works for a forwarded message tell me

wheat tiger
#

how will I fetch the metadata?

#

the forwarded msgs' content, author data, time etc...

#

Only stress-free and possible way is to wait till pycord implements it. Or I gonna make pr

sage tendon
#

and no, you wont be able to unless you make a raw api request i think

#
if message.flags.value & (1 << 14):
    # Message was forwarded
else:
    # Message wasn't forwarded
#

@wheat tiger ^^

wheat tiger
#

I just need to wait ¯_(ツ)_/¯

errant trout
#

the forwarded message's data will be under the message_snapshots key

#

next release is not too far off, after which it'll be under message.snapshots

#

(and it will also include Message._raw_data if you ever need that in future; you could also add this yourself by updating message.py if you don't want to fetch every time)

sage tendon
#

why is it called snapshot?

errant trout
little mirage
#

hello! is it acessible?

sage tendon
#

only the first one

nocturne jewel
#

how to use options with custom options for every server?

#

like "operator" for

server 1: add, remove
server 2: multiplicate, divide

lofty parcel
#

You mean the option displays different choices for each server?

lofty parcel
nocturne jewel
lofty parcel
#

Ok

#

You just explained how to do it

#

What's not working?

nocturne jewel
#

nevermind

wheat tiger
#

Hmm I can use it pepe_star

lofty parcel
#

You were always able to send http requests by yourself

wheat tiger
#

But using pycord, I didn't notice doing that

lofty parcel
#

Yes...

wheat tiger
#

Ig till next release I can do this way ctk_dance

lofty parcel
wheat tiger
lofty parcel
#

That's what the library does...

#

.http is just the module that handles all the requests

wheat tiger
lofty parcel
#

I'm confused

wheat tiger
# lofty parcel I'm confused

See, what I thought it, when they need to make some request they must be using the request module or asyncio module in that specific function, but I never realised that they made a unified class containing methods using which we can do http requests

#

Hope you understood pepeheart

#

I was just lazy enough to dig in the package Ah_kek

lofty parcel
#

It still uses aiohttp to make the request

#

You're just seeing the abstraction of the request

#

.request is a method of the HTTPClient, if you dig through it, you will see it handles the request and uses aiohttp

rugged lodgeBOT
lofty parcel
#

self.__session being an aiohttp.ClientSession

errant trout
#

allgood

wheat tiger
#

when not forwarded it returns None

#

else it returns the metadata

errant trout
#

pretty much yeah

fresh sierra
#

is ctx.user or ctx.author the dominant ?

lofty parcel
#

They're the same

rugged lodgeBOT
echo wraith
#

I'd say user just becaue both are a shortcut for Interaction.user

#

but it's more a preference than anyhting

errant trout
#

ctx.author is because it came from ctx.message.author, while interaction has user instead; hence both exist

lofty parcel
#

✨ evolution✨

shell radish
maiden bloom
#

Is the only way to determine if an entitlement is a test one, is to try to delete it?
I think both purchased and test entitlements have the application_subscription EntitlementType

nocturne jewel
#
@bot.slash_command(description="blablabla")
@option("choice", description="blabla", autocomplete=True)
async def choose(ctx: discord.ApplicationContext, product: str):
    await ctx.respond(f"you choose: {product}")


@choice.autocomplete("choice")
async def product_autocomplete(interaction: discord.Interaction, current: str):
    base_url = "https://api.example.com/"
    getshop_url = f"{base_url}?method=getlist"
    shop_response = await fetch_url(getshop_url)
    choices = []
    if shop_response is None or type(shop_response) is not list:
        return choices
    for item in shop_response:
        if current.lower() in item.lower():
            choices.append(discord.app_commands.Choice(name=item, value=item))
    return choices

Traceback (most recent call last):
  File "test.py", line 2891, in <module>
    @chooice.autocomplete("choose")
AttributeError: 'SlashCommand' object has no attribute 'autocomplete'

Hm

nocturne jewel
lofty parcel
#

Remove the decorator on the autocomplete func

#

Pass the function to the choice

#

autocomplete=product_autocomplete

nocturne jewel
#

lemme try

sage tendon
#

and also, autocomplete takes AutoCompleteContext, not Interaction, and no other parameters

#

and the thing at the bottom with discord.app_commands Blabla, that's discord.py. This is pycord.

#

@nocturne jewel

#

your ide should've told you that that doesn't exist in Pycord

silk spire
#

Probably AI combining codes of multiple libs since it doesn't know better

sage tendon
#

i can guess stuff myself too

#

i asked them.

nocturne jewel
#

It gave me the idea

#

I also use discord.py and pycord in 2 different environments so it's a bit confusing

sage tendon
#

you really shouldn't do that
for your own sake

ivory wind
#

hello, i have a task that's supposed to go off at 4:20pm but it's 4min early

eastern = pytz.timezone('US/Eastern')
...
@tasks.loop(time=time(hour=16, minute=20, tzinfo=eastern))
...

system time is right. i don't know what it could be

sage tendon
#

what if you print time.now() in the task and check which time exactly the timestamp resolves to

ivory wind
#

2025-03-02 16:36:28,422 - cogs.four_twenty - INFO - 2025-03-02 16:36:28.422396

#

looks right to me

sage tendon
#

hm

lapis dock
#

are you sure your system time is correct? Does it show as 4:16 for others as well?

ivory wind
#

@tasks.loop(time=time(hour=16, minute=42, tzinfo=eastern))

sage tendon
ivory wind
#

date
Sun Mar 2 16:41:53 EST 2025

sage tendon
#

your system time

#

yours

ivory wind
#

it is

sage tendon
ivory wind
#

it worked when I did it in utc. switched to eastern to handle daylight savings better

#

@tasks.loop(time=time(hour=20, minute=20, tzinfo=timezone.utc))

ivory wind
#

thanks. i'll try it later

lapis dock
#

yeah pytz is not recommended to be used for python 3.9+

ivory wind
#

TIL

#

thank you, it worked

lapis dock
#

would not be supprised if it had something to do with leap days/minutes/seconds/etc

slow gazelle
#

if i want to create a group of commands, for example /game trivia and /game akinator, but have the code of each command in a different file, what would be the best way to do it?

echo wraith
#

.tag multicog

sly karmaBOT
#

Tag not found.

sage tendon
#

pycord in itself does not support what you want, you need that extension

echo wraith
#

Or you'd do it manually but yeah

sage tendon
#

don't think that's easy

echo wraith
#

Yeah no it's not easy

errant trout
#

it would be if you disable syncing

#

i.e. if you subvert the library's command system, you can just setup interaction listeners

#

but you're actively fighting against the lib at that point

shell radish
atomic fern
#

is there an event for on guild boost?

echo wraith
#

afaik this

#

on_guild_update

#

but i'm not 100% cretain one would have to test

#

or wait for smbd else to confirm

hazy turret
#

Hello,

does anyone have any idea how long the Discord server-side cache lasts?
When I embed an image into an embed via URL, the image is cached with the URL from Discord. When I upload another image to the same URL, the old image is still displayed instead of the new one. The new one is only displayed when the URL changes.
Has anyone had any experience with this or knows how long the cache lasts? Or is there any way to delete or reset the cache?

echo wraith
silk spire
#

1 day.

#

Oh wait that's for attachment urls

#

Not the whole cdn

lapis dock
echo wraith
hazy turret
echo wraith
edgy nest
#

imagecdn/image?wefhreuighkrejn

round heart
#

Since reloading slash commands doesn't change the behavior of the command function (vs text commands), how do you guys structure your Cogs? Do your slash command do nothing but respond, and you have some other function/layer that actually does whatever magic needed (including building the response e.g. embeds)?

fresh sierra
#

If you reload a cog and then sync command the change will be reflected

round heart
#

meh. is there an atomic sync, or do I have to sync everything?

sage tendon
#

My commands contain all code they need unless its very unrelated to the command, duplicated, or stuff like DB handling

round heart
#

When developing, I might have to refresh things several times since there's often no way to simulate things without actually doing them

fresh sierra
#

As long as u sync it

sage tendon
#

why do you need to reload the cog tho, a restart is painless

round heart
fresh sierra
#

Only issue is if ur edit the bot class or u need to add a shard

#

It takes a lonnnng time

round heart
#

Hm. Looks like I had this commented out.

    @commands.command(name='reload', hidden=True)
    @commands.is_owner()
    async def owner_cog_reload(self, ctx, *, cog: str):
        """Command which Reloads a Module.
        Remember to use dot path. e.g: cogs.owner"""

        try:
            self.bot.reload_extension(cog)
            # await asyncio.sleep(1)
            # await self.bot.sync_commands(force=True)
        except Exception as e:
            await ctx.send(f'**`ERROR:`** {type(e).__name__} - {e}')
        else:
            await ctx.message.add_reaction('👍')
#

Maybe it was broken in a previous version of pycord

fresh sierra
#

But I feel like an update command which would reload all cog + sync command would be more efficient

#

Because you rarely edit only 1 command

sage tendon
#

i think you rarely edit more than one command at once lol

fresh sierra
#

So always some big update

round heart
#

For context, I was talking about reloading the cogs for the test bot. I don't mind restarting a prod bot for larger changesets.

fresh sierra
opal swan
#

hi everyone, can we send a dm to someone with await bot.fetch_user() ?

silk spire
#

Sure? As long as they share a server with the bot or have it installed to their profile

lapis dock
#

and they have DMs for that server turned on

lapis dock
round heart
lapis dock
#

afaik syncing commands has no effect on the actual callback of the command

#

But i trust you, it is probably a bug

round heart
#

The suck part for my current task is that when I reload my cog, this Web Client that I have loses its authentication for some reason. It calls out for the handshake and I never get a cookie the second time around. (Completely not Pycord related, just venting)

marble thistle
#

Does anyone know why when I call a bot.get_all_members then sort through member nick names the nicknames are missing on several people who indeed have nicknames on the server?

lapis dock
#

Never seen anyone use that function before 😅
Assuming it follows convention get_x returns cached things. So if the members nick changed after it was cached and the bot never received this update then it will be the old value

raven breach
#

When we use stop_recording() where does it save it?

fresh sierra
eternal kite
#

can embeds have image and thumbnail at the same time?

lapis dock
#

yes

eternal kite
#

i attached two files with different names, and passed the arg files=[file1, file2] but it seems like file1 overwrites file2

lapis dock
#

can you show that snippet of your code please

nocturne jewel
#
async def finished_callback(sink, *args):
    text_channel = bot.get_channel(123)
    if text_channel is None:
        try:
            text_channel = await bot.fetch_channel(123)
        except Exception as e:
            print(f"Error: {e}")
            return

    recorded_users = [f"<@{user_id}>" for user_id in sink.audio_data.keys()]

    await sink.vc.disconnect()

    files = [
        discord.File(audio.file, f"{user_id}.{sink.encoding}")
        for user_id, audio in sink.audio_data.items()
    ]
    await text_channel.send(files=files)

@bot.event
async def on_voice_state_update(member, before, after):
    if member.bot:
        return

    if after.channel is not None and after.channel.category is not None:
        if after.channel.category.id == 123456:
            if member.guild.id not in connections:
                vc = await after.channel.connect()
                connections[member.guild.id] = vc
                sink_instance = discord.sinks.MP3Sink()
                vc.start_recording(sink_instance, finished_callback)
                print(f"Started recording in '{after.channel.name}'")
            else:
                vc = connections.get(member.guild.id)
                if vc.channel.id != after.channel.id:
                    await vc.move_to(after.channel)
                    #pass

    if before.channel is not None and before.channel.category is not None:
        if before.channel.category.id == 123456:
            vc = connections.get(member.guild.id)
            if vc is not None and vc.channel.id == before.channel.id:
                await asyncio.sleep(1)
                non_bot_members = [m for m in vc.channel.members if not m.bot]
                if len(non_bot_members) == 0:
                    vc.stop_recording()
                    del connections[member.guild.id]
                    print(f"Stopped recording in '{before.channel.name}'.")

#

Exception in thread Thread-43 (recv_audio): Traceback (most recent call last): File "/usr/lib/python3.10/threading.py", line 1016, in _bootstrap_inner self.run() File "/usr/lib/python3.10/threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python3.10/dist-packages/discord/voice_client.py", line 863, in recv_audio self.unpack_audio(data) File "/usr/local/lib/python3.10/dist-packages/discord/voice_client.py", line 740, in unpack_audio data = RawData(data, self) File "/usr/local/lib/python3.10/dist-packages/discord/sinks/core.py", line 115, in __init__ self.decrypted_data = getattr(self.client, f"_decrypt_{self.client.mode}")( File "/usr/local/lib/python3.10/dist-packages/discord/voice_client.py", line 611, in _decrypt_xsalsa20_poly1305_lite return self.strip_header_ext(box.decrypt(bytes(data), bytes(nonce))) File "/usr/local/lib/python3.10/dist-packages/discord/voice_client.py", line 615, in strip_header_ext if data[0] == 0xBE and data[1] == 0xDE and len(data) > 4: IndexError: index out of range

#

is that normal?

#

i was trying to record a voice channel when for 10-20 seconds records it works, for longer like 2 minutes not

upper slate
#

Anyone know a way to jig it so that sending a voice channel invite to a user not already in the guild allows you to update overwrites for this user before they open the invite?

errant trout
lapis dock
nocturne jewel
errant trout
#

uhh isn't it because we didn't merge the encryption changes

nocturne jewel
lapis dock
#

The new system should work as an alternative but not actually fix this problem from what I can tell

obsidian stratus
#

😅

sage tendon
#

are you using on_message_delete ?

errant trout
obsidian stratus
obsidian stratus
#

Uptime being 3 days+ but still failing to log 15 min old messages being deleted by a moderator manually (not purged)

sage tendon
wary silo
#

does MessageType.application_command always have webhook id?

ebon swift
#

when using member.add_roles() , how do I use the snowflake feature to put multiple roles as parameters ?

def gives_necessary_roles(guild: Guild, member: Member):
    role1 : RoleTags|None = discord.utils.get(guild.roles, name="role1")
    role2 : RoleTags|None = discord.utils.get(guild.roles, name="role2")
    member.add_roles(???) #how to add both roles at once ?
sage tendon
#

await member.add_roles(role1, role2)

#

but getting roles by name is bad practice

#

if you already know the specific roles you want, just hardcode the IDs into the add_roles command

ebon swift
#

thank you

#

also about the role name I understand role ids are better, I'll switch to that soon

sage tendon
#

and then you should use guild.get_role

ebon swift
#

thank you for those better practice

obsidian stratus
#

On message works perfectly, I have intents.all enabled

sage tendon
#

and what if you send a message then delete it

strange oracle
#

I used pip install py-cord[voice] but cant seem to access anything from discord.sinks. Even in the example

from discord.sinks import MP3Sink```

I get

Exception has occurred: ModuleNotFoundError
No module named 'discord.sinks'
File "/home/mojobojo/dev/discoword/voice-recorder-test/vr.py", line 4, in <module>
from discord.sinks import MP3Sink
ModuleNotFoundError: No module named 'discord.sinks'```
Anyone have an idea why that could be?

lapis dock
#

can you make sure you have no other discord bot libraries installed. If you do uninstall them and reinstall pycord

nocturne jewel
#
@bot.group()
async def afk():
    pass

@afk.command()
async def set():
    ...

@afk.command()
async def remove():
    ...```

How to do this with ```python
@bot.slash_command```?
lapis dock
lapis dock
ebon swift
#

Hello

is there a way to make the listener, on_application_command execute and finish before the application command start ?

I made a listener so I can see who invoked a command and what command they used

@discord.Cog.listener()
    async def on_application_command(self, ctx: commands.Context):
        log.debug(f"Received command: {ctx.command} was invoked by {ctx.author}")

and any command like :

@commands.slash_command(name="ping", description="Check if the bot is alive.")
    async def ping(self, ctx: discord.ApplicationContext):
        log.info(f"LOGGING A MESSAGE")
        await ctx.respond(f"Pong! thanks for checking on me {ctx.author.mention} !")

when a user call the /ping command I get:

DATE TIME | INFO | LOGGING A MESSAGE
DATE TIME | DEBUG | Received command: pong was invoked by user

but it feels like its behaving as if I was using on_application_command_completion since this message always appears after a command completion.

edgy nest
#

if you want it to absolutely run before every time, you could make a global check

#

there might also be a before_application_command method

lapis dock
errant trout
# nocturne jewel thank you

i mean, it definitely runs before ```py
self._bot.dispatch("application_command", ctx)
try:
...
await ctx.command.invoke(ctx)
...
except DiscordException as exc:
await ctx.command.dispatch_error(ctx, exc)
else:
self._bot.dispatch("application_command_completion", ctx)

#

(ironically, before_invoke is after on_application_command)

#

it might feel like the other way round because before_invoke and similar functions have to finish before the command runs, but the event doesn't

edgy nest
#

runs out of order

errant trout
#

yeah i mean that was my point, the event is dispatched before invoke but it's possible to finish after unlike the other methods that actually block

obsidian stratus
#

Simple messages with just message content

#

It’s only not working when the message is like 15 mins old

It works sometimes but it’s unreliable

strange oracle
#

yep, so was just a messed up virtual environment. dunno why I didnt think of that. thanks for putting my brain in the right space.

ebon swift
#

I can't figure out how to do it globally

lofty parcel
frail basin
#

Make sure to always return True, else the command wont run.

ebon swift
#

will try that rn !

#

works like a charm thank you so much !

#

if anyone ever needs the same feature here is my code

class Events(commands.Cog):
    def __init__(self, bot: discord:Bot):
        self.bot = bot
        self.bot.add_check(self.__log_command_call)


    async def __log_command_call(self, ctx: ApplicationContext):
        log.debug(f"Command {ctx.command} called by {ctx.author} in {ctx.guild}.")
        return True
lapis dock
ebon swift
fresh sierra
ebon swift
#

aren't commands and slash commands different ?

fresh sierra
ebon swift
#

on applicaiton command shows after my command has been executed

sage tendon
#

so what about on_command

lapis dock
fresh sierra
#

It’s fire at the same time I think

ebon swift
#

yes

fresh sierra
#

Because completion is the one after

ebon swift
#

at the same time

fresh sierra
#

Or is it after and completion is only if there is no error

ebon swift
#

but I would rather have my log be always printed before the command is executed which makes the stack more readable

sage tendon
ebon swift
ebon swift
fresh sierra
sage tendon
fresh sierra
#

So why are you not using bot.before invoke

fresh sierra
sage tendon
#

yes it will

#

read the fucking docs

lapis dock
ebon swift
# sage tendon .

is on command sure to be called before the execution of the command ? I may have mis understood the difference between a command and an application command ? I thought application command = slash command and command is the hold <PREFIX> command

sage tendon
#

read and try

#

i cant tell you more than that

fresh sierra
lapis dock
#

^

fresh sierra
#

So if the thing takes more time it will likely break

ebon swift
#

for the bot before_invoke, I feel like I miss coded it, does it also requires to have a return True at the end ? cause that might have been my mistake

sage tendon
fresh sierra
ebon swift
#

I'll try all the solutions and let you know

fresh sierra
#

And dispatch is async

#

So it might run out of order and so after the command has been invoked

ebon swift
#
class Events(commands.Cog):
    def __init__(self, bot: discord.Bot):
        self.bot = bot
        self.bot.add_check(self.__log_every_command)

    async def __log_every_command(self, ctx: ApplicationContext):
        log.trace(f"Command {ctx.command} called by {ctx.author}. ADD_CHECK_METHOD")
        return True

    @discord.Cog.listener()
    async def on_command(self, ctx: ApplicationContext):
        log.trace(f"Command {ctx.command} called by {ctx.author}. ON_COMMAND")

    @discord.Cog.listener()
    async def on_application_command(self, ctx: ApplicationContext):
        log.trace(f"Command {ctx.command} completed by {ctx.author}. ON_APPLICATION_COMMAND")
    
    # gives me : Extension 'cogs.events' raised an error: AttributeError: module 'discord.bot' has no attribute 'before_invoke'
    # @discord.bot.before_invoke
    # async def before_invoke(self, ctx: ApplicationContext):
    #    log.trace(f"Command {ctx.command} called by {ctx.author}. BEFORE_INVOKE")
...
class Fun(commands.Cog):
    def __init__(self, bot: discord.Bot):
        self.bot = bot

    @commands.slash_command(name="ping", description="Check if the bot is alive.")
    async def ping(self, ctx: ApplicationContext):
        log.info("Pong!")
        await ctx.respond(f"Pong! thanks for checking on me {ctx.author.mention} !")

09/03/2025 15:52:44:44 | TRACE | Command ping called by lolozen (ZEN). ADD_CHECK_METHOD
09/03/2025 15:52:44:44 | INFO | Pong!
09/03/2025 15:52:44:44 | TRACE | Command ping completed by lolozen (ZEN). ON_APPLICATION_COMMAND

#

so before invoke doesn't work, but I assume I'm not using it right
my slash command isn't considered as a command of on_command()
and on_applicaiton_command shows up after my log aeverytime (might be because it's ran in parallel)

sage tendon
#

hm

ebon swift
sage tendon
#

yea lol

#

you need to use your botvar, not the discord.bot module lol

#

discord.bot just refers to the bot.py file inside pycord

ebon swift
#

hooo I need to use it like I did with the add_check ?

lapis dock
#

yes, i think so

ebon swift
#

trying it rn, but just out of curiosity, why is it better than add check ?

sage tendon
#

just

@bot.before_invoke()
async def logging(...):

must be in your main bot file i believe

sage tendon
#

before invoke is for all kinds of tasks that have to run before a command is invoked

ebon swift
#

well this works perfectly

#

thank you

#

I didn't put it in my main since I like to keep it in my event cog but it works perfectly still

sage tendon
#

yea i wasnt sure if you can use self.bot in the decorators in a cog

#

show how you did it

ebon swift
#
class Events(commands.Cog):
    def __init__(self, bot: discord.Bot):
        self.bot = bot
        self.bot.before_invoke(self.__log_every_command)

    async def __log_every_command(self, ctx: ApplicationContext):
        log.trace(f"Command {ctx.command} called by {ctx.author}. BEFORE_INVOKE")
sage tendon
#

ah

#

in the docs it says its a decorator but ig you can use it like that too

ebon swift
#

when my cog is initiated it sets the before invoke to the bot

sage tendon
#

also you shouldn't put a double underscore infront of it, single underscore is convention for private stuff

ebon swift
#

repalcing all my double underscore ^^

sage tendon
#

we aren't in java lol

ebon swift
#

😭

#

I'm jsute trying to be a good dev

#

lol

sage tendon
#

dunder methods are things like obj.__string__

ebon swift
#

okay thank you 🙂

sage tendon
#

and those are afaik the only methods that should use double underscores

ebon swift
#

alringt !

#

did a gloabl replacement ^^

#

well thank you all for your reactivity and for your help !

sage tendon
#

np

lapis dock
#

__ only in front is used in some non-dunder places, idk that much tho

lapis dock
ebon swift
#

I'll dig in and make research, but will stick to simple underscore for private from now on

sage tendon
#

but thats kind of a weird thing

lapis dock
#

Ah yeah, forgot about that it feels so gross I dont know why you would ever use it

fresh sierra
#

Without anything else ?

fresh sierra
ebon swift
#

we figured it out yes ^^

#

and it works perfectly

fresh sierra
#

Perfect

sage tendon
ebon swift
#

ho yes you're right

#

for now it's okay caus emy bot will onyl be on one server

#

but I will have to think about a guild filter

lofty parcel
quartz umbra
#

is it possible to make a bot which can be added to a user profile using pycord?

sage tendon
#

yes

rugged lodgeBOT
#

Here's the slash users example.

quartz umbra
sage tendon
#

you get a lot less info in slash commands, like basically no guild attribute access etc

quartz umbra
#

oh so i added this bot I made to my profile but I can't use any of its slash commands in dms?

sage tendon
quartz umbra
#

yeah I think I just overlooked the fact you need to set the integration types

lapis dock
#

Coding wise it is not that much different, but like toothy said you just get a lot less information sent by discord

lofty parcel
quartz umbra
#

Hi! is it possible for a bot to upload emojis to a guild? If so, how do you do it in py-cord because I only see create_sticker while the argument is called emoji so it's a bit confusing

echo wraith
rugged lodgeBOT
echo wraith
#

use this

quartz umbra
#

tysm

echo wraith
#

np

quartz umbra
#

is Attachment.to_file().fp a byte-like object?

sage tendon
#

what does your IDE say?

quartz umbra
#

I use vscode so nothing 0-0

echo wraith
#

btw it's await

#

so

#

(await attachment.to_file).fp

sage tendon
frail basin
echo wraith
#

yes

#

afaik

frail basin
#

so I could, in theory (await fetch_...()).attr ?

#

Thats useful to know

sage tendon
#

That's the only way to do such things in one line

#

because if not for the brackets you would await the .attr

lofty parcel
#

Python moment

sage tendon
#

no, completely logical

lapis dock
#

One thing I wish python had was bot?.user?.id which I think just returns None if bot or user are None instead of throwing a NoneType error

frail basin
#

Is the ? even an operator in python?

frail basin
lapis dock
#

dont think so

#

not in that context at least

fresh sierra
#

make so much sens ;)

errant trout
#

that was proposed in PEP 505 , but it's a pretty controversial topic amongst the maintainers and ended up being deferred

lapis dock
#

yeah I just found that now

fickle salmon
fresh sierra
fickle salmon
#

oh

silk spire
fallow crescent
#

Hi py-cord friends. Is there a way to access a guild member's signals as it's displayed in the discord members window? I want to notify myself when a member's suspicious behavior or excessive DMs signals go up.

#

I thought it might be some undocumented bit in the public_flags field but that doesn't seem to always be the case

silk spire
#

There are undocumented fields on the Member object that discord doesn't want bots to use iirc yes

fallow crescent
#

Undocumented fields that make it to py-cord's Member representation?

silk spire
#

No, libraries usually don't add undocumented fields as they can be unstable

echo wraith
tiny shard
#

Hello, I have an issue with my bot that is in 1 guild with 350k members. I want to receive on member join event only. I enabled intents.members however this makes my bot's RAM usage jump from ~50MB to almost 500MB. Disabling cache with bot = discord.Bot(intents = intents, member_cache_flags = discord.MemberCacheFlags.none()) didn't decrease the ram usage. Any help?

fresh sierra
#

Or else it can just be normal, if you have to receive intents from 300k members that’s a lot

little cobalt
errant trout
sage tendon
fallow crescent
sage tendon
#

yes

silk spire
round heart
#

Not pycord-specific, but I've always been curious about this. What's the "correct" way to define a property on your class without the ide whining that you typed it but it's initially None?

It's not really optional, I just have to pre-define before it actually gets used it so I don't get errors when I do.

errant trout
#

i mean

#

that's up to your typechecker, no?

lofty parcel
#

Just turn it off

#

Boom

#

No more issues

lapis dock
#

I just dont until it is set and leave a typehint at the class level

class A:
  hi: int
  def set(self, h: int):
    self.hi = h
a1 = A()
a1.hi # This returns an attribute error
a1.set(4)
a1.hi
round heart
#

Yeah it's stupid that you can typehint it with no value but IDE thinks it's not defined.

errant trout
#

i haven't opened pycharm like a year, all my pycord work is done on github.dev (vsc) with basic autocomplete and my bot work is in my server's web panel (lol)

silk spire
#

Just hi: int = None # type: ignore KEKW

it technically isn't defined. Without a value it's just an annotation that's added to the dict (cls.__annotations__)

echo wraith
#
class Foo:
    _hi: int | None = None

    @property
    def hi(self) -> int:
        if self._hi is None:
            raise AttributeError("bleh")
        return self._hi

    def set(self, v: int) -> None:
        self._hi = v
#

smth like that

silk spire
#

That's how not-lazy people do it yeah

#

hi could have a setter instead of the separate method but eh

echo wraith
#

yeah I did that at first

#

but then saw Wolfy's example with set

#

so I wanted it to be similar

silk spire
#

Ah

round heart
#

I have like a dozen props that need to be added this way; I’m not defining getters for them all, that’s silly

#

It’s stupid that you must define properties in init, and yet throw a warning if you assign to None initially because it’ll be updated later

silk spire
#

Do you perhaps want a dataclass

silk spire
#

What if the value is never assigned? The type checker would be lying atp

#

And a: int = None being invalid makes sense too

None is NOT an integer

round heart
#

Because it makes sense that not every property will be assigned at init. For instance a response from an api that the runtime of the class relies on

silk spire
#

It doesn't need to be assigned at the init

#

It can be in a method too that's called by you

#

The type checker will know that

round heart
#

But it does because if you set it outside of init, that’s technically wrong because it doesn’t exist. At least according to PyCharm

#

Plus I need to know it if it’s referenced in other classes. I imagine dynamic setting wouldn’t autocomplete

silk spire
#

Well yeah defining it outside without a value means it doesn't exist at runtime

#

Sounds like you want a dataclass

silk spire
#

You can assign the attrs all in the class and it will assign them when you construct the class

round heart
#

But I don’t? In my cogs, I want to be able to reference self.bot.object_from_api. There are several of them, and they’re collected at different times (or at least need to be accessible before others are set)

echo wraith
#

I mean

#

wait youre saiying if you only type them pycharm will complain ?

silk spire
#

Oh god

echo wraith
#
class E:
    hi: int
silk spire
#

Is pycharm that stupid

echo wraith
#

Idk I use basedpyright so I don't really know

silk spire
#

Does that take over the built in checker?

echo wraith
round heart
silk spire
round heart
#

I think that works (not at my computer). It’s when I define self.hi in init that it complains

echo wraith
#
from typing import reveal_type

class Foo:
    bar: int # Instance variable "bar" is not initialized in the class body or __init__ method  (reportUninitializedInstanceVariable)

foo = Foo()

reveal_type(foo.bar) # Type of "foo.bar" is "int"
#

this is w/ basedpyright link

round heart
#

If I self.hi: int = None it complains on type. If I self.hi: int, then it acts like it’s not an available instance var when you try to reference it

echo wraith
#

cause it shouldn't

round heart
#

When I’m back at my computer I’ll write out a test class with all the different ways

silk spire
#

self.hi: int isn't valid and complaining about assigning int to None makes sense tho?

#

Oh not available

round heart
#

How is it not valid? wtf

echo wraith
#

I think if you don't assign a value to a classvar pycharm will ignore it that's the thing here

silk spire
#

thing.thing: T isn't valid, at least with pyright

echo wraith
silk spire
#

x: T = thing.thing is

errant trout
#

(func name doesn't matter)

#

(i did not read the rest but idk why you would bother doing .set instead of overloading)

echo wraith
#

But that's what my original example did

#

Whatever

round heart
# round heart If I `self.hi: int = None` it complains on type. If I `self.hi: int`, then it ac...

Weird. If I set a simple class

class TestClass:
    def __init__(self):
        self.b: int

    def test(self):
        self.b = 2

There doesn't seem to be any issue with defining it this way; Pycharm does not complain.

But it treats my actual code differently...

class MyBot(commands.Bot):
    def __init__(self):
        self.http_session: aiohttp.ClientSession
        ....

    async def set_http_clients():
        self.http_session = aiohttp.ClientSession(...)

Setting it whines Instance attribute http_session defined outside __init__ . It doesn't if I make it a class attribute, but I admit I don't really understand where you'd use one or the other.

sage tendon
#

I think class attributes apply globally to the entire class and all of it's objects

round heart
#

Which for the bot would only be once, so I assume that shouldn't matter in this specific case.

But I still don't get why instance properties are being treated differently here. In my TestClass I can reference it fine outside of init, but not in the bot

sage tendon
#

because the bot class uses slots, i think

ebon swift
#

I need some help, when I do a guild.members, some user on my server are not listed, does anyone have any idea where this might come from ?

echo wraith
#

but no idea

ebon swift
#

is there a way for me to go around that ?

lofty parcel
#

Fetch the users

ebon swift
#

I should use guild.chunk() then ?

sage tendon
ebon swift
#

Sorry if I'm not getting this correctly I want to fetch all the user from the guild

#

I don't get their id in the first place

sage tendon
ebon swift
#

just restarted it

sage tendon
#

give it like a minute or two

ebon swift
#

I see

#

it's disturbing me a bit since I'm trying to do a db sync on startup

sage tendon
#

no i mean try that, im not sure if thats the issue

ebon swift
#

I'll try to sync it ig

ebon swift
#

very strange

errant trout
#

how many members are we talking

ebon swift
#

this:

@commands.Cog.listener()
    async def on_ready(self):
        """
        Event that is called when the bot is ready.
        Returns:
        """
        self.bot.main_guild = self.bot.guilds[0]
        members = await self.bot.main_guild.fetch_members(limit=None).flatten()
        user1 = self.bot.main_guild.get_member(48<...>00)
        user2 = self.bot.main_guild.get_member(33<...>25)
        user3 = self.bot.main_guild.get_member(82<...>72)
        user4 = self.bot.main_guild.get_member(69<...>58)
        loguru.logger.debug(f"{user1} | {user2} | {user3} | {user4}")

gives me:
11/03/2025 21:33:21:56 | DEBUG | None | None | None | None

#

4

errant trout
#

i mean in the entire guild

ebon swift
#

on a server of less than 50

errant trout
#

hm

ebon swift
#

I can't find something in common between all of them

#

my bot is also administrator

#

and I gave it : discord.Intents.all()

#

(yes not best practice its for the tests)

errant trout
#

fetch_members doesn't fill cache so it's pointless there, but if you have all intents it should cache all members at startup anyway

#

(unless you disabled it in your Bot class)

ebon swift
#

doesn't feel like I did

errant trout
#

seems fine

#

does your bot have a custom init

#

also pretty normal...

ebon swift
#

I know

#

I mean

echo wraith
#

does your bot override any metjopds

#

or what methods does it implement

ebon swift
#

that's what is making me really lost

errant trout
#

if you really want, await guild.chunk() should fill your cache

#

but if even that isn't working discord might just be really weird about it...?

#

do the missing members appear in your fetch_members list

echo wraith
ebon swift
#

might check twice still

echo wraith
#

yeah I mean I trust you but who knows atp

ebon swift
#

...

errant trout
#

oh

ebon swift
#

sorry to ahve bothered you all

errant trout
#

LOL

ebon swift
#

[redacted but there was two servers]

#

BUT

#

WAIT

#

ITS NOT APPEARING IN THE FIRST SERVER WTF

errant trout
#

burn him at the stake

echo wraith
#

in the online tab ?

errant trout
#

uhhh don't think a bot would need them

echo wraith
#

I'm pretty sure if @ everyone disbles view channels and the bot doesn't have that in its default role it doens't show up

ebon swift
#

okay well now I need to udnerstand how to kick him

#

or jsut force with guild id

echo wraith
errant trout
#

code-wise, you can kick any member with guild.kick(discord.Object(user_id))

#

(or fetch the user if you really want)

ebon swift
#

I'm very sorry for that 😦

#

thank you guys

errant trout
#

nah all good LOL

ebon swift
#

I feel so stupid

#

anyway thank you 🙏 as always, awesome community

echo wraith
#

nw and feel free to ask if there's anything

lofty parcel
#

i know im awesome, ty

fierce seal
#

Does anyone know how to start a task that's in a cog when the bot starts up?

sage tendon
#

self.task.start()

#

lol

errant trout
#

erm actually there's no await

sage tendon
#

true

fierce seal
#

didn't seem to work but i'll check again

sage tendon
#

in the cog init

#

not in your main file

little cobalt
sage tendon
#

damn zervy typed faster

little cobalt
#

Im at my phone ;3

sage tendon
#

i was held back by pycharm loading

echo wraith
#

Curious if starting in a once=True on_ready is also good

errant trout
#

theoretically yeah

#

well

#

you generallyyyy don't need to add once to on_ready, but i guess you can

echo wraith
errant trout
#

fairfair

upper slate
#

why did my post in #creations get deleted?

#

it was an lfg bot

echo wraith
#

idk ask lala or some mod

#

probably has to do with #creations message

upper slate
#

ah I see, sorry. if anybody has any tips for advertising a bot feel free to dm me

sage tendon
#

its a 2 seconds google search

#

which is why you chose the several-minute path that this is

lethal loom
#

I have the following problem, somehow I get all members who are on the server at member_ids and not only from the specific channel and no these are not admins or so

    async def user_callback(self, select, interaction):
        users_ids = [user.id for user in select.values]
        print(users_ids)
        users = []
        users_errors = []
        channel = interaction.channel
        print(channel)
        member_ids = [member.id for member in channel.members]
        print(member_ids)
        print(len(member_ids))```
#

and the channel prints the right channel

sage tendon
#

thats normal

lethal loom
#

why?

sage tendon
#

because thats how user selectors work

lethal loom
#

Ah nonono

sage tendon
#

oh yes

lethal loom
#

but i use the itneraction?

#

and how can i do it 0only become the channel members?

sage tendon
#

you cant limit user selects to only show specific people

#

it always shows everyone afaik

#

and if you mean this, that should work if the docs are right

lethal loom
#

So i want to make a suer select and there are all users inside that works and is correct but i want now wnen i can make the dropdown in a private only a lsite of all suer who are in the channel

#
class UserSysAddUser(discord.ui.View):
    @discord.ui.user_select(placeholder="Wähle einen user aus", min_values=1,max_values=3)
    async def user_callback(self, select, interaction):
        # Get the user IDs from the select
        users_ids = [user.id for user in select.values]
        print(users_ids)
        users = []
        users_errors = []
        # Get the channel where the dropdown was used
        channel = interaction.channel
        print(channel)
        # Get all users who are in the channel where the dropdown was used
        member_ids = [member.id for member in channel.members]
        print(member_ids)
        print(len(member_ids))```
#

i added coms.

lofty parcel
#

I'm sure user selects only show relevant users who can see the channel.

lethal loom
#

no XD

sage tendon
#

No, they show all

lethal loom
#

I have a dropdown with all users, this is right

sage tendon
#

all user selectors work like that, in slash commands as well

lethal loom
#

BUT

sage tendon
#

I dont think there's an easy way to achieve what you want

lofty parcel
#

Well then create the dropdown yourself

sage tendon
#

but then you are limited to 25? options

lethal loom
#

You don't understand that

lofty parcel
#

It's ugly?

lethal loom
#

Everything is ok with the userselector

lofty parcel
#

Yes

#

It works?

#

Also yes

lethal loom
#

but after i have selected one or more users i would like to get all users who are in the channel in a list

sage tendon
#

well again the docs do say channel.members returns only members who can see the channel

#

so Shrug_3 if the docs lie no clue

lethal loom
#

but i don't get the users from the channel but everyone who is on the whole server

#

I get a site with 28 users but in the channel only 10 people are authorised to see and read it

sage tendon
#

make sure they dont have read messages in that channel

#

deny them that specifically

#

that should fix it

sage tendon
lethal loom
#

but i become all members with this
member_ids = [member.id for member in channel.members]

sage tendon
#

what did i just say?

lethal loom
#

look no body can see this

sage tendon
#

that isn't the permission that matters as i just showed

sage tendon
sage tendon
lethal loom
#

i have desable all perms but i become all suers 😦

sage tendon
#

In the channel overrides, does @ everyone have X for read messages?

sage tendon
#

Okay yea looking at the library code again I saw that my assumption was wrong, but now I have even less of a clue why your stuff doesnt work

lethal loom
#

and this is my code to create this channelpy permissions = { interaction.user: discord.PermissionOverwrite(send_messages=True, read_messages=True, view_channel=True), interaction.guild.default_role: discord.PermissionOverwrite(view_channel=False, read_messages=False) }

sage tendon
#

can you do print("Test " + len(channel.members))

#

and show the output

#

just to make sure its what i expect

lethal loom
#

print("Test " + len(channel.members)) ~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~ TypeError: can only concatenate str (not "int") to str

sage tendon
#

bruh then do an f string

lethal loom
#

ah XD

sage tendon
#

god python is so dumb sometimes

lofty parcel
#

print("test", len(channel.members))?

sage tendon
#

I choose to disagree with that syntax

lofty parcel
#

Python doesn't

echo wraith
#

Looking at it but might be too tired to do a full repro, rn can't repro

lethal loom
sage tendon
#

and how many members do you see in the members list

lethal loom
#

9

sage tendon
#

also its "get", just to clear out confusion
become means something different

#

Then can you try this

for member in channel.members:
    print(channel.permissions_for(member).read_messages)
lofty parcel
#

It's weird, it works for me

sage tendon
#

2 v 1 then lol

#

and i have to agree i dont see anywhere this could go wrong, the internal code seems solid

#

Can you show a full screen recording of the entire process as well
I think we're missing something

lethal loom
#

i become 28 x ture its bad

#

yeah

echo wraith
echo wraith
#

Oh

lethal loom
#

yeah wait

echo wraith
#

thx toothy

#

can you try with pycord master ?

sage tendon
echo wraith
#

I think I pred something abotu broken permissions overwrites

#

and it got merged

echo wraith
#

didnt see it

#

what

echo wraith
#

But I'm not sur if it applies here

lofty parcel
#

I don't use master and it works for me

sage tendon
#

the screen rec will show us the issue

#

100%

echo wraith
lethal loom
sage tendon
#

this seems an issue with your backend code tho? lol

#

like where do you print that "already in the ticket"

#

the logic deciding that is busted

lethal loom
#

this is my complet funcvtion

#
class UserSysAddUser(discord.ui.View):
    @discord.ui.user_select(placeholder="Wähle einen user aus", min_values=1,max_values=3)
    async def user_callback(self, select, interaction):
        # Get the user IDs from the select
        users_ids = [user.id for user in select.values]
        print(users_ids)
        users = []
        users_errors = []
        # Get the channel where the dropdown was used
        channel = interaction.channel
        print(len(channel.members))
        print(channel)
        for member in channel.members:
            print(channel.permissions_for(member).read_messages)
        # Get all users who are in the channel where the dropdown was used
        member_ids = [member.id for member in channel.members]
        print(member_ids)
        print(len(member_ids))
        for u in users_ids:
            user = interaction.guild.get_member(int(u))
            if user is None:
                users_errors.append(f"\n - <@{u}> `Invaid User`")
                continue
            elif user.id == interaction.user.id:
                users_errors.append(f"\n - <@{u}> `Du kannst dich nicht selber zu dem Ticket hinzufügen`")
                continue
            elif user.id in member_ids:
                users_errors.append(f"\n - <@{u}> `der Nutzer ist schon im Ticket vorhanden`")
                continue
            overwrite = discord.PermissionOverwrite()
            overwrite.read_messages = True
            await channel.set_permissions(user, overwrite=overwrite)
            users.append(f"<@{u}>")
        user_string = ", ".join(users)
        users_errors_string = ", ".join(users_errors)
        await interaction.response.defer()
        embed = discord.Embed(description=f"{interaction.user.mention} hat {user_string} zum Ticket hinzugefügt",color=TICKET_COLOR_GREEN)
        embed_error = discord.Embed(description=f"Folgende User konnten nicht hinzugefügt werden: {users_errors_string}", color=TICKET_COLOR_RED)
        if len(user_string) == 0:
            await channel.send(embed=embed_error)
        elif len(users_errors_string) == 0:
            await channel.send(embed=embed)
        else:
            await channel.send(embeds=[embed, embed_error])```
sage tendon
#

i have to admit i have no clue why you're extracting the IDs from the full objects, then later you need to jump through hoops because of that

lofty parcel
#

Long ass callback

sage tendon
#

yea a lot going on lol

lethal loom
#

yeah but why channel.members give me 28 😭

echo wraith
#

idk if it's that or smth

sage tendon
#

i was just intently looking at the "interaction.channel" line

#

lmao

#

yea please try on master branch

echo wraith
#

.tag master

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

lofty parcel
#

If its that

#

I'll fucking lose it

echo wraith
#

its that 100%

#

cause

#

member_ids = [member.id for member in channel.members]

#

channel.members uses permission_for

#

which was broken

lofty parcel
#

Yeah

sage tendon
#

the code itself looks fine, but i heavily recommend splitting it up into several functions

and importantly, from the full user and member objects you get, you just extract the ID. Then later you construct a mention manually beacuse, well, you only have the ID. What's the point of reducing the objects to their ID?

lofty parcel
#

You can also improve that code lol

#

Or I'd just do it different

echo wraith
sage tendon
#

2.7 is really fucking overdue now

#

if for nothing but bug fixes

lethal loom
#

with master its work 😦

echo wraith
#

alright there we go

lofty parcel
#

Why u sad

#

It works

lethal loom
#

yeah thx for all helpers 🙂

sage tendon
#

because we wasted a long time on an issue outside of our control, which should have gone into a stable version ages ago

#

that fucking PR was merged 2 years ago

echo wraith
#

what

sage tendon
#

wait

echo wraith
#

my pr ?

sage tendon
#

ugh okay im tierd

#

no the issue, i thought it was a pR

echo wraith
#

this is the pr

sage tendon
#

well nevermind that, we need 2.7 now seriously

echo wraith
#

the issue btw
InteractionPayload["channel"] is partial, thus, when creating a GuildChannel object from it, some attributes were missing/incorrectly set. With this pr, InteractionPayload["channel"] is used only in the following cases:

  1. When the interaction happens in private channels.
  2. When the channel is missing from the bot's cache.

In all other cases, it uses the full channel object from the cache.

sage tendon
#

ill pretend i understand

echo wraith
#

Basically with every interaction discord sends a channel object so we tought it was a good idea to use it instead of the cached one but that one was missing permissions

#

whatever

#

gn chat

raw beacon
#

For slash command interactions, how would i get the supplied values of the command arguments?

lofty parcel
#

It works exactly the same way. You just use the function arguments you set.

lapis dock
#

You should have it setup like arguments to the callback function

@bot.slash_command()
async def warn(ctx, user, reason):
  ...

/warn user:@Ice Wolfy reason:bad :3

lofty parcel
#

OK wolfy beat me with the example

raw beacon
#

Oh i guess i wasnt clear, apologies, i meant if i have the interaction object of a command that was executed

lapis dock
#

Actually, this might not work

raw beacon
#

AttributeError: 'ApplicationContext' object has no attribute 'data'

lapis dock
#

oh, you already have an application context object, not interaction

lofty parcel
#

Slash commands receive an ApplicationContext, not a "plain" interaction object like discord.py

lapis dock
round heart
#

So if you have ctx, it'd just be ctx.command which is the SlashCommand object (and the ctx.selected_options as Wolfy mentions)

raw beacon
#

command.options only returned the args it has, not values that were supplied

lapis dock
#

^ selected options includes the user provided values

wintry pelican
#

hullo... i tried searching first, but i couldn't find an answer for my question...

i am running a bot that maintains a set of threads for different work issues; we use Jira which posts an event to our bot on every issue update, then the bot checks to see if that issue should have a Discord thread and if so creates/updates it. we are hitting this rate limit after three or four updates in a minute or so:

[2025-03-13 20:27:13] [WARNING ] discord.http: We are being rate limited. PATCH https://discord.com/api/v10/channels/1349184233557590076 responded with 429. Retrying in 518.31 seconds.

i am trying to figure out which rate limit we are hitting (global? that endpoint? some grouping of endpoints?) and what the limit is. i know from the docs some of that is available in the http response headers, but i don't know how to get at those using discord.py. does anyone have any advice? ty in advance!

sage tendon
#

Are you ever renaming the channel

silk spire
#

oh no do threads have the same limits now nvm that's a channel url

lapis dock
#

Also note that this is the support server for py-cord not discord.py

wintry pelican
#

right sorry, i meant py-cord. 🙂

wintry pelican
sage tendon
#

renaming channel has an extremely low rate limit

wintry pelican
#

i bet that's it, ty!

silk spire
#

channel edit name/topic has a ratelimit of 2 changes per 10 mins, discord does not want you to use channels as some sort of counters of stuff

sage tendon
#

yea prolly

silk spire
#

threads shouldn't have this low limit

#

use and rename those instead, if possible

wintry pelican
#

will do, thank you so much.

maiden bloom
#

Can an event listener be added for when entitlements are cancelled and expire?

sly karmaBOT
#

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

nimble matrixBOT
maiden bloom
lofty parcel
#

You listen to the update event

maiden bloom
lofty parcel
maiden bloom
lofty parcel
#

uhh

#

not really, i have never worked with entitlements

#

but they should differ somehow, check the discord docs themselves

tulip verge
#

hey so when i try to install pycord it comes up with this

lofty parcel
#

remove the $

tulip verge
#

yeah i did then it comes up with the same error for install

#

then pip

#

see

lofty parcel
#

Where are you running this?...

tulip verge
#

in pyhton

lofty parcel
#

You don't run it in the python idle

#

You use your terminal

tulip verge
#

where tf i get that lmao

lofty parcel
#

You open a Command Prompt

tulip verge
#

yeah

lofty parcel
#

or simply type cmd in the search bar of your apps

tulip verge
#

yeah i got it up

lofty parcel
#

ok now install the library

#

consider learning python before trying to create a discord bot

tulip verge
#

just need it for a account gen lol

lofty parcel
#

a what?

tulip verge
#

dw

#

btw

#

it still dont weork

lofty parcel
#

No, it does matter, because if it breaks the ToS, I won't help you and remove you from here.

tulip verge
#

what lmao

#

what breaks tos

#

doesnt say anywhere in rules about it

lofty parcel
#

"account gen"

tulip verge
#

so idk what u on about

lofty parcel
#

What

#

Following the Discord ToS is common sense

#

you dont need to read it in a rules channel

tulip verge
#

noone finna read discord tos

#

ibsr

lofty parcel
#

Not reading it does not make you excempt from it.

tulip verge
#

this makse sense now

round heart
#

It's funny when people who don't even understand that Windows is not for development are trying to do stupid shit like auto-generating accounts.

flat wind
#

Hello !
is it possible to know if a timestamp is sent in a message ? like a mention I mean.
f.e a message containing a mention will have <@someID> but also message.mentions, is it possible to get the same information for the <t:123:F> ?

#

if not, I will fetch it manually using a regex

silk spire
flat wind
fresh sierra