#Basic Pycord Help

1 messages ¡ Page 65 of 1

sage tendon
#

the website

#

top right

pulsar ferry
echo wraith
#

ye

sage tendon
#

yes

pulsar ferry
#

k reading now

echo wraith
#

If I want to send an attachment and have a file url, is there a way I can directly "pipe" the url to discord without having to re-download it to use less network ressources ?

sage tendon
#

I guess you can put it as filepath of a discord.File

#

very maybe

#

actually no that'll do the same thing I think

#

I don't think that's possible

echo wraith
#

That sucks oh well

#

I'll find a solution

sage tendon
#

alternatively just directly send the link lol

pulsar ferry
#

Giving the cogs another shot, quick question on it. where in the individual cog file in the setup() function does the bot object that is passed to setup come from?

https://guide.pycord.dev/popular-topics/cogs

Cogs, often known as modules or extensions, are used to organize commands into groups. This is useful

sage tendon
#

nowhere

#

it's just a standardised function that bot.load_extension calls

#

oh nvm I misread

#

well bot.load_extension calls setup(bot) very basically

pulsar ferry
#

in other words, when bot.load_extension('cogs.greetings') is called, ...

#

yep okay thanks

echo wraith
drowsy grove
#

after a brutal amount of hours spent on entitlements, discord documentation, discord.py and pycord documentation, and random stack overflow pages, I can confidently say that I did it. My first premium shop item is live. That took WAY too long, and I'm just glad it's over.

sage tendon
#

lol

#

congrats

#

honestly SKUs still seem so weird and half assed

lapis dock
#

🎉

sage tendon
#

(never used them so limited opinion)

drowsy grove
#

thank you. I think I'm going to go get a cold beer and a lawn chair from walmart and just sit in my driveway

drowsy grove
# sage tendon honestly SKUs still seem so weird and half assed

I fully agree. You can only get your SKU id from an api endpoint or from the url of your SKU in the dev portal. And then, you have to deal with EntitlementIterators only to realize that they DON'T WANT TO ITERATE. And THEN, you discover the golden chapel of interactions.entitlements, which returns a simple list of Entitlements that the invoking user owns, and all is right in the world.

sage tendon
#

lol

pulsar ferry
#

with cogs, we still need to call bot.run though correct?

if __name__ == "__main__":
    cogs_list = ["referral"]

    for cog in cogs_list:
        bot.load_extension(f"cogs.{cog}")
    bot.run(SWEEPY_TOKEN)

sage tendon
#

yes

stray cape
#

hey guys I just have a question: persistent views, alright so they are kind of persistent, so they work everytime the bot is online, but are there cases where persistent views don't work?

sage tendon
#

when the bot is offline

#

:3

stray cape
sage tendon
#

really the only case I could think of

stray cape
#

thought you were joking

lapis dock
#

When, you dont re-add them to your bot when you restarted

sage tendon
#

well yea but that's kinda required for a view to be considered persistent

sage tendon
stray cape
#

I just have to set the timeout to None and give every item a custom id right?

stray cape
#

?

pulsar ferry
#

is there a different task decorator that needs to be used in cog?

@tasks.loop(hours=1)

sage tendon
#

no

stray cape
#

Oh had to read the docs thorough

#

found it thx

pulsar ferry
#

and is it okay to have on_ready() defined in multiple cogs or is that a bad idea?

sage tendon
#

cogs use listeners so it's fine

#

they don't overwrite the event

lapis dock
# stray cape wym?

How it works is when you send a button (or other component) to discord it has a custom_id attached to it. Every time a user clicks the button discord send the custom ID to your bot and the bot finds what view it was "attached" to to and does the callback. So as long as your bot can receive the custom ID from discord (bot is online) and is able to find what view the button was attached to (there exists an "active" view that has a component with the same custom ID) it will work

pulsar ferry
#

does the on_ready retrigger on every cog through is forexample bot just disconnects / reconnects?

#
    @commands.Cog.listener()
    async def on_ready(self):
        await self.update_contributors.start()
sage tendon
#

yea

lapis dock
#

Yes, you can add once=true to the listener tho

pulsar ferry
lapis dock
#

I believe so

sage tendon
#

yes

pulsar ferry
#

hey guys - ive almost fully migrated over to cogs but having an issue with a custom decorator that was previously working to validate the value provided from an autocomplete - I cant use Options as there are too many values i want the user to be able to select

def check_casino_name(casino_name):
    if casino_name in CASINOS:
        return casino_name
    else:
        return None

def validate_casino_name(func):
    @wraps(func)
    async def wrapper(ctx, casino_name: str, *args, **kwargs):
        valid_casino_name = check_casino_name(casino_name)
        if not valid_casino_name:
            return await ctx.respond(ERROR_MESSAGE, ephemeral=True)
        return await func(ctx, casino_name=valid_casino_name, *args, **kwargs)
    return wrapper

class Casino(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @discord.slash_command(guild_ids=[GUILD_ID], description="Lookup information about a casino")
    @validate_casino_name
    async def info(self, ctx, casino_name: discord.Option(str, "Choose a casino", autocomplete=discord.utils.basic_autocomplete(casino_name_autocomplete))):
        # Look up the casino info by name in the CASINOS dictionary
        casino_data = CASINOS.get(casino_name.lower())

        if casino_data is None:
            await ctx.respond(f"'{casino_name}' is not a valid option. Please make a selection from the list", ephemeral=True)
            return
#

getting this:

Ignoring exception in command info:
Traceback (most recent call last):
  File "/Users/ethan/Python Projects/EliteSweeps/.venv/lib/python3.12/site-packages/discord/commands/core.py", line 138, in wrapped
    ret = await coro(arg)
          ^^^^^^^^^^^^^^^
  File "/Users/ethan/Python Projects/EliteSweeps/.venv/lib/python3.12/site-packages/discord/commands/core.py", line 1078, in _invoke
    await self.callback(self.cog, ctx, **kwargs)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Casino.info() got multiple values for argument 'casino_name'

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

Traceback (most recent call last):
  File "/Users/ethan/Python Projects/EliteSweeps/.venv/lib/python3.12/site-packages/discord/bot.py", line 1137, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "/Users/ethan/Python Projects/EliteSweeps/.venv/lib/python3.12/site-packages/discord/commands/core.py", line 435, in invoke
    await injected(ctx)
  File "/Users/ethan/Python Projects/EliteSweeps/.venv/lib/python3.12/site-packages/discord/commands/core.py", line 146, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: Casino.info() got multiple values for argument 'casino_name'
#

not entirely sure where the multiple value is coming from, only thing really that changed is this info function is now part of a cog

sage tendon
#

you are passing casino_name twice, thats the entire problem

#

run kwargs.pop("casino_name")

#

you are passing it via **kwargs, and then explicitly

#

i think thats the issue at least
or no wait

pulsar ferry
#

i dont think so because this worked fine before putting in cog

sage tendon
#

since its in a cog it has self now, and your wrapper doesnt respect that

pulsar ferry
#

ahh

#

so just add a dummy self to the wrapper?

sage tendon
#

not just dummy lol

#

just do like wrapper(cog, ctx..)

#

its not a dummy because it serves a purpose :)

#

same for then calling the function below

pulsar ferry
sage tendon
#

same thing.. pass the cog you define above to the actual function call

#

cog = self

pulsar ferry
#

youre saying this

def validate_casino_name(func):
    @wraps(func)
    async def wrapper(cog, ctx, casino_name: str, *args, **kwargs):
        valid_casino_name = check_casino_name(casino_name)
        if not valid_casino_name:
            return await ctx.respond(
                f"It doesn't look like I know which casino `{casino_name}` is. Make sure you select a casino name from the dropdown and if it's not an option, open a request in #1318685820823142471 with the `new casino` tag.",
                ephemeral=True,
            )
        # Pass the valid casino name to the command function as a keyword argument
        return await func(ctx, casino_name=valid_casino_name, *args, **kwargs)

    return wrapper

and then what else?

sage tendon
#

but self is reserved

#

here too

pulsar ferry
#

ah duh yeah sorry

#

okay let me try it

#

yep that did it - thanks!

#

Alright cogs up and running thanks all! definitely feels much more organized... now the main thing i wanted to work on today 😅 ... I currently have a subscriber only forum channel that the bot automatically posts to. I want to have some sort of way that once the post is over 24 hours, it then becomes visible to everyone regardless of if they are subscribed...

What would be the best approach to go about doing this? Is is possible to move an entire thread from one forum channel to another while keeping all its tags/comments etc.? For example like a public 'archive' forum channel that everyone can always see that threads get moved into after the time threshold

sage tendon
#

no, you cant move threads list that, you'd need to redo it

pulsar ferry
#

hmm, is there a way maybe then for when i post the thread to only have it visible within that channel to a certain role, and then after the time limit make it public?

sage tendon
#

no idea

fresh sierra
#

why does the load_extension -with the recursive arg ignore every file which begin with _

sage tendon
#

because it should

fresh sierra
#

