#Basic Pycord Help

1 messages Β· Page 54 of 1

lethal loom
#

hm ok

sage tendon
#

pass the bot variable to the RoleButton, then pass it on to the modal

#

currently your bot variable just points to the class

lethal loom
#

but when i dont user from bot Import Bot how can i use it herte? (this is outside a cog)

    def __init__(self):
        super().__init__(
            label="Verifiziere dich hier!",  # Text auf dem Button!
            style=discord.enums.ButtonStyle.blurple,  # Button-Fabre!
            custom_id="interaction:RoleButton",
            emoji=":greentickincircle_xenority:"
        )

    async def callback(self, interaction: discord.Interaction):
        verify = random.randint(1, 2)
        user = interaction.user

        role = interaction.guild.get_role(SERVER_SYSTEM["verify_role_id"])

        if role is None:
            return

        if role not in user.roles:
            modal = verify1(Bot, title="Xenority")
            if verify == "1":
                modal = verify1(Bot, title="Xenority")
            if verify == "2":
                modal = verify2(Bot, title="Xenority")
            await interaction.response.send_modal(modal)

        else:
            await interaction.response.send_message(f":x: Du bist bereits verifiziert!", ephemeral=True)
#

interactiomn.client?

sage tendon
#

pass it when creating it

#

RoleButton(bot)

lethal loom
#

self.not

#

bot

little cobalt
#

Timeout None at the view class

lethal loom
#
    async def on_ready(self):
        view = discord.ui.View(timeout=None)
        view.add_item(RoleButton(self.bot))```
#

so right

sage tendon
#

try it and see

lethal loom
#

ok thx ❀️

little cobalt
#

Now I wonder how you send the view

#

;3

#

@lethal loom

lethal loom
little cobalt
#

uh...

sage tendon
#

do you even call self.bot.add_view

lethal loom
#

Yeah on the sartup

sage tendon
#

and yea, idk how it works if you just take the bare View class to do that with
I'd always make a subclass

little cobalt
#

Is it working?

lethal loom
#

yeah

sage tendon
#

that probably makes all views of your bot permanent now lol

lethal loom
#

XD yeah

little cobalt
#

I subclass all the button and view classes

sage tendon
#

me only the views, i dont see a point subclassing the buttons

lethal loom
#

its a old code from me i do all in a class like button a class button a ::::

proven valley
#

is there a way to put the funciton for each of my commands in different files to stay a bit more organized? the cogs are nice but I want to take it a step further if possible

sage tendon
#

i mean, make more cogs then lol

#

or do you mean moving the actual code of each command somewhere else? because that is pointless for most commands

proven valley
#

for most commands

#

just a few of my commands have a bit attached to them

errant trout
#

Well, what's your idea of "a step further" with cogs

dense summit
#

Hey there, i started to working on a feature in my bot and i thought about using the tasks extension although i have some questions. The feature should allow a user to start a monitor that sends a request every X seconds to an api endpoint till X parameter is true. With tasks how would i go about starting a task that is linked to a user?

sage tendon
# proven valley this is what I mean

If you have code that multiple commands need, you should put that into helper functions
But if its just one command with a big blob of unique code, i leave it like that

fresh sierra
sage tendon
#

they want the command code in another place than the cogs

lofty parcel
#

It surprisingly worked.

#

But I'm sure there's a better practice for it lol

errant trout
#

if they're strictly short term tasks, while is probablyyyy easier?

#

the problem with using task loops when it comes to user customization is that it becomes a hassle at that point

dense summit
errant trout
#

eh then you probably do want tasks...

#

i guess you can fully create and start a task inside your command

dense summit
#

Yeah, but i don't know how would i go about stopping a specific monitor instead of another, if i was able to let's say create a task and assign it a name it would be amazing

errant trout
#

then the end of the task callback can just destroy itself if it's the correct result

errant trout
dense summit
errant trout
#

so let's say you're creating a task

dense summit
#

alr

errant trout
#

then you can do self.tasks["some_name"] = task

#

where task is the loop you've created

dense summit
#

mhm

errant trout
#

well that's basically it

#

now you have a reference to your task, you can do what you want with it

dense summit
errant trout
#

you only need a single self.tasks dict

#

just decide on a unique reference whenever a user creates a task

#

e.g. if a user can only have one task at once, just make it their user id

dense summit
#

oh alr im going to try when im home, it isnt really clear but something should come out

errant trout
#

though note that with a method like this, the tasks would be lost whenever the bot shuts off

#

so perhaps you want to save the necessary data required to re-create each task after a restart

dense summit
errant trout
#

well if you only store it in variables/dicts, you can't exactly save the function outside (well, you could, but it's not very pretty)

#

so just save the necessary parameters (link, seconds delay, user id, etc. etc.) and recreate it on startup

dense summit
#

it would have been much easier if the task create function had a parameter like name to get it πŸ˜΅β€πŸ’«

errant trout
#

well the problem is that tasks aren't stored in pycord itself

#

asyncio handles their management

dense summit
#

ah i see, im going to try your way even tho i didnt understand it fully

errant trout
#

i guess i'll write a vague example

dense summit
#

if you have time it would be amazing

errant trout
#

VERY loose example, assuming this is in a cog context```py
...
self.bot = bot
self.tasks = {}

async def command_to_create_tasks(self, ctx, ...):

@tasks.loop(seconds=...)
def task():
x = await request(...)
... # other logic to determine if result is correct

self.tasks[...] = task
task.start()

include some way to write relevant data to a file or database

await ctx.respond(...)

opal swan
#

is it possible to use discord.Spotify like get a song information by his name or we need use spotify api or smthing else

errant trout
#

i don't THINK that's exposed

#

but lemme see

opal swan
#

alr tu

#

ty

little cobalt
opal swan
#

alr let's see it

errant trout
#

oh actually, perfect

#

just check in user.activities

#

list of all activities, spotify does show up

#

(i think it only works on members)

dense summit
opal swan
#

nah imo u don't know wth I mean...
like a thing like this code :

async def get_spotify(ctx, name : str) -> discord.Spotify:
    spotify = # get the spotify by his name
    await ctx.reply(content=spotify.album)
errant trout
#

allgood

#

ohh

#

no you'd have to use the spotify api

opal swan
#

ok bcs I though I can use the discord.Spotify class like discord.Embed

errant trout
#

well users don't use the Spotify class

#

it's only used to retrieve someone's spotify status on their profile

opal swan
#

ye it's with activities ik

opal swan
#

ty for the information also

errant trout
opal swan
#

wth meaning "nullable"

errant trout
#

bar on the right makes testing very easy, have fun

#

nullable means either it can be null (None in python)

#

or it won't appear at all in the response

opal swan
#

ohhh ye I see

#

ty

errant trout
#

allgood

opal swan
#

like it return a thing if it have a result else it's None

#

is it right ?

errant trout
#

uhhh possibly? i'd just recommend testing it a fair bit and being careful when parsing the response

opal swan
#

πŸ‘Œ

opal swan
#

i'm beginner in slash command so what is "Autocomplete" ?

#

it's not this thing with multiple choice where I can choose

granite pier
opal swan
#

const ?

tidal vessel
# opal swan const ?

In simple terms, autocomplete returns options dynamically based on the previously selected option.
If you want options that do not change you must use the choices parameter

granite pier
#
choices=["a", "b", "c"]
async def get_items(ctx: discord.AutocompleteContext):
  # dynamic get e.g. database query, array filter
...
autocomplete=get_items
opal swan
opal swan
granite pier
lapis dock
#

Discord has a built in member option that is different from autocomplete.

#

That is what yoggies showed

opal swan
#

😭

#

idk why

lapis dock
#

Can you show your code

errant trout
#

probably went wrong and fellback to string instead

opal swan
#

πŸ˜‚

lapis dock
#

That should be true by default, unless you made it false.
Also remember to always reload the discord client whenever you make changes to the command or command options

opal swan
#

it's prob this

autumn narwhal
#

is there have a way to handle the error that from the autocomplete?

real glacier
#

how to give custom view a new pagination, and not sync to the previous pagination anymore?

#

i mean, adding a new pagination to the custom view