yeah but why ?

sage tendon
#

because a _ prefix indicates private or unused things in python

fresh sierra
#

even for a name file ?

sage tendon
#

Shrug_3 guess so

fresh sierra
#

how should i name my file for i can appear at the top of the other but still be use

#

maybe 1setup

#

but its very strange asf

sage tendon
#

file order really shouldnt be a consideration lol

fresh sierra
sage tendon
#

__init__

fresh sierra
#

i used to do init even if ik i shouldnt

#

just gonna do !setup

#

looks better

sage tendon
#

just for defining that group?

fresh sierra
#

just rewriting my bot with a new db thats why its empty

humble turtle
#
Traceback (most recent call last):
  File "C:\Users\SchĂźler\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\commands\core.py", line 138, in wrapped
    ret = await coro(arg)
          ^^^^^^^^^^^^^^^
  File "C:\Users\SchĂźler\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\commands\core.py", line 1078, in _invoke
    await self.callback(self.cog, ctx, **kwargs)
  File "C:\Users\SchĂźler\Documents\Botify\cogs\Admin\admin.py", line 290, in premium
    "%Y-%m-%d %H:%M:%S") if entitlement.starts_at else "Unbekannt"
                            ^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'int' object has no attribute 'starts_at'
#
            premium_entitlements = await get_premium_users(self.bot)
            desc = "Bot Entitlement Users:\n\n"

            for entitlement in premium_entitlements:
                starts_at = entitlement.starts_at.strftime(
                    "%Y-%m-%d %H:%M:%S") if entitlement.starts_at else "Unbekannt"
                ends_at = entitlement.ends_at.strftime(
                    "%Y-%m-%d %H:%M:%S") if entitlement.ends_at else "Unbekannt"
                desc += f"{int(entitlement.user_id)} - Start: {starts_at} - End: {ends_at}\n"
sage tendon
#

get_premium_users isnt something from pycord, so if thats your own function, fix what it returns

#

currently its evidently a list of ints

humble turtle
sage tendon
#

that is not something built into Pycord by default unless it's just not documented

#

and I mean if you looked at it you'd see you get user IDs only, not entitlements

humble turtle
#

yes

sage tendon
#

yea so I don't know what you're doing if you know lol

humble turtle
#

this is my code

sage tendon
humble turtle
#

I got it

round heart
sage tendon
#

did you do this with chatgpt

pulsar ferry
#

Why is it that when i try and run both of these tasks on ready, only the first seems to run?

class Casino(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.Cog.listener(once=True)
    async def on_ready(self):
        await self.update_freebie_stats.start()
        await self.archive_old_threads.start()
pulsar ferry
#

It seems to work if i remove the awaits - but im not sure if thats the proper way to handle this?

edgy nest
#

you can, but it will wait until the task gets cancelled

#

since it returns the internal task

#

also you should not start tasks in on ready, you should use wait_until_ready in the task's before method

pulsar ferry
#

Ah wow okay I’m definitely doing this wrong will try updating to the example flow today

#

Thanks!

fresh sierra
pulsar ferry
# edgy nest you can see examples here: https://docs.pycord.dev/en/stable/ext/tasks/index.htm...

trying to follow this - i dont understand why update_leaderboard is just calling itself?

class LeaderboardCog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.update_leaderboard.start()
        self.leaderboard_embed = generate_leaderboard_embed()

    leaderboard = SlashCommandGroup(name='leaderboard', description='Leaderboard commands.')

    @tasks.loop(minutes=10)
    async def update_leaderboard(self):
        print('Updating leaderboard...')
        await update_leaderboard()
#

I think this is the correct approach though?

class Casino(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.archive_old_threads.start()

    @tasks.loop(hours=1)
    async def archive_old_threads(self):
        logger.info("Archiving threads older than 24 hours...")
         # ...Rest of code for this function

    @archive_old_threads.before_loop
    async def before_archive_old_threads(self):
        await self.bot.wait_until_ready()
torn barn
#

What are you trying to accomplish here? Calling the loop function manually?

pulsar ferry
#

I originally had this and was told its inaccurate way to do it #1132206148309749830 message

just trying to have some tasks start up and run in background

#

to not start them in the on_ready

torn barn
#

Okay, it seems okay, but what do you exactly don’t understand

#

You said “I don’t understand why update_leaderboard is just calling itself?”

sage tendon
pulsar ferry
#

in the example

sage tendon
#

no, it isnt

#

ah wait below

pulsar ferry
sage tendon
#

yea, its calling a different function

pulsar ferry
#

yeah i gathered that after but confusing since its named the same as the one its in

sage tendon
#

yea its kind of a bad example name, wildcard import doesnt help

sage tendon
pulsar ferry
# sage tendon then when do you want to start them

I do want them to start right when the bot starts, but @edgy nest mentioned to not actually do it in the on_ready, and pointed to the guide, which states to start it in the init (which im doing now i think accurately)

sage tendon
#

It really doesnt matter where you start them

pulsar ferry
#

moving from #1132206148309749830 message to #1132206148309749830 message

sage tendon
#

but you should put await self.bot.wait_until_ready() as the first line of your task

#

that ensures it doesnt start too early, before cache is present

pulsar ferry
#

well yeah i just have it in the before loop now

#

class Casino(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.update_freebie_stats.start()

    @update_freebie_stats.before_loop
    async def before_update_freebie(self):
        await self.bot.wait_until_ready()
sage tendon
#

never knew you could even split loops like that, weird

pulsar ferry
#

lol thats how the guide says to do it!

#

#1132206148309749830 message

sage tendon
#

i know

#

i just didnt know you could

pulsar ferry
#

Am i doing something wrong here? the after_loop doesnt seem to ever run. I am seeing the 'TEST DONE' get printed but not the "thread archiving complete" message

    @tasks.loop(hours=1)
    async def archive_old_threads(self):
        cutoff_time = datetime.now(timezone.utc) - timedelta(hours=24)
        channels = [await find_channel_by_name(self.bot, "freebies"), await find_channel_by_name(self.bot, "promos")]
        for channel in channels:
            for thread in sorted(channel.threads, key=lambda t: t.id, reverse=True):
                if thread.created_at <= cutoff_time and not thread.archived:
                    logger.info(f"Archiving thread {thread}")
                    await thread.archive()
        print('TEST DONE')

    @archive_old_threads.before_loop
    async def before_archive_old_threads(self):
        await self.bot.wait_until_ready()
        logger.info("Archiving old threads...")

    @archive_old_threads.after_loop
    async def after_archive_old_threads(self):
        logger.info("Thread archiving complete")
sage tendon
#

are you ever stopping the task?

fresh sierra
pulsar ferry
#

ah so if we have a loop that is going every 1 hour, it would never "stop" then right?

#

i guess i can just put that log message at the end of the function itself and not overengineer it lol

sage tendon
#

a task only stops if it crashes or you cancel it

#

or stop it

fresh sierra
#

but you can test trying to stop it

#

to see if its triggered or not

pulsar ferry
#

well if i have this for if it errors out, and there shouldnt be any other scenario where i want it to stop so i think i dont need after_loop then

    @archive_old_threads.error
    async def error_archive_old_threads(self, error):
        msg = f"An error occurred while archiving old threads: {error}"
        logger.error(msg)
        await send_moderator_message(self.bot, msg)
#

so this all makes sense for a task thats on a loop, but what if there is a task i just want run once when the bot starts up... still not best practice to put in on_ready?

#
    async def refresh_invite_cache(self):
        logger.info(f"Refreshing server invites cache...")
        async with self.server_invites_lock:
            guild = self.bot.get_guild(GUILD_ID)
            invites = await guild.invites()
            self.server_invites = invites
        logger.info(f"Server invite cache refresh complete!")

    @commands.Cog.listener(once=True)
    async def on_ready(self):
        await self.refresh_invite_cache()
#

The other way i was thinking to do it could be like this, but not sure the implications of having a function declared as a loop and then also having other events call that same function?

class Referral(commands.Cog):

    def __init__(self, bot):
        self.bot = bot
        self.refresh_invite_cache.start()

    @tasks.loop(count=1)
    async def refresh_invite_cache(self):
        async with self.server_invites_lock:
            guild = self.bot.get_guild(GUILD_ID)
            invites = await guild.invites()
            self.server_invites = invites
        logger.info(f"Server invite cache refresh complete!")

    @refresh_invite_cache.before_loop
    async def before_refresh_invite_cache(self):
        await self.bot.wait_until_ready()
        logger.info(f"Refreshing server invites cache...")

    @refresh_invite_cache.error
    async def error_refresh_invite_cache(self, error):
        msg = f"An error occurred while refreshing invite cache: {error}"
        logger.error(msg)
        await send_moderator_message(self.bot, msg)

    @commands.Cog.listener()
    async def on_invite_create(self, invite: discord.Invite):
        await self.refresh_invite_cache()

    @commands.Cog.listener()
    async def on_invite_delete(self, invite: discord.Invite):
        await self.refresh_invite_cache()
sage tendon
#

at that point just make a seperate helper function that the task also calls

#

also what is count=1?

pulsar ferry
#

oh is that not valid? i was using it previously here and it seemed to be working

    @tasks.loop(count=1)
    async def run_fastapi(self):
        logger.info("Starting FastAPI server")
        config = uvicorn.Config(self.app, host="0.0.0.0", port=8080)
        server = uvicorn.Server(config)
        await server.serve()
sage tendon
#

im asking what it is

pulsar ferry
#

well what i am trying to do is essentially when the bot starts, run the refresh_invite_cache 1 time

sage tendon
#

why make a task for that?

pulsar ferry
#

and then the listeneres when invites get created / deleted, it runs it on demand

sage tendon
#

just call the function?

pulsar ferry
#

where?

#

in the on_ready?

sage tendon
#

literally just call the function

#

there is no point to make a task that only runs once

pulsar ferry
#

I was previously doing it like this

    @commands.Cog.listener(once=True)
    async def on_ready(self):
        await self.refresh_invite_cache()

but was now going into all the code and refactoring away from using the on_ready

sage tendon
#

i dont see the issue with that

pulsar ferry
#

should i just keep it like this?

#

ok

lapis dock
sage tendon
#

oh yea that was what I forgot thx

drowsy grove
#

Sealy time! Today’s question is…(drumroll for dramatic effect)…which @after_invoke() decorator should I use for my slash commands if I want to save a log of that command being executed to my DB? I presume it would be ApplicationContext, but I notice that when building the decorator it asks for a “self” parameter. Am I good to simply skip it and say “coro=test”?

sage tendon
#

applicationcontext is not a decorator

drowsy grove
#

And what if I have parameters I want to pass to that method as well?

#

The docs made me interpret that there was a discord.ApplicationContext.after_invoke decorator

#

ApplicationCommand*

#

Brain went brrr for a second, sorry

sage tendon
#

I mean I think it's @functionname.after_invoke

#

same for when you do .error

drowsy grove
#

Found it, thanks

#

Back to the other question then, is there a way to pass params to it?

sage tendon
#

doubt, why?

drowsy grove
#

My solution was going to be adding a decorator to handle all methods instead of adding it to each individual one. If not, then I’ll find another way lol

#

Just seemed it would be more convenient to do it that way so I only had to look at the top level of the method instead of searching through the method’s code for the call

humble turtle
#

how can i inquire if the server has owner premium then the others should also have premium automatically

sage tendon
#

wdym "owner premium"

drowsy grove
#

I think they mean how do they check if the server owner has premium so they can allow other members of the same server to use premium commands

sage tendon
forest horizon
#

Hmmm. Does my bot need the (privileged) message content intent, to be able to retrieve its own messages with Channel.fetch_message() ? (I'm getting '403 Forbidden (error code: 50001): Missing Access', so it would seem possibly so, but it seems pretty weird that a bot wouldn't be able to retrieve its own messages)

lapis dock
#

No, you would not get that error even with other messages. You just would get blank content fields

#

Can you check if your bot has the read messages permission in that channel?

forest horizon
#

Ah, do you mean "read message history"?

lapis dock
#

Yes

forest horizon
#

ah, does not. Still seems weird it wouldn't be able to retrieve its own messages (by id, anyhow), but I guess I can see the logic. That works, at any rate, thanks!

lapis dock
#

Yeah, it would make sense to allow that but it might be difficult to implement on discords side 🤷‍♂️

upper slate
#

Are there built-ins for creating group dm's? If not, any suggestions for getting a group of users from different guilds a medium to message each other?

shell radish
upper slate
shell radish
#

you can create invites, yes

round heart
#

Is there an example of the slash command option for mentionable input?

#

Didn't see it in the Guide or the github Examples folder, but could've sworn I've seen it before

sage tendon
#

i really see very little use for something like that tbfh so not sure if its worth an example

round heart
#

Well it's a good thing you're not the fucking king of pycord

sage tendon
#

What I'm saying is that it's pointless to make an example for something that barely has any real use

round heart
#

This is what I mean when I tell you that you're an asshole. It's not for you to say what has real use or not. Newsflash, I actually need it for something, so it has use.

sage tendon
#

you dont understand what im saying. try and stop being dick.

round heart
#

I do understand what you're saying - King Fucking Toothy doesn't think something matters, despite it being available, so nobody else should use it or be able to find information on how to implement it

sage tendon
#

sorry for offering my opinion

#

i cant change how you view what i say, maybe fix your mindset

#

if you think it matters, PR an example

round heart
#

Maybe stfu when someone asks a question and you don't have a constructive answer. It's been like this with you for as long as you've been here.

sage tendon
#

again, i cant change how you react to me giving my opinion
remember i said I see little use for that. i very explicitly gave my opinion

#

you are free to ignore it

round heart
#

But note that I (nor anyone else that posts here) didn't ask for opinions. People here ask for information. Your "opinion" does not belong unless specifically requested.

sage tendon
#

i mean you already said it doesnt exist

round heart
#

No, I said I was having trouble finding one; it wasn't a definitive conclusion that it didn't exist. Reading comprehension. Even if I did, the underlying question was how to use it; it still wasn't asking you what you personally thought about it.

round heart
lofty parcel
#

Dang you two like to yap

#

But I do agree with Debau

#

@sage tendon this is a help channel. You're no judge about how people use the library. The man was looking how to do mentionable inputs, you shouldn't give a fuck about what he uses it for, just provide the help.

sage tendon
#

no

#

I thought it was merely about the lack of a specific example, not how to actually use it

cosmic swift
#

Is there something that lets you update the bot without having to restart discord entirely?

echo wraith
#

maybe reloading cogs

#

/extensions

#

but I think there are issues w/ slash commands and that currently

cosmic swift
echo wraith
#

yes

cosmic swift
lapis dock
#

Paillat is right that it is kinda broken rn. It might work for your case but there are lots of glitches

cosmic swift
#

👍

lapis dock
#

I might try to fix it in the next ~1 month but don't know if I will have time

red crypt
#

it uses importlib and also just basic cog reloading

drowsy grove
sage tendon
#

mentionable is typically roles, channels, users

round heart
drowsy grove
#

Ahhhh I understand now. Clever. I’ll keep that in mind if I ever need it lol

#

Python whines anytime I use discord.Option but I hit it with the silliest move (#type: ignore)

sage tendon
#

using the decorator version (@discord.option) gets rid of that warning, and is also a bit cleaner imo

lapis torrent
#

Trying to use the VoiceClient to record audio from a stage, but I'm getting very choppy audio. Anyone have any experience with this? Or is this process pretty resource hungry?

lofty parcel
#

Voice is a sea of mysteries.

#

Nobody really uses it so nobody really knows how it works

#

Nobody really uses it so nobody really knows how it works

shell radish
lofty parcel
ionic wasp
#

why does the info not show in the blue command thing, its apart of the actual command

lofty parcel
#

Idk ask discord

ionic wasp
lofty parcel
#

Discord being discord i guess

sage tendon
#

bug probably

rugged lodgeBOT
#

test for a bug
I don't think so.

sage tendon
#

hm, i see the subcommand there on mobile

sage tendon
#

same for desktop

lapis dock
#

It could have something to do with the length

#

8ball ask is shorter than Roblox info

rugged lodgeBOT
#

test for question
Yes.

echo wraith
lapis dock
#

Yeah, guess not

sage tendon
#

probably some odd build discord broke something in again

nova epoch
#

This might seem dumb but is there an event for when someone adds a user-app to their account (kinda like on_guild_join but for user-apps)?

sage tendon
#

i think discord's last message on that was that its "coming next"

#

nothing since on that topic afaik

rotund quarry
#

Quick question, can i use py cord with python 3.13?

round heart
#

For the most part, but if you want voice, you'll need to install audioop-lts

rotund quarry
#

Thank you

lofty parcel
#

Just use 3.12.x

rotund quarry
#

ok

nova epoch
sage tendon
sage tendon
#

unless there is some lean install version of pycord without any of the voice features

lapis dock
sage tendon
# sage tendon

maybe they'll add it soon given this message, but who knows

#

since custom emojis are a thing now

edgy nest
delicate shell
#

when somebody moves a channel to a new position, is there a way for a bot to see who did it? the action triggers discord.on_guild_channel_update but doesn't seem to show up in the audit log

echo wraith
#

If it's not in the audit log I don't think so

#

Also the audit log seems like it has been a bit let behind lately

#

New features aren't necessarily logged properly anymore

delicate shell
#

ah, i see

echo wraith
#

Not saying that on_guild_channel_update is a new feature

rugged lodgeBOT
errant trout
delicate shell
#

oh, that makes sense

round heart
#

I mean, I guess. But they could have short-circuited it to just note the intentionally-changed position

stray cape
#

hey guys I am a bit confused

#

This is currently the channel status, only a few people can view the channel and actually join it

@bot.slash_command(name="some")
async def some(ctx: discord.ApplicationContext):
    await ctx.respond("OK")
    for member in ctx.channel.members:
        await ctx.channel.send(str(member))

currently, this is what the bot is printing

sage tendon
#

seems perfectly like expected then

stray cape
#

I mean, how? Am i using the wrong property to get the users in the channel or

sage tendon
#

oh

#

that's a thread, right?

stray cape
#

It's a channel

#

I suppose a private channel

sage tendon
#

hm

stray cape
#

Each user (there is a selected group of users) that can only send and view the channel

#

Those are the only permissions: view and send

#

And yeah intents are Intents.all()

sage tendon
#

does it print all members of the server?

stray cape
#

I thnk so

#

Let me check hold on a second

#

Yup

#

Everyone

sage tendon
#

honestly no clue

#

seems like a bug

little cobalt
#

What was that

sage tendon
#

i was off by 1 to the right on my keyboard

stray cape
#

just as confused too

sage tendon
#

can you make sure that ctx.channel is the right one idk this seems weird

stray cape
#

This is weird

#

since

#

If I do this:

@bot.slash_command(name="some")
async def some(ctx: discord.ApplicationContext):
    channel = ctx.guild.get_channel(1325911264941314059)
    await ctx.respond(f"len: {len(channel.members)}")

#

then it gives me the correct result:

len: 12
sage tendon
#

can you do print(ctx.channel == ctx.guild.get_channel(id))

stray cape
#
@bot.slash_command(name="some")
async def some(ctx: discord.ApplicationContext):
    channel = ctx.guild.get_channel(1325911264941314059)

    await ctx.respond(str(ctx.channel == channel))

sage tendon
#

you dont need to cast everything to str lol

stray cape
sage tendon
#

hm so its the same object

#

tf

stray cape
#

caching?

little cobalt
#

can you do the same with the member amount of the channels

stray cape
sage tendon
#

yea no get_channel also only reads from cache so wtf

#

weird

stray cape
#

and if I use get_channel then it gives me 12 which is the correct result

little cobalt
#

can you do it with fetch_channel

stray cape
#

with the assert?

lapis dock
#
mystr = str(len(ctx.channel.members))
channel = ctx.guild.get_channel(1325911264941314059)
await ctx.respond(f"{mystr}   {len(channel.members)}")
#

can you try that

stray cape
#

using fetch_channel

@bot.slash_command(name="some")
async def some(ctx: discord.ApplicationContext):
    channel: discord.TextChannel = await bot.fetch_channel(1325911264941314059)

    await ctx.respond(f"fetched result: {len(channel.members)}")
    #await ctx.respond(str(ctx.channel == channel))
lapis dock
#

This is what members returns so I dont know why channel cache would have anything to do with it
return [m for m in self.guild.members if self.permissions_for(m).read_messages]

stray cape
#
@bot.slash_command(name="some")
async def some(ctx: discord.ApplicationContext):
    channel: discord.TextChannel = await bot.fetch_channel(1325911264941314059)
    mystr = str(len(ctx.channel.members))
    channel = ctx.guild.get_channel(1325911264941314059)
    await ctx.respond(f"{mystr}   {len(channel.members)}")

stray cape
#

Should I make it an issue then in gh or

lapis dock
#

can you remove the fetch line above

#

then try again

stray cape
#
@bot.slash_command(name="some")
async def some(ctx: discord.ApplicationContext):
    #channel: discord.TextChannel = await bot.fetch_channel(1325911264941314059)
    mystr = str(len(ctx.channel.members))
    channel = ctx.guild.get_channel(1325911264941314059)
    await ctx.respond(f"{mystr}   {len(channel.members)}")

lapis dock
#

if you want you can open an issue. I will keep looking into it though

stray cape
#

Right, thanks yall for giving it an attempt

lapis dock
#

One last thing you can try is printing ctx.channel.overwrites and channel.overwrites I think the interaction channel is not getting its overwrites set properly.

stray cape
#

issue created

stray cape
#
@bot.slash_command(name="some")
async def some(ctx: discord.ApplicationContext):
    from_ctx = ctx.channel.overwrites
    from_get = ctx.guild.get_channel(ctx.channel_id).overwrites
    await ctx.respond(f"From ctx:\n\`\`\`{from_ctx}\`\`\`\nFrom get:\n\`\`\`{from_get}\`\`\`")

#

You get the idea

lapis dock
#

Yeah, thats what I suspected. That narrows down the issue but I would have to do a lot more testing to find where it is actually wrong

#

I think this is only an issue in private channels or channels with permission overwrites. It should work properly for "normal" channels

ancient cosmos
#

Trying to debug some of my code that's broken after a Pycord update.

I'm currently decorating a Cog method for a slash command with the following:

    @commands.slash_command(
        name = "scan",
        description = "Scan the monitored servers for a problematic user, without raising a proper Alert.",
        guild_ids = list(fcy_constants.ENABLED_ALERT_GUILDS.keys()),
        guild_only = True,
        cooldown = None,
    )

That's raising an exception, for which the relevant portion of the traceback is:

File "/home/lux/.local/lib/python3.13/site-packages/discord/commands/core.py", line 257, in __init__
     raise InvalidArgument(
         "the 'contexts' and 'integration_types' parameters are not available for guild commands"
     )

(There's also a @discord.commands.option decorator, but that's not what the traceback is telling me is causing the exception.)

Based on the source code, it seems like the guild_only kwarg is considered to be deprecated. Is the fix for this simply removing the guild_only = True kwarg and decorating the method with @discord.commands.guild_only instead?

(I know I can just try that and see if it works, but I want to make sure that's the right solution rather than a hack that works for reasons I don't understand.)

sage tendon
#

You should set contexts instead

#

which in your case will only be discord.InteractionContextType.guild

ancient cosmos
#

Cheers; I'll go ahead and try that, although I'm somewhat confused, since the documentation says:

contexts
The location where this command can be used. Cannot be set if this is a guild command. [emphasis added]

#

Yeah, I'm actually still getting the same error with either using the guild_only decorator instead, and with setting contexts = discord.InteractionContextType.guild instead

#

And that makes sense, given what I'm seeing in the source code (discord/commands/core.py line 1269) - it looks like I can't pass guild_ids along with any way to declare that the command is only available in a guild setting.

But that... seems like something one would want to be able to do... right? I would think there needs to be a way to do that?

The source code doesn't seem to imply this anywhere, but does setting guild_ids implicitly mean that the command is now guild-only, or something like that?

sage tendon
#

i think so

lofty parcel
#

A command registered to a specific guild is only available in the guild itself

#

Not in other places like global commands

torn barn
lapis dock
#

🎉

spark shadow
#

ok so i need help downloading pycord

#

it keeps saying invalid syntax

lofty parcel
#

What

#

What's difficult about running pip install py-cord

spark shadow
#

idk it gives this

round heart
#

what is 'it'?

lapis dock
#

sounds like you entered into the python repl by accident
In the console run quit()

spark shadow
#

alr thanks

echo wraith
sly karmaBOT
#

1. Uninstall discord.py or any other forks of discord.py you might have with the namespace discord.
python -m pip uninstall discord.py discord -y

2a. Install py-cord
python -m pip install py-cord

2b. Update py-cord
python pip install -U py-cord

Installing other builds:
Note: You need to have git installed. Use ?tag git to find out how to install git.

Updating the module to master branch (unstable):
pip install -U git+https://github.com/Pycord-Development/pycord

echo wraith
#

No actually it's still open #2658

rugged lodgeBOT
echo wraith
#

@torn barn ⬆️

little cobalt
#

so... I tried to use run_in_executor but I get every time Command raised an exception: TypeError: BaseEventLoop.run_in_executor() missing 1 required positional argument: 'func'

sage tendon
#

just try passing None as first arg

little cobalt
#

that worked, thx

echo wraith
#

oh he said it

lapis dock
#

Does the tag need to be updated them?

little cobalt
young skiff
#

is this a bug?

sage tendon
#

yes

verbal bluff
#

I know server admins can restrict command visibility/usability to certain roles or permissions, but can you do that in the code?
like i want the command to not be visible to people without the Manage Channels permission, or just a specific role
is that possible?

sage tendon
#

@discord.default_permissions()

#

look it up in the docs

#

not possible to do it with roles though, only permissions

verbal bluff
#

does it hide the command or just make it unusable, just curious

sage tendon
#

it hides it

#

it uses the discord permission system for commands

verbal bluff
#

alright tysm

lapis dock
# verbal bluff alright tysm

This is only the default permission when you bot is added to the server. Server admins can override this to whomever they want

verbal bluff
#

Yea i read

drowsy grove
#

This is more discord help but...if I had lootboxes to my bot is that ok? Like is that against ToS or Privacy Policy? I read both and it mentioned "illegal gambling", but the boxes aren't buyable. It's a daily reward.

#

I'm sure I've seen lootboxes that ARE buyable on other bots before, but want to double check because I'm a good seal

lofty parcel
#

if real money isnt involved, it is allowed

#

afaik tho

sage tendon
#

if it was on mee6, its not bound by any rules

#

mee6 is lawless because it's discords best selling bot

lapis dock
drowsy grove
#

Thanks y'all!

drowsy grove
lapis dock
drowsy grove
#

finna sell seal coins and be a gazillionaire frfr

lapis dock
maiden bloom
#

How can I check if a guild has purchased a certain SKU? I tried it in a testing server and purchased a SKU, but it doesn't show up under guild.entitlements()

sage tendon
#

you actually bought the SKU? lol i think you can use test entitlements for it

#

but no clue about entitlements apart from that so

drowsy grove
#

Devs can purchase any SKY for free @sage tendon

sage tendon
#

oh, ok

drowsy grove
#

@maiden bloom is it the server owner you’re checking for?

#

If that’s the case, you would check the user.entitlements of the server owner

#

I’m not aware of how guild SKUs work as I’ve only used user subscription ones

maiden bloom
sage tendon
#

how

maiden bloom
#

The testing account is part of the bot's dev team in the dev portal

#

It shows as premium under the guild integration settings and the shop shows that the current guild is subscribed

drowsy grove
#

@maiden bloom I’m sadly not sure. Where are you getting your guild reference from?

#

I know that when I was handling my entitlements I had to get them from a specific context

maiden bloom
drowsy grove
#

Ik that I personally have a dev and prod bot for coding purposes

#

And that I pulled a silly once with entitlements where I tried grabbing entitlements from the dev bot that were for the prod bot

#

If not, then I’m not quite sure. Discord doesn’t have good docs related to entitlements, so I can’t really suggest any of them to read sadly. I would say to look up your context in pycord’s docs and read what the entitlements fields are giving you

#

I spent a few hours browsing them and fully understanding what it needed, returned, and referenced before it clicked

#

Sorry I can’t help more

vivid valve
#

Hi there, I have a few general questions that I've not been able to find clear answers to:

  1. Is it possible to place buttons in an ephemeral message?
  2. If not, is it otherwise possible to limit the use of buttons to a specific user?
  3. Is it possible to place buttons in an embed object?
vivid valve
#

Okay, excellent. Are there any handy examples which show how to do these things?

tidal vessel
vivid valve
#

I have read the docs. I've not found anything that clarifies my original questions, thus why I asked them here. Otherwise I wouldn't be here.

tidal vessel
#

Add buttons to an ephemeral message?

vivid valve
#

Specifically what I'm doing is sending a series of multiple choice questions to users, which would be great to set up as a series of interactive embeds with buttons for answer selection. The questions are directed at specific users and thus input must be filtered out to only the user who invoked the command to start the sequence.
If buttons can manage that then I no longer necessarily require ephemerality.

tidal vessel
lapis dock
rugged lodgeBOT
#

Here's the tic tac toe example.

lapis dock
#

If you are still struggling after looking at the examples you should post your current code with any errors you are getting

fresh sierra
#

For what I understand, even if it’s not with real money etc you cannot play at some casino game

#

Even if it’s not related to real money

#

(This is the policy for premium app only)

#

@drowsy grove you might want to check that

drowsy grove
#

I have it with fake money, but I see people that make gambling bots that succeed as well. They only go so far as to increase daily rewards, which is all I’ve done as well

#

I want to see if I can contact discord for an exact answer, because I don’t want to break any of their policies

echo wraith
#

good luck

drowsy grove
# fresh sierra

Because this seems very cut and dry, whereas the other things I’ve read say that it’s fine as long as it has no real world value

fresh sierra
drowsy grove
#

Thank you for pointing out the monetization policy, as I didn’t know it existed @fresh sierra

deft hull
#

Hi, guys. new to pycord. How do you limit all commands to one server for testing purposes

lofty parcel
deft hull
#

thank you

minor basin
#

hi, question about modals: if user input fails validation, how can I tell them that as the "Something went wrong" error appears? I've been trying to set the self.children[0].value to an error message, but it doesn't change.

errant trout
#

you basically have to accept whatever they input and respond to the modal so it closes

minor basin
#

Ah. Alright, thanks

lapis dock
#

I think the best option is to send a message containing what the invalid input was with a button that allows them to re submit the model, possibly with the other values pre-filled in.

minor basin
#

yup, seems like the next best option, thanks.

maiden bloom
echo wraith
#

In a Paginator, are Page instances bound to a view / paginator, or can they be stored and reused across paginator instances ?

deft hull
#

How do I create a custom command check?

lofty parcel
deft hull
#

Thank you

errant trout
echo wraith
tender python
#

How can I create discord slash and context commands?

little cobalt
tender python
#

As in the ones that discord will autocomplete, (e.g. </cat:824701594695368767>)

little cobalt
#

that is a slash command

tender python
#

Yes, I would also like to know how you make the context menu commands, as in right click > apps > command

rugged lodgeBOT
#

Here's the slash basic example.

#

Here's the context menus example.

sly karmaBOT
lapis dock
#

These will help you get started along with the other examples in the "app_commands" directory on the github page. If you have more questions feel free to ask!

tender python
#

Thank you!

tender python
#

Is it possible to do with client, or just bot? nevermind

lapis dock
#

Client is only for events so you should use discord.Bot

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

How would you type a function return type (say it returns a list of whatever) as Immutable ?

#

I get it wouldn't actually be

#

just in typing

#

is there a way even ?

lapis dock
#

Would you not need to use a list subclass for that?

errant trout
#

otherwise stuff like collections.abc.Sequence are considered immutable types (though, as always, not enforced)

echo wraith
#

I want to type it as an immutable list because after that it goes into another method that takes lists as params

sage tendon
#

make it take lists or tuples

#

shouldn't be breaking unless you mess with the list in certain ways in that method

#

they're both collections and iterable

errant trout
#

if you specifically want it immutable and enforced, tuple is exactly what you want

#

if you only care to type it as immutable, then type it as Sequence

echo wraith
sage tendon
#

hm
convert it back to a list when you pass it to the method?

deft hull
#

Hi guys

@bot.command()
@discord.option('amount', input_type=discord.SlashCommandOptionType.integer, min_value=1)
async def give(ctx, amount, target: discord.User):
    ...

Why does this error still appear

AttributeError: Option does not take min_value or max_value if not of type SlashCommandOptionType.integer or SlashCommandOptionType.number
sage tendon
#

it's type for the decorator i think

#

you can just pass it as the second positional argument, just remove the input_type=

#

and you can just use int, you dont have to use the slashcommandoptiontype thing

#

and you should typehint target as discord.Member

deft hull
#

Yeah but I prefer letting discord check for the integer >= 1 instead of writing conditions

sage tendon
#

thats what you should do

fresh sierra
#

@discord.option(‘amount’, min_value=1)
async def give(ctx, amount: int)
Should be the same but you will also get the type hint

sage tendon
#

i never said anything about that part lol

#
@bot.command()
@discord.option('amount', int, min_value=1)
async def give(ctx, amount: int, target: discord.Member):
    ...
#

this is what i meant

deft hull
#

ahh I see thanks

sage tendon
#

in the option to make it immediately obvious just from reading the decorator, and in the function header to get proper autocomplete in the function code

fresh sierra
#

Ok so just for more clarity

sage tendon
#

and type checking in general

#

yea, explicit is better in this case imo

little cobalt
sage tendon
#

i know

round heart
#

This is why decorators for options are stupid

lapis dock
#

shhhh you are going to anger toothy

round heart
#

Let him go on his rampage about being wrong. If you define it in the method args, it's easier to follow and don't have to do it twice.

sage tendon
#

to each their own

#

i prefer clean code, others might not

wary portal
#

Hi, I'm here for some help. I used bot.get_user(), but is there a way to get their display name in a specific server?

frail basin
#

That returns a discord.Member object, which has a .display_name property

sly karmaBOT
echo wraith
#

.rtfm discord.Guild.get_member

sly karmaBOT
sage tendon
wary portal
#

.rtfm discord.Guild.get_member

sly karmaBOT
wary portal
#

Using bot.get_user with the same ID returns a User object.

#

Any idea why that could be happening?

#

.rtfm discord.Guild.get_user

sly karmaBOT
#

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

wary portal
#

ok

#

.rtfm discord.Guild.get

wary portal
#

=========

#

get_member also doesn't work. It returns a nonetype even if im in the guild, right ID, and right Guild ID.

#

Neither doing

members = guild.members
user = discord.utils.get(members, id=1008913569871564811)```
works.
#

I'm in the guild.

sage tendon
errant trout
wary portal
errant trout
#

fetch_guild doesnt return members

#

use the cached guild from get_guild

wary portal
echo wraith
errant trout
#

god no

wary portal
echo wraith
#

buffers

wary portal
#

ooooh.

echo wraith
#

you'd necessairly to create a streamed json parser

#

for it to be remotely ok to use

wary portal
#

not a good idea

echo wraith
#

yeah definitely

errant trout
#

thats kinda how it works in gateway

#

on startup you can receive every member of the guild, though it takes some time when scaling

wary portal
errant trout
#

yeah at that size it's instant

wary portal
errant trout
#

well in the most literal sense, the more members you have naturally the longer it takes

#

if your bot is connected to, let's say, guilds totalling 1 million members, the startup may take a few mins if you intend to receive all of them

lilac stone
#

How to call Pycord coroutine outside of an asynchronous context?
For example, outside a command or event handler

sage tendon
#

what do you wanna actually achieve

lilac stone
sage tendon
#

asyncio ig?

lilac stone
#

I'm wondering if there's some perfect way that's best used

#

When I use the asyncio methods I get
RuntimeError: Timeout context manager should be used inside a task

little cobalt
#

or for what do you need that?

lofty parcel
#

Can't you run the socket server as a bot task?

lilac stone
lilac stone
lilac stone
lofty parcel
#

That's what I do with my web server.

#

That way I can use anything from the bot.

lilac stone
#

I don't want to rewrite half of my code

upper slate
#

Is there a way to purposely stall how long a button takes to respond after being pressed? I've tried using asyncio.sleep() in the button's callback method, but this breaks the button's functionality

sage tendon
#

why do you want to delay the response artificially

upper slate
#

because I want to limit the user from spamming said button

echo wraith
#

just waiting wouldn't change anything

sage tendon
#

okay well it would but.. no, dont do that

upper slate
#

hence why im asking how to stop the user from doing this. I cannot find a solution

echo wraith
#

you can use a ttl cache for example

#

I use aiocache

#

and you add a key for each user that expires after a set time

upper slate
#

dont cooldowns only apply to commands?

echo wraith
#

Here i'm talking about a manual cooldown implementation in your bot

echo wraith
upper slate
#

Gotcha, thank you

frosty trellis
#

what are the benefits of using cogs in my bot? i understand that i can group different commands, but are there any other benefits?

subtle moth
#

You can very well not use cogs at all and struggle a lot to maintain your code structure and quality

#

A wise man once said you read code much more than you write, so write good code that you'd want to read

sage tendon
#

yea a big part is not having a 1000 line long main.py

#

gets hard to maintain fast

humble turtle
#

why do user apps not work

from utils.extensions.user_apps import *
@discord.command(
    integration_types=ALL_INTEGRATIONS,
    contexts=DM_CONTEXTS,
)
class Bot(ezcord.Bot):
    def __init__(self) -> None:
        super().__init__(
            intents=discord.Intents.all(),
            language="auto",
            debug=True,
            error_webhook_url=ERROR_WEBHOOK_URL,
            default_command_contexts={discord.InteractionContextType.guild},
            default_command_integration_types={discord.IntegrationType.guild_install},
#
import discord
from discord import InteractionContextType, IntegrationType

ALL_INTEGRATIONS = {
    IntegrationType.guild_install,
    IntegrationType.user_install,
}
DM_CONTEXTS = {
    InteractionContextType.bot_dm
}
sage tendon
#

User apps work, but you use ezcord, so no clue if they broke it

#

also never seen @discord.command

humble turtle
#

I will take a look with slash_command

sage tendon
#

might be a prefix command in ezcord, no clue what ezcord.Bot subclases

#

also, what exactly doesnt even work
does the command show or not, what happens if you call it..

humble turtle
#

thanks anyway

echo wraith
#

don't use ezcord

sage tendon
humble turtle
#

no i'll ask on the ezcord server

fickle garnet
round heart
#

I just have 1000-line long cogs 😦

lofty parcel
#

Why ask here if you use ezcord

little cobalt
round heart
tender python
#

Is there a way to rate limit slash commands?

frail basin
sage tendon
waxen briar
#

is there a way to send a modal and then followup and edit a message

#

await interaction.response.send_modal(InputModal())
await interaction.response.edit_message(view=view)

like this but w/o the interactionresponded error

deft hull
#

Hi, how do you apply CommandOnCooldown error handling (defined in main script) to commands in other cogs

rugged lodgeBOT
echo wraith
#

to a listener

deft hull
#

thank you 👍

#

how do I uh avoid pasting the same error handling to every cog

#

oh wait it's await

echo wraith
#

you can use on_command_error

#

like this

#
class MyErrorHandlingCog(commands.Cog):
    @commands.Cog.listener()
    async def on_command_error(self, ctx, error) -> None:
        
rugged lodgeBOT
deft hull
#

Yeah but let's say I have this script, I want to apply this to all commands in all cogs i.e. the whole bot

@bot.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.CommandOnCooldown):
        print("Print debug statement")
        await ctx.respond(embed=discord.Embed(
            color=discord.Colour.brand_red(), 
            description="You can use this command again in **{0:,} seconds**".format(round(error.retry_after))
        ))     
flat wind
deft hull
#

it seems non-cog commands also face the same issue. not sure if im doing something wrong

#

I also tried print debugging but it did not appear as well.

#

Update: tried removing the if isinstance statement but the print debug statement did not appear as well

frail basin
deft hull
#

ok. let me try that

#

something like this?

import discord
from discord.ext import commands
from main import MyErrorHandlingCog 

class MoneyGame(MyErrorHandlingCog): ...
# Commands go here

def setup(bot):
    bot.add_cog(MoneyGame(bot))
frail basin
#

I recommend putting it in a separate file, as importing from main is generally a bad idea, but yes.

deft hull
#

nope, still fails

#

The cooldown does work but not the error message

echo wraith
deft hull
#

yeah

#

oh

#

💀

echo wraith
#

then

deft hull
#

thanks 👍

#

i'll be sure to keep that in mind

echo wraith
deft hull
#

yup

deft hull
#

is there a better way to do this

@bot.command()
async def test(ctx):
    """please do not run this"""
    result = await send_confirmation(ctx, ctx.user, "Press Confirm")
    if result:
        result = await send_confirmation(ctx, ctx.user, "I was joking, are you really really sure", followup=True)
        if result:
            result = await send_confirmation(ctx, ctx.user, "last warning, you will be ban", followup=True)
            if result:
                await ctx.followup.send("jk")
            else:
                await ctx.followup.send("ok")
        else:
            await ctx.followup.send("ok")
    else:
        await ctx.followup.send("ok")
#

if/else nests are bad

echo wraith
lofty parcel
waxen briar
#

thanks

#

ill give that a shot

sage tendon
#

Also, don't go that deep into if clauses @deft hull

#

invert them

frosty trellis
#

i'm having some trouble subclassing my bot and adding cogs, do i use commands.Bot for my bot class or do i use discord.Bot for my bot class?

drowsy grove
#

I use commands.Bot

#

and commands.Cog for my cogs

frosty trellis
#

is there any difference?

drowsy grove
#

I would think there isn't, but that's a better question for one of the helpers

frosty trellis
errant trout
#

if your bot is all on slash commands, context menu etc., then discord.Bot is fine

deft hull
#

guys need help

#

How do I edit the original message and send an additional ephemeral message upon interaction (in a view)?

echo wraith
sly karmaBOT
#

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

rugged lodgeBOT
deft hull
#

thanks. May I know why does the following not work?

await interaction.response.edit_message(embed=self.embed, view=self)
await interaction.followup.send_message(embed=discord.Embed(description=text), ephemeral=True)
echo wraith
#

.tag idw

sly karmaBOT
#

Saying it doesn't work or asking what's wrong with this code is not helpful for yourself or others.
Describe what you expect and/or tried (with your code), and what isn't going right.
Please provide any errors you get for optimal assistance.

deft hull
#

Sorry, here is the error.

AttributeError: 'Webhook' object has no attribute 'send_message'
sly karmaBOT
deft hull
#

Ohh thanks 👍

echo wraith
#

np lmk if anything

tender python
#

Using slash commands: How can I respond with "Bot is thinking" and then send the actual response. Discord allows more time to respond when sending a confirmation.

lilac stone
#

.rtfm on_application_command

upper slate
#

How can I create a voice channel that is only joinable if you received an invite link? If there is no direct way to do this, can the bot set a voice channel to only be joinable for certain usernames? (I want to avoid creating roles)

sage tendon
#

sure, you can create overrides for users just like in the UI

#

and no, you can't do the former for all I know

upper slate
#

Thank you. Didn't realize overwrites directly allowed you to input users, not just roles

lapis dock
#

I know there is a way to allow users to join a voice channel (maybe only stage?) with an invite but not actually join the server. I have no idea how that works tho

upper slate
#

Them joining the server is fine. Curious if there is actually a way around that tho 👀

sage tendon
lapis dock
#

^

sage tendon
#

not sure if you can use it here, maybe with some smart permission or role shenanigans depending on your server

maiden bloom
#

I'm adding a premium feature that allows servers to change the embed color for the bot. I'm assuming fetching the guild's entitlements to check it's premium status for every single embed that is sent isn't a great idea.

Would having a scheduled task that runs every hour or so and checks the premium status of a guild and updates it in a database be more efficient or is there an easier method I'm not thinking of?

#

I see there's an event for when a SKU gets purchased, but not for when one has expired/ended

lofty parcel
#

Caching is definitely better.

errant trout
#

if you manage these embeds through interactions, anyway

#

otherwise periodically checking isn't a bad idea

eternal kite
#

is it possible to have image on modal?

lapis dock
#

No

little cobalt
fading crag
#

Quick question:

Can you make subgroups for a BridgeCommandGroup?

I want to have the commands:

game card blackjack (args)
game card war (args)

#

and have them as slash too

echo wraith
#

you would have to define slash and prefix versions separately

errant trout
#

uhhh you could probably try with creating another bridge group and specifying parent

echo wraith
#

see #2035

errant trout
#

otherwise apparently bridge never updated the create_subgroup function

rugged lodgeBOT
fading crag
obsidian stratus
#

My ctx.guild.members returns 4300 while the server has 100k members

I’m trying to get a specific role.members but that also just feels members 5 out of 50 get returned

#

I have all intents enabled and it’s a custom bot

errant trout
#

and show your main bot file

rugged lodgeBOT
echo wraith
#

Use this @obsidian stratus

#

You'll need to fetch the guild before

echo wraith
#

With with_counts=True

errant trout
#

i think they want the actual members, the count was just to demonstrate their issue lol

echo wraith
#

oh maks sense

grizzled loom
obsidian stratus
#

First time it caches less members
Then second and onwards it works perfectly
Then the next 1.5 days it returns no members

grizzled loom
#

soo depending on which loop its in, maybe not the best place.

#

however: b2t

#

would you make it a topic and share code + outcome, so we can have a closer look?

gilded thistle
little cobalt
#

Why should you not able to run it?

gilded thistle
#

Is there a good example that comes to mind of a bot that's also serving requests sent in via a webhook?

In particular, we have logic that serves /commands that we want to also serve an incoming webhook.

E.g. /statistics can be asked for by a user or from e.g. Zapier

And thse webhooks could be channel specific or across the whole server

#

I'm also wondering if Pycord has generic support to make all /commands capable of also serving webhooks

#

Or if this is something we need to build

obsidian stratus
fresh sierra
#

because /command works with a context

#

why the http request doesnt create any

gilded thistle
#

If the webhook supplies user and channel, could it assume values for the rest of context?

#

I assume this is the right documentation- it says pycord 0.1 at the top

lapis dock
#

That is just a bug with the docs. Although you linked the 2.5.x version when latest is 2.6.x

#

You can change that in the little box in the lower right corner

#

I dont know exactly what you are trying to do but it sounds like you should have a structure like this

async def get_the_data(user, channel):
    return ...
@bot.slash_command()
async def stats(ctx):
    await ctx.send(get_the_data(ctx.author, ctx.channel))

// However you return a webhook thing to your service

I cant help more now but feel free to ask more questions

deft hull
#

Are there any optimisations I can do to reduce the latency of my bot? Right now it's at 400ms and I'm unsure if that's normal.

lofty parcel
#

The location of your hosting

fresh sierra
deft hull
#

Ah ok thanks

#

as for the latter err

lapis dock
ionic wasp
#

what is py-cord[speed] lol

lofty parcel
#

Extra dependencies that are supposed to make the library work faster

ionic wasp
#

what extra dependencies? is there a list

lapis dock
#

Probably somewhere. It aiohttp speedup stuff. Apparently it only works on some computer systems tho

ionic wasp
#

only works as in the speed-up effect or it will crash completely?

lapis dock
#

I am not sure, I have never used it

ionic wasp
#

oh alright

lapis dock
#

Thanks defi

frail basin
#

Any ideas?

The bot has full administrator access (top role in the hierarchy), the category has 0 channels so thats also not an issue.

#

Nevermind, didnt specify any of thebeginning, end, before or after params.

#

Though, the error could be a little more descriptive.

tiny fractal
#

having strange behavior suddenly in my but without having made changes. Events all work normally. but no slash command works anymore. and logger set to debug returns zero information when a command is executed. Only get "The application did not respond"

sage tendon
#

did you try a restart?

tiny fractal
#

several times

sage tendon
#

your discord client as well?

tiny fractal
#

yea

#

same result on both desktop and mobile

sage tendon
#

try check this event

#

if that doesnt fire i guess discord somehow fails to send your bot the event?

tiny fractal
#

nothin lol

sage tendon
lapis dock
#

You made sure to use @bot.listner() or similar right?

tiny fractal
#

cog listerner yea

#

it was working fine when i went to bed

#

100% of all of my commands are dead

lofty parcel
#

Did you override on_interaction?

tiny fractal
#

negative

ionic wasp
#

maybe discord ratelimit

#

but i think that would throw a seperate error idk

lapis dock
#

Can you override on_interaction and see if you get any events

tiny fractal
sage tendon
#

slash commands are interactions

tiny fractal
#

i thought you meant in the sense of discord.Interaction

lapis dock
#

You should be able to put that event in place of the one you just had

tiny fractal
#

same thing.

#

no response in console

lapis dock
#

Are you using cogs? If so are you ensuring they are loaded correctly?

tiny fractal
#

yeah they all load

#

even the task loops work fine

sage tendon
#

make a new command and see if that shows up maybe

lapis dock
#

Or try running the basic slash example with your token

rugged lodgeBOT
#

Here's the slash basic example.

tiny fractal
#

made a new command, it registered in discord immediatly. but no execution, and nothing in log

lapis dock
#

Can you show how you are starting your bot and one of the command definitions?

sage tendon
tiny fractal
#

just tried a new fresh bot with token. got nothin

#

gonna reset it

sage tendon
#

and you get the same issue when you run it locally or on your (i assume) server (as in VPS)?

tiny fractal
# lapis dock Can you show how you are starting your bot and one of the command definitions?
@modcmd.command(name='godmode', description='Add or Remove Self From Admin-Mode')
    @commands.is_owner()
    async def godmode(self, ctx: discord.ApplicationContext):
        member = ctx.author
        role = discord.utils.get(ctx.guild.roles, id=ADMIN_ROLE)
        if role in member.roles:
            await member.remove_roles(role)
            await ctx.respond('Removed from Admin-Mode', ephemeral=True)
        else:
            await member.add_roles(role)
            await ctx.respond('Added to Admin-Mode', ephemeral=True)

i start it with systemd or just python main.py

tiny fractal
sage tendon
#

exotic guess would be that something in the network route is somehow blocking those very packets
but idk how discord sends data so no clue if thats even possible

lapis dock
#

It sounds a little bit like you are cloud flare banned but that should be giving you an error

tiny fractal
#

is discord using cloudflare ?

lapis dock
#

yeah

tiny fractal
#

i have an event for creating voice channels if you join a "join to create" channel. that works.

lapis dock
#

or cloudflare somehow comes into the equation

tiny fractal
#

everything about the bot works except for slashcommands

#

it posts logs for every event. like prescense, typing, voice status

lapis dock
#

Try the basic slash example from above please

tiny fractal
#

nope

lapis dock
#

have you enabled logging yet?

sly karmaBOT
tiny fractal
#

yep in debug mode as well

#
DEBUG:discord.client:Dispatching event socket_event_type
DEBUG:discord.client:Dispatching event presence_update
DEBUG:discord.gateway:Keeping shard ID None websocket alive with sequence 5.
DEBUG:discord.gateway:For Shard ID None: WebSocket Event: {'t': None, 's': None, 'op': 11, 'd': None}
DEBUG:discord.gateway:For Shard ID None: WebSocket Event: {'t': 'PRESENCE_UPDATE', 's': 6, 'op': 0, 'd': {'user': {'username': 'cauan1000', 'primary_guild': None, 'id': '1288180297329803351', 'global_name': 'Cauan', 'discriminator': '0', 'clan': None, 'avatar_decoration_data': None, 'avatar': 'f44cb3daf7dbe4511b744a6b9dde42ab'}, 'status': 'online', 'guild_id': 'xxxx', 'client_status': {'mobile': 'online'}, 'activities': [{'type': 4, 'state': 'Vivendo sem ódio 🫠', 'name': 'Custom Status', 'id': 'custom', 'created_at': 1737155361910}]}}
DEBUG:discord.client:Dispatching event socket_event_type
DEBUG:discord.client:Dispatching event presence_update
#

i get these messages only

lapis dock
#

Are you doing anything "weird" with commands or do you think you have a pretty normal setup?

tiny fractal
#

pretty standard. been running untouched for months

#

think the most complex thing i do is reachout to minecraft through RCON

#

or my temporary private voice channel system

lapis dock
#

Can you print
bot._listeners and self._handlers in on_ready

tiny fractal
#
print(f'{bot._listeners} listeners registered.\n{bot._handlers} handlers registered.\n'
{} listeners registered.
{'ready': <bound method Client._handle_ready of <discord.bot.Bot object at 0x7f28eb2ab6e0>>} handlers registered.
lapis dock
#

You are on 2.6.x version of pycord right?

tiny fractal
#

2.6.1

sage tendon
#

python version?

tiny fractal
#

3.12.8

lapis dock
#

This is really weird, if basic bot does not work and you are up to date on other things I feel like it has to be something other than your code

#

You dont have multiple discord bot libraries installed do you (like discord.py, nextcord, etc)

tiny fractal
#

nope. just py-cord

#

ill throw it onto another server quick

#

yep. same problem on cloud vps

#

but my other bots on other servers work

lapis dock
#

Is it specifically that guild? If you try testing your bot on a different guild do the results change?

tiny fractal
#

sec

#

put it in a different guild. got nothing

ionic wasp
#

try different bot token if you havent already

tiny fractal
#

and i was sure to swap guild ids

#

yea i swapped tokens too

#

oh another bots token?

ionic wasp
#

Yes

tiny fractal
#

same issue

ionic wasp
#

there really arent that many possible cases left then

#

pretty much HAS to be something with the code

sage tendon
#

not really at all

#

we basically completely ruled the bot code out by now

lapis dock
#

Can you make sure this is not set

tiny fractal
#

OOH SHIT

sage tendon
#

bruh moment

ionic wasp
#

oh trol

tiny fractal
#

maybe it takes a while to propogate after removing that

#

i put the damn endpoint url in the wrong bot

lapis dock
#

Make sure you hit save in the dev portal. Then you probably have to restart the bot again

tiny fractal
#

ill let the bot sit offline a while. still borked. WTB ctrl+f5 for bots

sage tendon
#

i mean, stopping the bot does clear the cache lol

tiny fractal
#

well it's lying

#

this is some how now a DNS issue

#

because you know the poem

sage tendon
#

wrong link

#

1s lmfao

#

damnit i cant find what i wanted

#

omg i did

tiny fractal
#

thats the one

#

there we go. i reset my token again and magic

#

sorry for the missing curly brace moment

lapis dock
#

🎉
I was like you would know if you changed something in the dev portal. But it makes 100% sense how you would accidently do that.

tiny fractal
#

yea my bots are named Axon, and Axon Verifiy

lapis dock
#

I am probably going to change my bots name one of these days because my password manager autofills my discord username into the bot username field everytime I open the dev portal facepalm

tiny fractal
#

lol

#

ProtonPass does that shit to me too

#

sometimes it enteres my password as the username

sage tendon
#

ProtonPass is legit ass
Tried to use it but nothing beats bitwarden

tiny fractal
#

i like it, specially the passkey functionality

sage tendon
#

bitwarden has it too

tiny fractal
#

just where i jumped to after lastpass failures. i got the unlimited subscription to the proton stack. i can't be bothered to hop again for a while

#

man i need to write a mod for discord where shell commands work in the text box. like ctrl-a and ctrl-e

dry gust
#

is this normal when I'm trying to import pycord's discord package

ionic wasp
#

happens on python 3.13+
either downgrade or manually install (i forgot the command tho)

dry gust
#

wia pip install you mean?

ionic wasp
#

Yes

sage tendon
#

pip install audioop-lts

ionic wasp
#

^

dry gust
#

thx

sage tendon
#

afaik 3.13.1 doesnt work at all tho, i think there was some bug

dry gust
#

damn

#

glad Im only on 3.13 hahayes

fathom barn
#

ive been using 3.13.1 perfectly fine

#

i did have to install audioop-lts but thats because it was removed in 3.13 after being deprecated in 3.11

#

other than that, no issues so far

tiny fractal
#

why does making database querys cause discord to rate limit, but when i comment out database querys. everything is fine

sage tendon
#

you mean it times out?

#

database queries can take some time and unless you defer, you can't respond to an interaction after 3 seconds

tiny fractal
#

no it force restarts the bot

2025-01-18 09:00:13,755:INFO:discord.client: Cleaning up tasks.
2025-01-18 09:00:13,755:INFO:discord.client: Cleaning up after 2 tasks.
2025-01-18 09:00:13,756:INFO:discord.client: All tasks finished cancelling.
2025-01-18 09:00:13,756:INFO:discord.client: Closing the event loop.
sage tendon
#

lol what

tiny fractal
#

i have an on_message event that makes a db query

sage tendon
#

async?

tiny fractal
#

yes

sage tendon
#

show your on message

tiny fractal
#
@commands.Cog.listener()
    async def on_message(self, message: discord.Message):
        if message.author.bot:
            return
        
        db = AsyncSurrealDB(self.db_host)
        await db.connect()
        await db.sign_in(self.db_user, self.db_pass)
        await db.use(self.db_namespace, self.db_db)

        select_query = f"SELECT * FROM activity WHERE member_id = '{str(message.author.id)}'"
        result = await db.query(select_query)
        
  
        if result and result[0].get('result'):
            update_query = f"UPDATE activity SET last_active = time::now() WHERE member_id = '{str(message.author.id)}'"
            result = await db.query(update_query)
            logger.info(f"{result}")

        else:
            insert = await db.create('activity', {
                
                "member_id": str(message.author.id),
                "last_active": "time::now()"
            })
            logger.info(f"{result}")
  
        await db.close()
sage tendon
#

do you get a high amount of messages per second?

tiny fractal
#

zero messages per day

#

its jsut me

sage tendon
#

lol

sage tendon
tiny fractal
#

it does not

#

surrealdb queries are sub nano second responses

sage tendon
#

where does it get to

tiny fractal
#

i dunno it just restarst the bot on message

#

it doesn't execute any of the logger methods

sage tendon
#

what is your self.db_host exactly

tiny fractal
#

localhost

torn barn
#

you should also consider not creating a new connection every time you receive a message but instead use some db pool

sage tendon
#

can you just put a print after each of the first 3 db lines

#

I think that the DB somehow interferes with the discord event loop

tiny fractal
#
2025-01-18 09:07:48,221:INFO:discord: connect: <surrealdb.async_surrealdb.AsyncSurrealDB object at 0x7eff16186ed0>
2025-01-18 09:07:48,271:INFO:discord: signin: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpYXQiOjE3MzcyMTI4NjgsIm5iZiI6MTczNzIxMjg2OCwiZXhwIjoxNzM3MjE2NDY4LCJpc3MiOiJTdXJyZWFsREIiLCJqdGkiOiJiOTg2MDk5Yy02MDQ3LTQ3NjktYWE3NC0zYjcxNzZkZjMyMGIiLCJJRCI6InJvb3QifQ.BzoqBrG0tF5rnNXTKtckRN6Er4nfciJ1LY8G4aJNccIA8jSBf4GOR_UM_uIY2jLp53PfCv0a4725cPLNpMLucg
2025-01-18 09:07:48,272:INFO:discord: use: None
#
2025-01-18 09:07:54,987:WARNING:discord.http: We are being rate limited. Retrying in 21.05 seconds. Handled under the bucket "None:1313644334465421312:/applications/{application_id}/guilds/{guild_id}/commands"
sage tendon
#

huh

#

do you ever manually sync commands anywhere?

tiny fractal
#

never

lapis dock
#

You can't be rate limited if you are not sending requests...

torn barn
#

maybe auto syncing

tiny fractal
#

modcmd = discord.SlashCommandGroup(name='mod', description='Moderation commands', guild_ids=[GUILD_ID])

#

thats how i do my commands

torn barn
#

try disabling auto syncing

sage tendon
tiny fractal
#

well if i comment out the db queries in on_message. all the problems disappear

#

goes back to normal operation

torn barn
#

huh

sage tendon
torn barn
#

yeah, that could not happen

lapis dock
#

Is it possible the DB is emiting the same error we catch for rate limits?

torn barn
#

ratelimit errors are on the HTTPClient.request method

#

so, it should not

tiny fractal
sage tendon
#

can you find out exactly which line it gets to before it shuts down? might help

tiny fractal
#

('no decoder for tag', 12)

#

lol now i get this

#

and immediat kill of the bot

sage tendon
tiny fractal
#
connecting to db
signing in
using db
('no decoder for tag', 12)
sage tendon
#

can you wrap all of your db stuff in a try except and print the type

#

kinda poking into nothing here but this is a very weird problem lol

tiny fractal
#

try except yields nothing

#
        await self.db.connect()
        print("connecting to db")
        await self.db.sign_in(self.db_user, self.db_pass)
        print("signing in")
        await self.db.use(self.db_namespace, self.db_db)
        print( "using db")
   
        
        select_query = f"SELECT * FROM activity WHERE member_id = '{str(message.author.id)}'"
        result = await self.db.query(select_query)
        print( f"result: {result}")

        if result and result[0].get('result'):
            print( "exist")
            update_query = f"UPDATE activity SET last_active = time::now() WHERE member_id = '{str(message.author.id)}'"
            result = await self.db.query(update_query)
            print( f"update: {result}") 
            logger.info(f"update: {result}")
        else:
            print( "not exist")
            insert = await self.db.create('activity', {
                
                "member_id": str(message.author.id),
                "last_active": "time::now()"
            })
            print( f"insert: {insert}")
            logger.info(f"insert: {insert}")
torn barn
#

yeah, wrap all of that on a try / except block