errant trout
shadow sigil
#
Traceback (most recent call last):
  File "D:\GitHub\fractal-rhomb\.venv\Lib\site-packages\discord\commands\core.py", line 138, in wrapped
    ret = await coro(arg)
          ^^^^^^^^^^^^^^^
  File "D:\GitHub\fractal-rhomb\.venv\Lib\site-packages\discord\commands\core.py", line 1078, in _invoke
    await self.callback(self.cog, ctx, **kwargs)
  File "D:\GitHub\fractal-rhomb\cogs\fractalthorns.py", line 272, in single_image
    await ctx.respond(response_text, file=file)
  File "D:\GitHub\fractal-rhomb\.venv\Lib\site-packages\discord\interactions.py", line 618, in respond
    return await self.followup.send(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\GitHub\fractal-rhomb\.venv\Lib\site-packages\discord\webhook\async_.py", line 1769, in send
    params = handle_message_parameters(
             ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\GitHub\fractal-rhomb\.venv\Lib\site-packages\discord\webhook\async_.py", line 688, in handle_message_parameters
    "value": file.fp,
             ^^^^^^^
AttributeError: 'NoneType' object has no attribute 'fp'
```...huh?
can file not be set to none or something?
shell radish
#

file is used to upload; if you want to edit the current message, you use attachments

shadow sigil
#

i mean
that doesn't address what i said at all
but also i'm not editing a message

errant trout
#

(some methods still use utils.MISSING rather than None)

shadow sigil
#

that's what i changed it to
it's just... why...

late slate
#

If I needed to impose a strict character set limit for the str input of a discord.Option (eg. "can only contain characters A-Z, 0-9"), would this best be done with input_type = <some defined ext.commands.Converter class>? I don't know much about Converters yet, but wanted to make sure I was on the right track before going down this rabbit hole, haha

opal swan
#

in slash command @commands.is_owner, is other guys see this command ? or no ?

tidal vessel
little cobalt
#

because discord does not have it as a permission

hazy turret
#

I have uploaded emojis to my bot and am trying to retrieve them like this

emoji = self.bot.get_emoji(1277980926566994022)```
But I always get none in return
hazy turret
sly karmaBOT
# hazy turret I have uploaded emojis to my bot and am trying to retrieve them like this ```py ...

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

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

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

hazy turret
# little cobalt .tag get_x

Yes I am aware of that but there is no fetch_emoji method. How can I get the emojis into the cache then? πŸ˜„

little cobalt
#

?

hazy turret
little cobalt
#

but for that you dont use the get_

hazy turret
little cobalt
#

I dont know if its even got added to py-cord

hazy turret
lethal loom
#

How can i fix this

  if not message.content and not getattr(message, 'interaction_metadata', None) and not getattr(message, 'interaction', None):
/home/container/.local/lib/python3.10/site-packages/chat_exporter/construct/message.py:184: DeprecationWarning: interaction is deprecated since version 2.6, consider using interaction_metadata instead. See https://discord.com/developers/docs/change-log#userinstallable-apps-preview for more information.
  if not message.content and not getattr(message, 'interaction_metadata', None) and not getattr(message, 'interaction', None):```
frail basin
#

Thats something the chat exporter lib's maintainers have to fix

errant trout
#

well not even an error, just a deprecation warning

opal swan
#

how to "add_command" (slash command) in a cog ?

little cobalt
#

you load the cog with the commands in it

opal swan
#

nah I fixing that I just fix that

#

:

#

commands.command -> discord.slash_command

little cobalt
#

lol

#

commands.command are prefix commands

opal swan
#

ye but I was confused

#

😭

digital bear
#

Lately I have been seeing a lot of these warnings
28/08/2024 15:40:50 - WARNING - We are being rate limited. Retrying in 0.56 seconds. Handled under the bucket "1028291225255678022:None:/channels/{channel_id}/messages/{message_id}"
Does anyone know what causes it?

sage tendon
#

are you fetching messages a lot?

digital bear
sage tendon
#

most likely yes

#

judging from the rate limit message

digital bear
mellow pebble
#
  new_cls.__cog_commands__ = tuple(c._update_copy(cmd_attrs) if not hasattr(c, "add_to") else c for c in new_cls.__cog_commands__)  # type: ignore```
#

so what to do with this

#

[ - ] Failed To Load COGs : Extension 'COGS.Stocks' raised an error: TypeError: 'BridgeOption' object is not callable

sage tendon
#

show your code

little cobalt
#

And maybe also your pip list

mellow pebble
#
    @stock.command(
        name="quote",
        description="Get The Current Price Of A Stock",
    )
    @BridgeOption(
        "symbol",
        description="The Stock Symbol",
        choices=["AMD", "APPLE", "INTEL", "GOOGLE", "MICROSOFT"],
    )
    async def quote(self, ctx, symbol):

        await ctx.defer(ephemeral=True)

        valid_symbols = ["AMD", "APPLE", "INTEL", "GOOGLE", "MICROSOFT"]

        if symbol not in valid_symbols:
            embed = discord.Embed(
                title="Invalid Symbol",
                description="Please Enter A Valid Symbol",
                color=0xFF0000,
            )

            embed.add_field(
                name="Valid Symbols",
                value="AMD, APPLE, INTEL, GOOGLE, MICROSOFT",
                inline=True,
            )

            await ctx.respond(embed=embed, ephemeral=True)
            return

        symbols = {
            "AMD": "AMD",
            "APPLE": "AAPL",
            "INTEL": "INTC",
            "GOOGLE": "GOOGL",
            "MICROSOFT": "MSFT",
        }

        try:
            main_symbol = symbols[symbol]
        except Exception as e:
            main_symbol = symbol.upper()

        try:
            quote = self.finnhub_client.quote(symbol=main_symbol)

            if quote:
                embed = discord.Embed(
                    title=f"{symbol} Stock Quote",
                    description=f"### Current Price: ${quote['c']}",
                    color=0xD5E4CF,
                )

                await ctx.respond(embed=embed, ephemeral=True)

        except Exception as e:
            pass

sage tendon
#

please add py after the first set of back ticks lol

#

ah yea, it's probably @bridge_option

mellow pebble
mellow pebble
sage tendon
#

actually I'm looking at the docs rn and there doesn't seem to be a bridge option decorator (?)

mellow pebble
# sage tendon actually I'm looking at the docs rn and there doesn't seem to be a bridge option...

yea, that's what i also saw .... still getting the error

/root/Fallen-SMP-BOT/COGS/Stocks.py:340: DeprecationWarning: Using Option for bridge commands is deprecated since version 2.5 and will be removed in version 2.7, consider using BridgeOption instead. See https://github.com/Pycord-Development/pycord/pull/2417 for more information.
  async def buy(self, ctx, symbol: str, quantity: int):
/usr/local/lib/python3.10/dist-packages/discord/cog.py:234: DeprecationWarning: Using Option for bridge commands is deprecated since version 2.5 and will be removed in version 2.7, consider using BridgeOption instead. See https://github.com/Pycord-Development/pycord/pull/2417 for more information.
  new_cls.__cog_commands__ = tuple(c._update_copy(cmd_attrs) if not hasattr(c, "add_to") else c for c in new_cls.__cog_commands__)  # type: ignore
/usr/local/lib/python3.10/dist-packages/discord/cog.py:234: DeprecationWarning: Using Option for bridge commands is deprecated since version 2.5 and will be removed in version 2.7, consider using BridgeOption instead. See https://github.com/Pycord-Development/pycord/pull/2417 for more information.
  new_cls.__cog_commands__ = tuple(c._update_copy(cmd_attrs) if not hasattr(c, "add_to") else c for c in new_cls.__cog_commands__)  # type: ignore

sage tendon
#

then you'll probably have to use the typehint method

mellow pebble
sage tendon
#

is what

mellow pebble
#

what were you saying about typehint method

#

how do i use it ?

sage tendon
#

async def command(self, ctx, thingy: BridgeOption(stuff here))

mellow pebble
#

nvm it worked

little cobalt
#

name: BrideOption()

mellow pebble
#

using bridge_option

sage tendon
#

lol

#

then that's just not documented

little cobalt
mellow pebble
#

yea i missed one option

mellow pebble
mellow pebble
sage tendon
#

forget what I said about the typehint then

#

should probably be documented tho lol

little cobalt
#

We are missing some stuff at the docs xd

#

same for the examples

mellow pebble
#

yea u should update the examples

#

πŸ₯²

sage tendon
#

I thought everything was updated automatically by just reading the docs in the code
apparently not

mellow pebble
#

especially the bridge commands, theier docs need to be updated

sage tendon
#

because they're special and weird

mellow pebble
#

i agree special but wierd

#

i am stuck ina situation i have to use them

sage tendon
#

why can't you go slash only

little cobalt
#

I also only use slash commands

sage tendon
#

yea I refuse to do prefix too, and no one ever uses prefix anymore imo

mellow pebble
shell radish
#

what

mellow pebble
mellow pebble
sage tendon
#

No

#

mobile has a lot of bugs but slash commands work fine

mellow pebble
#

hmm ic

#

like i see people just typing /whitelsit

#

instead of triggering the whitelist cmd

sage tendon
#

that's a user issue

shell radish
#

that's a skill issue

sage tendon
#

they're just doing it wrong, that's it

mellow pebble
#

XD

shell radish
#

i can also type /whitelsit on pc

sage tendon
#

on mobile you need to click the commands for them to actually register
if not you're just sending a message

#

on PC it will automatically select a command if you type the correct name

mellow pebble
#

ohh .. bruh then why am i working so hard

#

for other's skill issue

sage tendon
#

it's incredible how people are apparently still incapable of using slash commands
they're so old by now

mellow pebble
#

true

little cobalt
#

Its incredible that people still not reading the docs

sage tendon
#

lol

shell radish
#

hasn't it literally been 3 years?

sage tendon
#

if not more

shell radish
#

yeah, they were released in dec 2020

#

so almost 4 years

sage tendon
#

can i trust this to work? I'm not sure at what stage in starting the bot cogs are loaded
just wanna make sure i can trust on this .get_guild

fresh sierra
#

So get_guild might return None

edgy nest
#

tasks have a handy dandy before_loop method that you can use to wait before starting

#

and bot has a wait_until_ready

little cobalt
#

I wonder if its working with client.login

fossil valve
#

I'm using the on_application_command_error event to handle my slash command errors. But when I raise them in my code they are still handled by the event, but I also see the error in console. Why is this?

Console error:

[ERROR] Error while executing /stats 
Traceback (most recent call last):
  File "E:\Anwender\Documents\GrinMaxTracking Bot\.venv\Lib\site-packages\discord\commands\core.py", line 138, in wrapped
    ret = await coro(arg)
          ^^^^^^^^^^^^^^^
  File "E:\Anwender\Documents\GrinMaxTracking Bot\.venv\Lib\site-packages\discord\commands\core.py", line 1078, in _invoke
    await self.callback(self.cog, ctx, **kwargs)
  File "E:\Anwender\Documents\GrinMaxTracking Bot\cogs\stats.py", line 30, in _display_stats
    deals = await self.db.get_deals_in_date_range(date_range)
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "E:\Anwender\Documents\GrinMaxTracking Bot\data\database.py", line 77, in get_deals_in_date_range
    raise DatabaseEmptyError(date_range)
utils.exceptions.DatabaseEmptyError: No deals found in the database for the period: Today

I raise it this way:

        if not documents:
            raise DatabaseEmptyError(date_range)

here I call the error_reporter in bot.py :

    async def on_application_command_error(
        self, context: ApplicationContext, exception: DiscordException
    ) -> None:
        await ErrorReporter(self).report_error(context, exception)

Error reporter:

        error = getattr(error, "original", error)

        if isinstance(error, DatabaseEmptyError):
            await ctx.respond(embed=ErrorEmbed(error.message), ephemeral=True)```
fresh sierra
#

Well it is

#

Can you share the code of the command ?

fossil valve
# fresh sierra Can you share the code of the command ?

Yes:

@slash_command(name="stats", description="Display deal statistics and charts in the selected timeframes")
    @option(
        name="period",
        choices=["Today", "This Week", "This Month", "Past 3 Months", "Past 6 Months", "This Year", "All Time", "Custom"],
        required=False,
        default="Today",
        default_member_permissions=discord.Permissions(administrator=True)
    )
    async def _display_stats(self, ctx: discord.ApplicationContext, period: str):
        date_range = DateRange(period)

        deals = await self.db.get_deals_in_date_range(date_range)

        deal_stats = DealStats(ctx, deals, date_range)
        await ctx.respond(embed=await DealStatsEmbed.create(ctx, deal_stats, period))
#

I raise the error in the get_deals_in_date_range method

fresh sierra
sage tendon
#

yea

fossil valve
# fresh sierra That why ig

sadly still the same when I raise it directly in the cog:

        date_range = DateRange(period)

        deals = await self.db.get_deals_in_date_range(date_range)
        if not deals:
            raise DatabaseEmptyError(date_range)```

Error:

File "E:\Anwender\Documents\GrinMaxTracking Bot\cogs\stats.py", line 39, in _display_stats
raise DatabaseEmptyError(date_range)
utils.exceptions.DatabaseEmptyError: No deals found in the database for the period: Today

fresh sierra
fossil valve
fresh sierra
#

on_command_error(): pass

#

Does it still occur ?

#

Don’t think it will resolve it but we never know

fossil valve
#

still not working maybe it is because I use also the ezcord library

#

yes it was because of the additional ezcord error handling

lofty parcel
#

You shouldn't use two libraries for the same thing at the same time...

fossil valve
lofty parcel
#

What

#

For what

#

What does it even do

fossil valve
fossil valve
echo wraith
#

why do I feel like ezcord dosen't make things easier?

sage tendon
#

cog loading is a single line..

errant trout
#

you can disable ezcord's error handler by passing error_handler=False in the Bot init

fossil valve
#

Yes, that worked. I also needed to remove the error_webhook_url in the Bot init

opal swan
#

my IDE error :

#

my code

#
    @discord.slash_command()
    @commands.has_permissions(manage_messages=True)
    async def say(self, ctx : discord.ApplicationContext,  channel : discord.Option(discord.TextChannel, required=False), msg : discord.Option(str)):
        await ctx.channel.send(msg)
sage tendon
#

use the @discord.option() decorator instead of the typehint method

opal swan
#

alr ty

opal swan
#

how to use it

#

like a variable

sage tendon
#

welp, guess no example for you rn :>

opal swan
#

need I use it ?

sage tendon
#

wait why does a direct link to the guide work lol

opal swan
#

idk

#

πŸ˜‚

sage tendon
opal swan
#

oh I see

ivory wind
#

hello, i am trying to make a slash command administrator only. i have the following code but a test user can see the command. is there a way to hide it from non admins?

@commands.slash_command(guild_ids=[guild_id], name='open', description='Opens game chat.')
@commands.has_permissions(administrator=True)
...
shell radish
#

@discord.default_permissions(admininistrator=True)

ivory wind
#

thank you!

sage tendon
#

also you can use @discord.slash_command, bit shorter to type

late slate
#

If I needed to impose a strict character set limit for the str input of a discord.Option (eg. "can only contain characters A-Z, 0-9"), would this best be done with input_type = <some defined ext.commands.Converter class>? I don't know much about Converters yet, but wanted to make sure I was on the right track before going down this rabbit hole, haha

#

I guess there's no way to sanitize this during input, and will just have to do it in the function itself?

shell radish
granite pier
#

but just for user hints (it still can accept other things)

#

so something like:

def parse_input(value: str) -> str:
    # let's say I want only 1-9
    parsed_value = ""
    for char in value:
        if char in digits:
            parsed_value += char
    return parsed_value


def input_autocomplete(ctx: discord.AutocompleteContext) -> list[str]:
    value = ctx.options.get("value", "")
    return [parse_input(value)]


@discord.slash_command()
async def command(
    self,
    ctx: discord.ApplicationContext,
    value: discord.Option(
        str, autocomplete=input_autocomplete
    )
) -> None:
    value = parse_input(value)
    ...
errant trout
#

strictly speaking building a custom converter and catching the issue in checkfailure would also work

deft kestrel
#

How to shard a bot in pycord?

sly karmaBOT
#

Tag not found.

echo wraith
deft kestrel
deft kestrel
#

How do some bots don't have "playing" status but only that?

fresh sierra
deft kestrel
little cobalt
deft kestrel
little cobalt
#

3 oder 4 only?

deft kestrel
#

I mean VPS

deft kestrel
little cobalt
#

I mean at how many server is your bot?

deft kestrel
little cobalt
#

why?

deft kestrel
#

Just to know if it is possible and how

echo wraith
little cobalt
#

still why?

deft kestrel
little cobalt
#

Why should you need it?

echo wraith
fresh sierra
#

for cluster maybe

river oriole
#

Can I not use autocomplete in BridgeOptions for the SlashCommands?

fresh sierra
#

like just dont put autocomplete in ur option if u dont want it

river oriole
#

I want autocomplete. I ask if BridgeOptions support it

fresh sierra
#

why add not ?

#

but yes u xan

#

using @bridge.bridge_option()

deft kestrel
river oriole
# fresh sierra using @bridge.bridge_option()

I do it like this. That should work then too

async def banned_users_autocomplete(
        self, ctx: discord.AutocompleteContext
    ) -> List[discord.User]:
        return [
            banentry.user for banentry in await ctx.interaction.guild.bans().flatten()
        ]

    @bridge.bridge_command(name="unban", description="Unbans a user")
    @isStaff()
    async def unban(
        self,
        ctx: bridge.BridgeContext,
        user: bridge.BridgeOption(
            discord.User,
            "The user you want to unban",
            autocomplete=banned_users_autocomplete,
        ),
    ):
deft kestrel
# deft kestrel

Which permission can I ask more without having approved "intents"

lapis dock
deft kestrel
# errant trout wdym

Like permission to set profile activity needs some extra permission from discord

errant trout
deft kestrel
errant trout
#

Oauth permissions generally don't require any permission from discord, because the end user has to authorize

deft kestrel
# deft kestrel

There's like when I receive a message the bot answer as "me"?

#

Or isn't possible

errant trout
#

That'd be userbotting, which is a no go

deft kestrel
#

Just app commands?

errant trout
#

Well, user installable apps let the end user use the allowed commands anywhere rather than just specific guilds

#

Basically yeah, just app commands tied to the user

deft kestrel
#

Damn

#

Thank you

deft kestrel
#

Is it possible to see who deletes the message in s server?

shell radish
#

audit log could give you the answer

digital bear
opal swan
fresh sierra
#
  • its not an error but a warning from vsc
opal swan
compact oasis
#

what is wrong?

sage tendon
#

it quite clearly says whats wrong

#

you're passing a positional argument to the slash_command decorator, and it takes no positional arguments

#

and you should add self.bot.wait_until_ready() in your task

#

and, what

#

ngl with the comments too it just feels like an outdated / bad bot template or chatgpt

zealous kindle
#

gschmarre

zealous kindle
sage tendon
#

No

zealous kindle
#

yes

sage tendon
#

No.

zealous kindle
#

Yes.

sage tendon
#

.all() applies all intents

#

as should be clear from the name

zealous kindle
#

clearly

#

but its does work so far

sage tendon
#

its unnecessary, hence i said that

zealous kindle
#

test it

sage tendon
#

i use .all() in my bot

#

and i can read the docs

zealous kindle
#

too

zealous kindle
sage tendon
#

and the code

zealous kindle
sage tendon
#

you dont even need that
it takes on the function name

zealous kindle
#

that ist the error

sage tendon
#

or they can just leave it out entirely

fresh sierra
errant trout
#

cogs also use the class name

#

if you want to pass a different name, you have to use the name kwarg

fresh sierra
#

So technically it’s the same here without ?

#

Or it’s different with discord.Cog

errant trout
#

(and that is the correct usage)

fresh sierra
#

Ok, why name is a kwarg and not an arg ?

errant trout
#

well

#

where would you put it as an arg :)

fresh sierra
#

I don’t really know the diff with arg and kways

#

Does arg are mandatory and lways not ?

shell radish
#

technically all kwargs are args

errant trout
#

well most of pycord disables that kind of behavior

#

but yes

fresh sierra
errant trout
#

if a python function has listed arguments, you can always refer to them by name

#

e.g. ```py
def foo(bar):
print(bar)

foo("bar")
foo(bar="bar")

fresh sierra
errant trout
#

both of these work

#

shitty example but whatever

fresh sierra
#

Yeah but I understood Dw

errant trout
#

but ALSO in python, you can force options to be written as an arg or kwarg

#

e.g. ```py
def foo(bar, /):
print(bar)

foo("bar")
foo(bar="bar") # this errors

#

and the opposite ```py
def foo(*, bar):
print(bar)

foo("bar") # this errors
foo(bar="bar")

fresh sierra
#

Why this will raise an error ?

#

The / one

errant trout
#

in the first i used / to force all args before it to only work as args

#

in the second, * forces all args after it to only work as kwargs

#

you see this a lot if you go through pycord's code

sage tendon
#

call me ignorant but why would you ever make something kw only

#

like whats the downside to just allowing either

errant trout
#

generally if you don't want ANY ambiguity

fresh sierra
#

And arg need to do bar=bar and kwazgs not ?

shell radish
sage tendon
#

no
what

errant trout
#

(in the end, just try it and it'll make more sense)

fresh sierra
#

Yeah gonna try tomorrow

#

Special Symbols Used for passing arguments in Python:

*args (Non-Keyword Arguments)
**kwargs (Keyword Arguments)

shell radish
sage tendon
#

I don't use vim

shell radish
#

let’s say you are using vim and you want it to be non-ambiguous

sage tendon
#

ah

balmy finch
#
import discord
from discord.ext import commands
import sqlite3


class Stats(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        conn = sqlite3.connect('counter.db')
        self.c = conn.cursor()
        
    @commands.slash_command(description="How many link did you fetch")
    async def stats(self, ctx: discord.ApplicationContext, member: discord.Member = None):

        self.c.execute("SELECT * FROM counts WHERE id=?", (str(member.id),))
        row = self.c.fetchone()
        if not row:
            row = [0,0]
        val = self.c.execute("SELECT SUM(count) FROM counts;").fetchone()[0]
        await ctx.respond(f"{ctx.author.display_name} has fetch {row[1]} links\nGlobal: {val} links", allowed_mentions = discord.AllowedMentions(everyone=False, users=False))

def setup(bot):
    bot.add_cog(Stats(bot))

using the same code, the bot works locally for me, but it doesnt work on the host. any ideas?

errant trout
#

well

#

did the bot actually start

balmy finch
#

yes

errant trout
#

does anything appear in console after using the command

balmy finch
#

nope

#

it worked like 2 days ago

sage tendon
#

I think that's an issue on the client or discord site

#

else it would say application didn't respond

#

try to restart discord

balmy finch
#

I tested it with my local code using the anola token, and it still said this interaction failed

#

although the bot xDaaa1 works

sage tendon
#

did you restart discord after starting the bot?

balmy finch
#

i did

#

or maybe because of this...?

sage tendon
#

nah

#

p sure no

#

think it only prevents you from adding the bot to more servers when you reach 100

#

do any other commands work?

#

actually I think I might know the issue lol
can you rename the function of the command, just add a letter or whatever

balmy finch
#

okay let me try

#

btw, i cant use application command since i verified the bot

sage tendon
#

ah

#

hm, I never did bot verification, idk then

balmy finch
#

clueless

sage tendon
#

I thought the function name might have been the issue cause it has the same name as the cog except the lowercase s

balmy finch
#

hm but it works on my unverified bot

#

weird

errant trout
#

does it work at all if you change the command name

#

or maybe on another device

balmy finch
#

both no: neither command name and change device

errant trout
#

hmmm

#

if it's verification related, probably better to ask in ddevs

sage tendon
#

I gotta say idk what "this interaction failed" can be caused by

#

red errors outside of "application didn't respond" suck

errant trout
#

that's a client error as you said

#

basically, no clue

balmy finch
#

okay

#

thanks guys

sage tendon
#

I'd say ask discord support but that's hit or miss, with a big portion of miss

balmy finch
shut fox
#

how to fix this space?

little cobalt
shut fox
little cobalt
#

Oh you mean the space from the IDE?

#

Is that PyCharm or vscode?

shut fox
sacred gale
#
@app_commands.command(name="test")
    async def test(self, ctx):
        loadingGifFile = discord.File("./bot_dc/assets/loading.gif", filename="loading.gif")
        embed1 = discord.Embed(title="Loading...", description=f"loading")
        embed1.set_thumbnail(url="attachment://loading.gif")
        embed1Message = await ctx.guild.get_channel(1230207199855513705).send(file=loadingGifFile, embed=embed1)

        await asyncio.sleep(5)

        embed2 = discord.Embed(title="Success!", description=f"We have finished loading")
        await embed1Message.edit(embed=embed2)```
#

this command produces the above image

#

and after the asyncio.sleep it edits said message to this

#

how do i make it remove the loading gif whenever it edits the message

#

nvm fixed it

#
await embed1Message.edit(
            attachments=[],
        )```
lofty parcel
#

Not pycord

sacred gale
#

oh

#

but they are similar no

sage tendon
#

for slash commands, not at all really

#

for slash command specific stuff at least

#

the core parts are very very similar to exactly the same because pycord is a discord.py fork

sacred gale
#

do they have more features or something

echo wraith
#

like it makes way much more sense

shut fox
#

member join not working

code:
import discord
from discord.ext import commands
import config
from discord.ui import Modal, InputText, View, button

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

@bot.event
async def on_member_join(member):
await member.send(
f'Welcome to the server, {member.mention}! Enjoy your stay here.'
)
bot.run(config.TOKEN)

sage tendon
#

oh paillat already said lol

shut fox
little cobalt
shut fox
# little cobalt You havent added Intents

if i'm add intents:
File "C:\Users\V\PycharmProjects\ilias_Projects\bots\FCB\main.py", line 11, in <module>
bot = discord.Bot(intents)
File "C:\Users\V\PycharmProjects\ilias_Projects\venv\lib\site-packages\discord\bot.py", line 1154, in init
self.description = inspect.cleandoc(description) if description else ""
File "C:\Users\V\AppData\Local\Programs\Python\Python310\lib\inspect.py", line 750, in cleandoc
lines = doc.expandtabs().split('\n')
AttributeError: 'Intents' object has no attribute 'expandtabs'

little cobalt
#

intents=intents

shut fox
#

oh, im so stupid

#

Traceback (most recent call last):
File "C:\Users\V\PycharmProjects\ilias_Projects\bots\FCB\main.py", line 183, in <module>
bot.run(config.TOKEN)
File "C:\Users\V\PycharmProjects\ilias_Projects\venv\lib\site-packages\discord\client.py", line 766, in run
return future.result()
File "C:\Users\V\PycharmProjects\ilias_Projects\venv\lib\site-packages\discord\client.py", line 745, in runner
await self.start(*args, **kwargs)
File "C:\Users\V\PycharmProjects\ilias_Projects\venv\lib\site-packages\discord\client.py", line 709, in start
await self.connect(reconnect=reconnect)
File "C:\Users\V\PycharmProjects\ilias_Projects\venv\lib\site-packages\discord\client.py", line 646, in connect
raise PrivilegedIntentsRequired(exc.shard_id) from None
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
Exception ignored in: <function _ProactorBasePipeTransport.del at 0x000001C46885CD30>
Traceback (most recent call last):
File "C:\Users\V\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 116, in del
self.close()
File "C:\Users\V\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Users\V\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 745, in call_soon
self._check_closed()
File "C:\Users\V\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 510, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed bruuuuh

sage tendon
#

it tells you exactly what to do

#

do it

shut fox
edgy nest
# shut fox idk

discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.

shut fox
edgy nest
#

read the message

shut fox
edgy nest
#

go to the dev portal and turn the intents on

shut fox
edgy nest
#

your bot

shut fox
sage tendon
#

and please make triple sure to click "using the commands extension"

naive ferry
#

Thankiess

opal swan
#

and auto process_command

naive ferry
#

Is there a way to see content of a message that a message is replying to?

naive ferry
nimble matrixBOT
naive ferry
# lofty parcel Yes

I have minimal idea of what I am doing, so can you help me with an example of how to?

naive ferry
#
@bot.command()
async def quote(ctx: commands.Context):
    if ctx.reference:
        print("test")
        await ctx.send(":)")
    else: 
        await ctx.send(":(")
#

And this crashes

edgy nest
#

ctx.message.reference

#

:3

sage tendon
#

tracelog probably had that in there too

edgy nest
#

reference is an attr of message, not context

sage tendon
#

traceback*

edgy nest
#

traceback just said 'no attr named reference'

quartz relic
#

Does this work to give a role the ability to move members?

await team_one_channel.set_permissions(team_one_role, connect=True, move_members=True)
#

or is it a different attribute?

sage tendon
#

try it and see

nova epoch
sage tendon
#

but mind this

opal swan
#
await team_one_channel.set_permissions(team_one_role, permissions=discord.Permissions(connect=True, move_members=True))
#

imo it's that

#

@quartz relic

quartz relic
#

I'll try that.

It's weird because the connect perm works, but I'm having trouble with the other one.

#

Thanks @opal swan

opal swan
#

discord.Permissions

#

.rtfm discord.Permissions

opal swan
#

the first one

proven valley
#

is this the correct way to query a junction table for the values?

echo wraith
#

.tag sqli

sly karmaBOT
#

SQL Injection is a technique used by attackers to interfere with and alter queries that an application makes to its database via input data. A vulnerability to this exploit can lead to attackers being able to read sensitive data, modify existing data (Insert/Update/Delete), perform administrative operations on your database and in some cases even issue commands directly to the operating system of the server.

More information on SQL Injection
w3schools, owasp.org

To avoid SQL Injection vulnerability, you should never directly merge or concatenate data into an SQL query through string operations (f-strings, + operator, string interpolation with %, etc.). Always use the parameterized queries included with the library you are using.

Examples of parameterized queries for popular libraries
psycopg2, asyncpg, sqlite3, mysql

opal swan
fossil valve
#

hey everyone :) Is there a way to get all the channels that were deleted in a guild?

sage tendon
#

no, there's no history that keeps track of that
audit log doesn't go back more than a week afaik

hollow plank
#

there are these invisible messages. Is there an event when you discard this message?

opal swan
fresh sierra
# echo wraith .tag sqli

dont really understand how we should do then, here the thing say to not use interpolation with %, however in the guid u send its using that

#

e.g

insert_stmt = (
  "INSERT INTO employees (emp_no, first_name, last_name, hire_date) "
  "VALUES (%s, %s, %s, %s)"
)
data = (2, 'Jane', 'Doe', datetime.date(2012, 3, 23))
cursor.execute(insert_stmt, data)
opal swan
#

ephemeral = the invisible msg

civic moon
#

Hi, after I first run my bot my slash commands work fine. Then shortly after they disappear and I can't use them. If I run bot.sync_commands() they show up again, only to disappear again shortly after. Any idea what I am doing wrong?

fossil valve
fresh sierra
#

And where do u load cogs

civic moon
civic moon
little cobalt
#

But it would help to build a structure

civic moon
#

Could it be something with too many slash commands in my guild? I read something about that in the past and we have a ton.

little cobalt
#

100 for normal is the limit

#

you still could create sub commands

civic moon
#

Hmm, I'd have to make a count. Think they would show up and disappear like that because the limit?

fresh sierra
#

U can check the number of slash command pretty easily with a control f

civic moon
fresh sierra
#

Inside ur code editor

#

If u only have 4 commands inside ur code that’s strange

little cobalt
#

How many slash commands does your bot have?

civic moon
civic moon
#

Here is an example of one:

async def initiatesummary(ctx, option : discord.Option(str, "Days back to evaluate (default 30)", required = False, default = "30")): ```
little cobalt
#

If you add guild its only gonna show up at the added ones

civic moon
fresh sierra
civic moon
civic moon
shut fox
#

trying to made mute command with timeout, but getting this error.
code:
@bot.slash_command(name="mute")
@commands.has_role("Staff")
async def mute(ctx, user:discord.Member, reason = "None"):
embed = discord.Embed(color=discord.Color.red(), title="User has been muted", description="You just muted user")
embed.add_field(name="User", value=user, inline=True)
embed.add_field(name="Reason", value=reason, inline=True)
await ctx.respond(embed=embed)
embedl = discord.Embed(color=discord.Color.red(), title="Muted", description="You has been muted")
embedl.add_field(name="Admin", value=ctx.author, inline=True)
embedl.add_field(name="Reason", value=reason, inline=True)
await user.send(embed=embedl)
await user.timeout(datetime(year=2100, month=1, day=1),reason=reason) #not working

bot.run(config.TOKEN)

#

error is to big lol

#

error:
Ignoring exception in command mute:
Traceback (most recent call last):
File "C:\Users\V\PycharmProjects\ilias_Projects\venv\lib\site-
File "C:\Users\V\PycharmProjects\ilias_Projects\venv\lib\site-packages\discord\commands\core.py", line 1013, in _invoke
await self.callback(ctx, **kwargs)
File "C:\Users\V\PycharmProjects\ilias_Projects\bots\FCB\main.py", line 175, in mute
await user.timeout(datetime(year=210 0, month=1, day=1),reason=reason)
File "C:\Users\V\PycharmProjects\ilias_Projects\venv\lib\site-packages\discord\member.py", line 873, in timeout
await self.edit(communication_disabled_until=until, reason=reason)
File "C:\Users\V\PycharmProjects\ilias_Projects\venv\lib\site-packages\discord\member.py", line 847, in edit
data = await http.edit_member(guild_id, self.id, reason=reason, **payload)
File "C:\Users\V\PycharmProjects\ilias_Projects\venv\lib\site-packages\discord\http.py", line 373, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In communication_disabled_until: Invalid communication disabled timestamp
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\V\PycharmProjects\ilias_Projects\venv\lib\site-packages\discord\bot.py", line 1130, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\V\PycharmProjects\ilias_Projects\venv\lib\site-packages\discord\commands\core.py", line 376, in invoke
await injected(ctx)
File "C:\Users\V\PycharmProjects\ilias_Projects\venv\lib\site-packages\discord\commands\core.py", line 139, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In communication_disabled_until: Invalid communication disabled timestamp

sage tendon
#

its too long

#

you can max time out for 28d

#

and i recommend using timeout_for

dense summit
#

Hey there, i have this code that if the cookie session is invalid it fetches a new cookie and retry to send the message, although sometimes i get

discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction

and sometimes i only get the cookie error as expected:

Cookie Error: Cannot fetch session cookie from https://www.vinted.it, because of status code: 403 different from 200.

fresh sierra
#

You should defer then

dense summit
#

i defer at the start of the callback, should i defer in the exception too?

fresh sierra
#

If u already defer that’s strange

dense summit
#

Well then im already doing it

fresh sierra
#

Cos after a after u have 15min to answer and I don’t think ur code takes 15min

dense summit
#

Maybe this is the wrong way to defer?

fresh sierra
#

Not it should be good

#

Strange

dense summit
#

well i dont really know what to do

fresh sierra
#

.tag paste

sly karmaBOT
#

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

fresh sierra
#

If its too big

dense summit
fresh sierra
#

Not traceback

dense summit
#

ohh callback

#

sorry

fresh sierra
#

Dw

dense summit
fresh sierra
#

Gonna check later

#

Dont have my laptop rn

dense summit
sage tendon
dense summit
sage tendon
#

no im just confused at that function lol

dense summit
sage tendon
#

nvm

dense summit
# sage tendon nvm

if it's the create_fake_chat, it's just image manipulation nothing more πŸ˜…

#

Anyway, it doesn't send the message "bot is working" is it normal?

loud kayak
dense summit
lapis dock
#

Not sure if this is the issue but you should be deferring with ephemeral=True if the response is going to be ephemeral

dense summit
echo wraith
#

just abest practice

dense summit
#

there are probably a lot of ways to improve it

fresh sierra
#

@dense summit i think i found ur error

#

its not directly inside this modal here but in ur code in general

#

you might have some not async function that block ur entire code

#

like the time.sleep

fresh sierra
#

Also why do u do file.close ?

#

Since u don’t open it

dense summit
#

It always throws like File is used by another process

dense summit
fresh sierra
fresh sierra
#

Callback => blocking code for more than 3s, defer but too late

dense summit
echo wraith
fresh sierra
#

.rie

sly karmaBOT
#

You can run blocking code (such as PIL/Pillow) in an executor to run it in a separate thread: ```py
def my_blocking_func(*args):
...

@bot.command()
async def test_command(ctx):
ret = await bot.loop.run_in_executor(my_blocking_func, 'put', 'args', 'here')``` See the python documentation for more info.

dense summit
#

i probably should have said this earlier

#

Like this right?

file = await self.bot.loop.run_in_executor(discord.File(create_fake_chat(lang.lower(), full, item_info.photo.url, item_info.title, format_float(item_info.price), price, output_path)))
fresh sierra
#

try and see

#

is it possible to get the guild object from an id even if the bot is not in ?

#

its to check if the id passed is a guild or not

edgy nest
#

not always

fresh sierra
#

wdym by not always ?

#

i think i will ask the user to pass an invite then

edgy nest
#

just kidding

#

it returns 404

#

but i was thinking of guild widgets

deft kestrel
#

is it possibile to save bot cache?

edgy nest
#

you'd be messing with the attrs in discord.Client._state

flint talon
#

yo

#

how to set discord option

#

for slash command

#

nothings working

flint talon
#

bro

#

py-cord is so annoying to use i should go back 2 discord.py

#

idk why i switched

edgy nest
#

go for it

flint talon
#

ty

#

bye

shell radish
#

cya

edgy nest
#

goodbye

edgy nest
# deft kestrel damn

it probably isn't that difficult, you'd just have to screw with internals quite a bit

lofty parcel
#

Man thought we'd beg

edgy nest
#

storing dictionaries isn't very hard

edgy nest
#

Β―_(ツ)_/Β―

#

he's been here for months, should've figured out options by now

lofty parcel
#

Fun how d.py handles options almost the same way

edgy nest
#

yeah

#

at least i didn't have to escort him out

tidal vessel
flint talon
#

but idk what happened

#

everything was working well

#

i've made lots of apps in py-cord since i started

#

then today

edgy nest
#

well nobody can tell you because we don't know what you're doing

flint talon
#

they js suddenly stopped working

#

i checked for conflicting packages

#

i used a venv

#

idk whats going on

#

πŸ€·β€β™‚οΈ

edgy nest
#

code helps usually

tidal vessel
flint talon
#

import discord
from features import create_embed, check_role

intents = discord.Intents.default()
intents.message_content=True
intents.moderation=True
intents.guild_messages=True

#We are using slash commands
bot = discord.Bot(intents=intents)
@bot.event
async def on_ready():
print(f"Logged in as {bot.user}")

#

is returning an error

edgy nest
#

and that error is

flint talon
#

discord has no attribute bot

edgy nest
#

reinstall

flint talon
#

i did

#

like 3 times imma do it again

edgy nest
#

can you drop a pip freeze

flint talon
#

then ill do

edgy nest
#

πŸ‘

flint talon
#

then install discord there

edgy nest
#

that might be a good idea

flint talon
#

see if it does anything

edgy nest
#

not discord

flint talon
#

ok

#

πŸ‘

tidal vessel
edgy nest
#

didn't want to change the namespace because it would have been more work to migrate

#

if we ever go to v3 we'll probably change it

flint talon
#

ok

#

πŸ‘

#

imma install py-cord here now

shell radish
edgy nest
flint talon
#

ok so i installed it in a venv

edgy nest
#

i'll bring it up if we ever discuss it again

flint talon
#

now lets see

#

wait

#

the first error went away

#

now i have a diff one

#

Option object is now callable

#

not

edgy nest
#

is that a python error or your ide being a little shit

#

if its the latter you can ignore it

flint talon
#

idk i think python

edgy nest
#

well does the code run

flint talon
#

no lol

#

so ig ur right

edgy nest
#

you got a traceback?

flint talon
#

ye

#

lemme fetch it real quick

tidal vessel
flint talon
#
PS C:\Users\[redacted]\Desktop\vscodeprojects\mys_bot> & C:/Python312/python.exe c:/Users/[redacted]/Desktop/vscodeprojects/mys_bot/main.py
Traceback (most recent call last):
  File "c:\Users\[redacted]\Desktop\vscodeprojects\mys_bot\main.py", line 21, in <module>
    @discord.Option(
     ^^^^^^^^^^^^^^^
TypeError: 'Option' object is not callable
PS C:\Users\[redacted]\Desktop\vscodeprojects\mys_bot> 
edgy nest
#

ah

#

you'll want a lowercase O for the decorator

flint talon
#

am i tripping

#

😭

#

i am tripping

edgy nest
flint talon
#

ok we got it

#

its running

#

imma test in my server now

#

🫑

edgy nest
#

have fun!

flint talon
#

ok it works :)

#

but

#

the options dont actually register

#

like

#

it wont set description and stuff

dense summit
#

I tried to print the list, the name and the description values and they work

lapis dock
dense summit
lapis dock
#

Yeah

dense summit
#

yeah i did that

lapis dock
# dense summit yeah i did that

In your option. You have type=
It should be input_type=
Also put it after name= not sure if that is 100% necessary but it might help

dense summit
#

Printing the value works, although it really doesnt want to show up

#

the command name and description works fine tho

lapis dock
#

Remove () after
get_filters_names()

#

Just want to check
You know the difference between choices and auto complete, right?

dense summit
dense summit
lapis dock
#

Just wanted to make sure you were not mixing them up

#

Can you show the auto complete function

dense summit
#

Yeah probably something wrong there

#

There isnt much

#

If i print db.get_all_filter_names()

lapis dock
#

My guess is the DB is taking a while to respond. Can you try changing the function to just return a static list temporarily

dense summit
#

Sure

#

Im about to go crazy, where did i mess uppp

#

Already did Ctrl + R

lapis dock
#

How are you loading your cogs, and do you override on_connect

dense summit
#

I don't override on_connect

lapis dock
#

Does this function return "filter_name"?
get_commandsinfo('bot_commands', ['filters_remove_command', 'options', 'filter_name_name'])

dense summit
#

I should probably change the key now that i read it, anyway this is not the issue :p

lapis dock
#

I think that is the problem.
The decorator is looking for a parameter with the name of Nome and cannot find one so it does not create the option. But than it seems that there is a filter_name parameter so it creates a default string option

dense summit
lapis dock
#

What do you mean by print the function?

#

print(filter_name)?

dense summit
#

I didn't really understand sorry

#

this thing is driving me crazy

lapis dock
#

So when you use the option decorator you need to tell it what parameter of the function it is describing. You are telling it to look for Nome
async def filters_remove(self, ctx, Nome: str):

#

I assume that you want the option name on discord to be Nome and the name in the code to be filter_name?

dense summit
#

exactly

#

they have to be the same?

lapis dock
#

parameter_name="filter_name" add this to the option

#

Also just a fyi I think discord requires option names to be lowercase

#

Looking at the code when I said use input_type before I was half right. You can use input_type or just type

dense summit
#

if they are the same i get the description but empty autocomplete even if the list is still the static one

lapis dock
#

Can you show your updated option decorator

dense summit
#

finallysadcatthumbsup

lapis dock
#

what changed?

dense summit
#

sorry for all the troubles man

#

i didnt really know about the parameter_name arg

lapis dock
#

It is kinda hidden in the docs

lapis dock
dense summit
#

this was exhausting, wasnt it?

dense summit
dense summit
loud kayak
#

got this error on startup when making a new bot. on the newest version when doing pip install py-cord

container@PingHost:~$ python main.py
Traceback (most recent call last):
  File "/home/container/main.py", line 3, in <module>
    from cogs.utils import *
  File "/home/container/cogs/utils.py", line 2, in <module>
    from discord.ext import commands, pages
  File "/home/container/.local/lib/python3.9/site-packages/discord/ext/pages/__init__.py", line 10, in <module>
    from .pagination import *
  File "/home/container/.local/lib/python3.9/site-packages/discord/ext/pages/pagination.py", line 31, in <module>
    from discord.ext.bridge import BridgeContext
  File "/home/container/.local/lib/python3.9/site-packages/discord/ext/bridge/__init__.py", line 26, in <module>
    from .bot import *
  File "/home/container/.local/lib/python3.9/site-packages/discord/ext/bridge/bot.py", line 31, in <module>
    from discord.commands import ApplicationContext
  File "/home/container/.local/lib/python3.9/site-packages/discord/commands/__init__.py", line 26, in <module>
    from .context import *
  File "/home/container/.local/lib/python3.9/site-packages/discord/commands/context.py", line 69, in <module>
    class ApplicationContext(discord.abc.Messageable):
  File "/home/container/.local/lib/python3.9/site-packages/discord/commands/context.py", line 271, in ApplicationContext
    @discord.utils.copy_doc(Interaction.respond)
AttributeError: type object 'Interaction' has no attribute 'respond'
#

nvm github branch install fixed it

little cobalt
#

lol

compact oasis
little cobalt
#

that should be at the setup func. at the cog

compact oasis
compact oasis
little cobalt
#

why at the main file?

little cobalt
#

At the main file you should have something like this load_extension

hexed herald
#

hey, can someone tell me what I did wrong?

@bot.listen("on_application_command")
async def on_application_command(command: discord.ApplicationContext):
    if not command.guild:
        if not command.interaction.context.bot_dm or not command.interaction.context.private_channel:
            await command.response.send_message("This command is not available in dm's.", ephemeral=True)

I am calling the on_application_command event to get application commands and check their context. if they are executed in a guild I want them to be executed normal by the defined function. but if they are executed in a dm and do not have either of the bot_dm context nor the private channel context I want to suppress their execution. now I've encountered this error

Ignoring exception in on_application_command
Traceback (most recent call last):
File "E:\Programming\PyCharm\Dragons-BotV2\venv\Lib\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "E:\Programming\PyCharm\Dragons-BotV2\main.py", line 50, in on_application_command
if not command.interaction.context.bot_dm or not command.interaction.context.private_channel:
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: '_EnumValue_InteractionContextType' object has no attribute 'bot_dm'

fresh sierra
fresh sierra
#

for me it should be
if not command.interaction.context == ...

#

chat didnt load mb

hexed herald
#

ohh yeah, sometimes it's the simple things...

#

thank you

errant trout
echo wraith
#

If you had to guess what eta would you give for pycord 2.7 ?

#

Cause I'm hesitating between 2.7 before rewriting a really huge project that, notably, uses bridge, or just doing it because it really needs it.

errant trout
#

uhhhhh 2.7 itself idk, we might be skipping it and be doing breaking changes with v3 instead...? but if that's the case, it'll be announced well in advance

sage tendon
#

imo pycord should go full semver at least from 3.0 on

echo wraith
fresh sierra
#

Wdym by semver ?

sage tendon
#

semantic versioning

flint talon
#

wel

#

plun

#

ig im still here

#

how can I see if a message has been reacted to with a given emoji?

sage tendon
#

as in, you wanna wait for that reaction, or you just want to read it from a message

flint talon
#

I just want to see if it has a reaction

#

cause I am enumerating through messages

sage tendon
flint talon
#

sometimes i cant find what im looking for in the docs

sage tendon
#

i mean, message.reactions is only logical lol

flint talon
#

but still

proven valley
#

I asked the a different day but is there a way to make it so that I have a seperate file for each subcommand/view and such?

sage tendon
#

for views you can ofc just make different files but i think for the subcommands you need an extension called multicog, just google it, never worked with that tho

proven valley
#

damn, you think I could I just define all my commands in one file then import functions and put them in there, like


    @mm.command(name="1v1", description="Challenge someone to a 1v1 money match")
    @option("player1", discord.Member, description="Player 1 Username",)
    @option("player2", discord.Member, description="Player 2 Username",)
    @option("value", int, description="value",)
    @option("sponsor1", discord.Member, description="Sponsor for Player 1", required=False,)
    @option("sponsor2", discord.Member, description="Sponsor for Player 2", required=False,)
    async def mm1v1(self, ctx: discord.ApplicationContext,
                    player1: discord.Member,
                    player2: discord.Member,
                    wager: int,
                    sponsor1: discord.Member,
                    sponsor2: discord.Member,):
        mm1v1function(paramters) ```
sage tendon
#

yea

#

but thats really messy imo

proven valley
#

I agree, but it's slightly less messy than having all the subcommands in one cog

little cobalt
sage tendon
#

thats not what we're talking about tho :3

proven valley
#

is there such thing as a subcog? that is what it seems the multicog is attempting but you said it doesn't really work

sage tendon
#

no, i said i never worked with it lol

#

it does work

proven valley
#

oh I read that wrong

#

my bad

#

well I'll give it a shot

lapis dock
stray pasture
#

Hi ! This is a quick question. Is there a way to count the usage of slash commands of another bot ? For example the command /ping from bot X was run 40 time last week ?

stray pasture
naive ferry
#

I currently have

reply = await ctx.fetch_message(ctx.message.reference.message_id)
await ctx.send(reply)

How do i get the content of a message instead of getting

<Message id=nuhuh channel=<TextChannel id=nuhuh name='general' position=0 nsfw=False category_id=nuhuh news=False> type=<MessageType.default: 0> author=<Member id=nuhuh name='nuhuh' global_name='nuhuh' bot=False nick='Not Nuhuh' guild=<Guild id=nuhuh name='Not a Discord Server' shard_id=0 chunked=True member_count=32>> flags=<MessageFlags value=0>>
naive ferry
#

what is in the message

lofty parcel
naive ferry
lofty parcel
#

reply.content

#

When I say message it's a reference to the message object you're getting

naive ferry
# lofty parcel reply.content
Logged in as Not a Quote Bot#0518 (ID: 1279177215929745509)
------
quote
Ignoring exception in command quote:
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.11/site-packages/discord/ext/commands/core.py", line 180, in wrapped
    ret = await coro(*args, **kwargs)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/container/bot.py", line 41, in quote
    reply = await ctx.reply.content(ctx.message.reference.message_id)
                  ^^^^^^^^^^^^^^^^^
AttributeError: 'function' object has no attribute 'content'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.11/site-packages/discord/ext/commands/bot.py", line 349, in invoke
    await ctx.command.invoke(ctx)
  File "/home/container/.local/lib/python3.11/site-packages/discord/ext/commands/core.py", line 959, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/home/container/.local/lib/python3.11/site-packages/discord/ext/commands/core.py", line 189, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'function' object has no attribute 'content'
#

im trying to create a quote bot. If you reply to a message, I want the bot to get the content of the message that the user replied to

lofty parcel
#
reply = await ctx.fetch_message(ctx.message.reference.message_id)

reply.content # <-- That's your content 
naive ferry
#

Am oopid

#

thank you

lofty parcel
#

Also you shouldn't use fetch

#

You should first try get

#

?tag get

limber wagonBOT
#
**Command:** ?tag get

Description: Get a tag
Cooldown: 5 seconds
Usage:
?tag get (optional category) [tag name]
Example:
?tag get how2invite

lofty parcel
#

OK I don't remember the tag

#

?tag get_x

limber wagonBOT
#

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

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

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

hexed herald
#

hey, is the @discord.guild_only() decorator broken? I've tried decorating many commands with it but I can still execute them in a direct message with the bot. Or do they need (up to) 1 hour to be removed from the dm's?

little cobalt
#

Its not removed from dm`s

#

guild_only is just a check if the command was executed at a guild or not

hexed herald
#

but it's also not raising any error

hexed herald
#

okay, I guess I'll do that for every command, thanks :D

fresh sierra
#

For they it apply to each subcommznd

jaunty blaze
#

Is there an overview on the differences between discord.Bot and discord.ext.commands.Bot? Which one should I use?
I want to support prefixed commands as well as slash commands.

pls ping me with a response, thanks

sly karmaBOT
jaunty blaze
#

Alright, so I should use commands.Bot then, thanks!

hexed herald
#

hmm, after changing most of my slash commands to use contexts I now get this error

Ignoring exception in on_connect
Traceback (most recent call last):
  File "E:\Programming\PyCharm\Dragons-BotV2\venv\Lib\site-packages\discord\client.py", line 409, in _run_event
    await coro(*args, **kwargs)
  File "E:\Programming\PyCharm\Dragons-BotV2\venv\Lib\site-packages\discord\bot.py", line 1214, in on_connect
    await self.sync_commands()
  File "E:\Programming\PyCharm\Dragons-BotV2\venv\Lib\site-packages\discord\bot.py", line 742, in sync_commands
    registered_commands = await self.register_commands(
                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "E:\Programming\PyCharm\Dragons-BotV2\venv\Lib\site-packages\discord\bot.py", line 541, in register_commands
    desynced = await self.get_desynced_commands(
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "E:\Programming\PyCharm\Dragons-BotV2\venv\Lib\site-packages\discord\bot.py", line 364, in get_desynced_commands
    elif _check_command(cmd, match):
         ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "E:\Programming\PyCharm\Dragons-BotV2\venv\Lib\site-packages\discord\bot.py", line 278, in _check_command
    as_dict = cmd.to_dict()
              ^^^^^^^^^^^^^
  File "E:\Programming\PyCharm\Dragons-BotV2\venv\Lib\site-packages\discord\commands\core.py", line 962, in to_dict
    as_dict["contexts"] = [ctx.value for ctx in self.contexts]
                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "E:\Programming\PyCharm\Dragons-BotV2\venv\Lib\site-packages\discord\commands\core.py", line 962, in <listcomp>
    as_dict["contexts"] = [ctx.value for ctx in self.contexts]
                           ^^^^^^^^^
AttributeError: 'str' object has no attribute 'value'

No traceback to my code, but I don't understand the libary code enough to find the origin of it

sage tendon
#

show what you changed

hexed herald
#

^ btw the commands are still available in the dm's and can be executed

#
    @pycog.subcommand("mod", independent=True)
    @commands.slash_command(
        name="warn", description="Warns a given member", contexts=(discord.InteractionContextType.guild)
    )
    @is_team()
    @discord.option("member", description="The member you want to warn", input_type=discord.Member, required=True)
    @discord.option("reason", description="The reason for the warn", input_type=str, required=True)
    async def warn(
        self,
        ctx: discord.ApplicationContext,
        member: discord.Member,
        reason: str,
    ):
    ...

I've a few more of these commands and just added the contexts parameter to them with just InteractionContextType.guild

#

before there was just contexts not in the slash command

sage tendon
#

subcommands cant have their own contexts

#

and i have no idea what pycog is

hexed herald
#

ohh, but I don't have a "main" mod command

sage tendon
#

Still

#

subcommand contexts are the same as the contexts for the group itself

#

(also, you cant have the group also be a command on its own)

hexed herald
sage tendon
#

ah

hexed herald
#

yeah, most likely I have to refactor the code to have a "main" SlashCommandGroup

#

and just not let it be autogenerated

sage tendon
#

also you dont need input_type if its a str, and you also dont need required=True
just to be shorter

#

also, i have no idea if multicog supports contexts at all lol, so take this with a grain of salt

#

hasnt been updated since they released

hexed herald
#

but there is still no libary native way to split slash command groups over multiple cogs/files, is there?

sage tendon
#

not that i know of

hexed herald
#

okay, thanks I'll try refactoring it and be back if the error persists/change/resolves :D

hexed herald
#

Uhhm, so I've started debugging a little in core.py, maybe someone with more knowledge of the core libary and python should look at this xD

It seems like here originates the problem. I've changed the code for debugging purposes to this

        if not self.guild_ids and not self.is_subcommand:
            as_dict["integration_types"] = [it.value for it in self.integration_types]
            for ctx in self.contexts:
                print(ctx)
                print(type(ctx))
                try:
                    print(ctx.value)
                    print(type(ctx.value))
                except Exception as e:
                    print(e)
                    print(type(e))
            as_dict["contexts"] = [ctx.value for ctx in self.contexts]

the output is this

guild
<class 'str'>
'str' object has no attribute 'value'
<class 'AttributeError'>
0
<class 'int'>
'int' object has no attribute 'value'
<class 'AttributeError'>

I'd suggest moving this to a thread to save this place for "quick questions" πŸ˜…
Thread -> #1280616860509016125

fresh sierra
#

And what do u want to do

hexed herald
#

Slash commands are still showing in dm's even through the contexts attribute of the SlashCommandsGroup does not allow it.

edgy nest
#

contexts needs to be an iterable

fresh sierra
#

Discord.SlashCommanGroup()

#

U make that and u make sure to load the cog with that before the other

edgy nest
#

with how you have it set up: (discord.InteractionContextType.guild) is not an iterable

fresh sierra
#

Then u use ur multicog like normal without the independent

hexed herald
fresh sierra
#

Do like so

edgy nest
#

either slap a comma on the end:
(discord.InteractionContextType.guild,)
or make it a set (it's supposed to be one):
{discord.InteractionContextType.guild}

fresh sierra
proven valley
#

when im loading my bot I'm getting this error, I mean the bot still loads but I don't know what's causing this

discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In 1.options.4.options.5: Required options must be placed before non-required options
In 1.options.4.options.6: Required options must be placed before non-required options
In 1.options.4.options.7: Required options must be placed before non-required options

fresh sierra
fresh sierra
# fresh sierra

If u want to do it for the whole group do like so @hexed herald

#

Else u will have to do it for each command

#

(The goal is to create a group and the. To load it before the other)

hexed herald
# edgy nest either slap a comma on the end: `(discord.InteractionContextType.guild,)` or mak...

I've tried both solutions but it's still throwing the same exception.

Ignoring exception in on_connect
Traceback (most recent call last):
  File "E:\Programming\PyCharm\Dragons-BotV2\venv\Lib\site-packages\discord\client.py", line 409, in _run_event
    await coro(*args, **kwargs)
  File "E:\Programming\PyCharm\Dragons-BotV2\venv\Lib\site-packages\discord\bot.py", line 1214, in on_connect
    await self.sync_commands()
  File "E:\Programming\PyCharm\Dragons-BotV2\venv\Lib\site-packages\discord\bot.py", line 742, in sync_commands
    registered_commands = await self.register_commands(
                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "E:\Programming\PyCharm\Dragons-BotV2\venv\Lib\site-packages\discord\bot.py", line 541, in register_commands
    desynced = await self.get_desynced_commands(
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "E:\Programming\PyCharm\Dragons-BotV2\venv\Lib\site-packages\discord\bot.py", line 364, in get_desynced_commands
    elif _check_command(cmd, match):
         ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "E:\Programming\PyCharm\Dragons-BotV2\venv\Lib\site-packages\discord\bot.py", line 278, in _check_command
    as_dict = cmd.to_dict()
              ^^^^^^^^^^^^^
  File "E:\Programming\PyCharm\Dragons-BotV2\venv\Lib\site-packages\discord\commands\core.py", line 962, in to_dict
    as_dict["contexts"] = [ctx.value for ctx in self.contexts]
                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "E:\Programming\PyCharm\Dragons-BotV2\venv\Lib\site-packages\discord\commands\core.py", line 962, in <listcomp>
    as_dict["contexts"] = [ctx.value for ctx in self.contexts]
                           ^^^^^^^^^
AttributeError: 'str' object has no attribute 'value'
hexed herald
# fresh sierra

also as list it's still failing for me, it's already it's own group without independent

fresh sierra
hexed herald
#
import discord
from discord.ext import commands

from utils import Bot, CustomLogger


class CommandGroups(commands.Cog):
    def __init__(self, client):
        self.client: Bot = client
        self.logger = CustomLogger(self.qualified_name, self.client.boot_time)

    mod = discord.SlashCommandGroup("mod", contexts=[discord.InteractionContextType.guild]) # creating the command group


def setup(client):
    client.add_cog(CommandGroups(client))
from datetime import datetime

import discord
import pycord.multicog as pycog
from discord.ext import commands
from discord.utils import format_dt, get_or_fetch

from utils import (
    Bot,
    ButtonConfirm,
    ButtonInfo,
    CustomLogger,
    InfractionsEnum,
    SettingsEnum,
    is_team,
)


class Kick(commands.Cog):
    def __init__(self, client):
        self.client: Bot = client
        self.logger = CustomLogger(self.qualified_name, self.client.boot_time)

    @pycog.subcommand("mod") # <-- adding it to the subgroup
    @commands.slash_command(name="kick", description="Kicks a given member", contexts=(discord.InteractionContextType.guild))
    @is_team()
    @discord.option("member", description="The member you want to kick", input_type=discord.Member, required=True)
    @discord.option("reason", description="The reason for the kick", input_type=str, required=True)
    async def kick(
        self,
        ctx: discord.ApplicationContext,
        member: discord.Member,
        reason: str,
    ):
        ...
def setup(client):
    client.add_cog(Kick(client))
fresh sierra
#

U already put it inside the group

hexed herald
#

yeah, I didn't see that one my bad and after changing contexts to a set (as it's supposed) it's no more throwing errors, thanks for all the help

fresh sierra
#

With pleasure

proven valley
#

Does anyone have experience with the multicog plugin? I'm looking to separate each of my sub commands into a separate file

hexed herald
#

yeah, I guess I can help you