#Basic Pycord Help

1 messages · Page 60 of 1

slender lantern
#

I’ve got one (fittingly, @premium). I’m just wondering if the logic itself is reasonable, or if there’s something obvious I’m overlooking

sage tendon
#

nah sounds good

hasty meadow
#

What's the best way to get the timezone of a user?

shell radish
#

you can't natively

slender lantern
#

Discord does have a way to show time in each user’s timezone, if that happens to be what you want

lapis dock
echo wraith
#

aiocache

deft kestrel
#

hey

echo wraith
#

Helloo

deft kestrel
#

does discord are buggy at this moment? embed attachments (photos) are not generating

echo wraith
deft kestrel
echo wraith
deft kestrel
#

that's strange

#

on my end are not working now

sage tendon
echo wraith
#

Oh yeah almost forgot that

sage tendon
#

nvm that was last week

echo wraith
shell radish
echo wraith
#

geneva & zurich

slender lantern
sage tendon
#

unfurling lol

deft kestrel
sage tendon
#

If I have guild = bot.get_guild(X), and then kick a member, will the guild var be updated? or do I need to get_guild again to get the updated object

sage tendon
#

i cant, thats why i ask

echo wraith
#

why can't you

#

wait I'll try

#

let me open pycord-sandbox

sage tendon
#

and?

echo wraith
echo wraith
#

It is updated, you don't have to get again

sage tendon
#

ok nice

#

idk how that even works

echo wraith
#

I mean it seems logical

#

like when you get Guild

#

the instance is not a copy

sage tendon
#

i guess

knotty ember
#

hello, Is possible to use users install applications with voice channels ?

shell radish
#

user installed applications can be used inside voice channel's chat. If you are asking if a user installed application can join a voice channel without being in the server, the answer is no

knotty ember
#

so it only works on DM's and in servers you need to owner to add it?

#

sorry my english reading isn't the best

knotty ember
#

thanks you

#

the last question, I used to join to a voice channel with await ctx.author.voice.channel.connect() but in DM's instead of a Member object I get an User Object so how can I connect without voice attribute?

sage tendon
#

bots cant connect to group calls afaik

knotty ember
#

oh, thanks you 😦

hasty meadow
errant trout
#

i'd personally approach by entering timezone -> convert to UTC -> check with them if it's correct by displaying with <t:> format

#

heck, make it autocomplete so you can display the current time in each timezone directly on the option

eternal kite
#

has there been any changes to task loops? my code used to work fine but recently discord.ext.tasks.Loop.next_iteration returns "None"

errant trout
eternal kite
#

uh probably not

#

pycord 2.6.0

errant trout
#

mmmm can't repro with any of my tasks

#

Are you sure you started it...?

eternal kite
errant trout
#

If the loop isn't running then why would it have a next iter GuraSquintSmol

eternal kite
#

nvm the loop wasn't running because there was a silent error in another file caused it to stop running

lean garnet
#

Hi, is there any way for a bot to publish a message to all the servers that are following a channel using Pycord ?

#

sorry for my english

sage tendon
#

yea

copper olive
sage tendon
#

it's literally just that

#

await message.publish()

copper olive
sage tendon
#

hardly

wise harness
#

using pycord (2.6.1)'s default paginator here, the embed image is just.. not showing up? rest everything is as expected through, and the image url is also correct when i print it onto the console.

here's the relevant part:

        my_pages=[]
        for item in samples:
            emd = Embed(
            title=f"[Sample info for [{song}](<{url}>)",
            description=""
            
            
        )
            field_name = f"{item['title']} ({item['year']})"
            field_value = f"Artist: {item['artist']}\nType: {item['type']}"
            print(str(item['img']))
            emd.set_image(url=str(item['img']))
           
          
            emd.add_field(name=field_name, value=field_value, inline=False)
            my_pages.append(
            Page(
                embeds=[emd]
            ))
        paginator = Paginator(pages=my_pages, timeout=None, author_check=False)
echo wraith
wise harness
#

and that one works just fine

echo wraith
slender lantern
#

Is there a builtin function to create a timestamp from a datetime?

rugged lodgeBOT
slender lantern
#

Thanks

hazy turret
#

If I have a button in an ephemeral message, how can I make it so that the message is deleted when the button is clicked? So what do I have to have in the callback of the button to be able to delete the ephemeral message?

little cobalt
#

ephemeral messages getting autodeleted after some time

hazy turret
sage tendon
#

i'm pretty sure you cant

lapis dock
#

if you still have the interaction that triggered the ephemeral message

sage tendon
#

i think it'll cause unknown message

hazy turret
hazy turret
# lapis dock `delete_original_response()` works I think

Unfortunately it does not work...

await interaction.response.send_message("Choose the attribute to edit:", view=AttributeEditView(), ephemeral=True,)

class AttributeEditView(discord.ui.View):
    def __init__(self,):
        super().__init__(timeout=None)

 @discord.ui.button(label="Title", style=discord.ButtonStyle.blurple)
async def button_callback(interaction: discord.Interaction):
     message = await interaction.delete_original_response()```
sage tendon
#

it doesnt return anything lol

#

but yea, unknown message right?

lapis dock
#
await interaction.response.send_message("Choose the attribute to edit:", view=AttributeEditView(interaction), ephemeral=True,)

class AttributeEditView(discord.ui.View):
    def __init__(self, old_interaction):
        super().__init__(timeout=None)
        self.old_interaction = old_interaction

 @discord.ui.button(label="Title", style=discord.ButtonStyle.blurple)
async def button_callback(interaction: discord.Interaction):
     message = await self.old_interaction.delete_original_response()

I mean something like this

#

It might still not work tho. Depend on if delete_original_response is not a response

little cobalt
sage tendon
#

true that

errant trout
#

wait wrong way

#

invisible=True (which is default in components anyway)

#

tl;dr just defer before deleting

hazy turret
errant trout
#

what

#

literally that

hazy turret
# errant trout literally that

The message can be deleted, but how can I send the modal?```py
await interaction.response.defer(ephemeral=True)

await interaction.delete_original_response()

await interaction.followup.send_modal()```

errant trout
#

not possible

#

modal has to be the first response

#

can't even defer if you want to send a modal

hazy turret
errant trout
#

well

#

either delete the message in your modal callback, or after sending the modal use modal.wait to wait for a submission so you can delete it in the same function

#

tbh idk maybe send_modal -> instant delete works but i havent tried it

#

just experiment and come up with something GuraShrug

hazy turret
# errant trout well

When I pass the message ID to the button and try to fetch the message and then delete it. Would that work?

errant trout
#

can't fetch an ephemeral

#

well

#

that's blatantly wrong, you can just do fetch_original_response

hazy turret
#

Very simple way how it works:

await self.message.delete()

errant trout
#

wtv works GuraSquintSmol i didn't bother with .message since it used to have some issues

hazy turret
#

The button is in the view and the view object has the message object that I can delete

sage tendon
#

hey nelo

#

if i do guild = bot.get_guild(), then kick a member, and access guild.members, will that be the old or updated list?

little cobalt
sage tendon
#

no im getting first

echo wraith
sage tendon
#

ok
how?

errant trout
#

because half of python stuff is just referencing what's in memory

sage tendon
#

doesnt that need pointers

errant trout
#

not really

sage tendon
#

i feel dumb now
wtf
how

shell radish
errant trout
#

get_guild returns the guild object from ConnectionState via _get_guild, you kick a member, this triggers on_member_remove which also gets the guild from state and removes the member

shell radish
#

of abstraction

errant trout
#

it's never at any point made a new reference to guild

sage tendon
#

man
idk
i thought like if you return something it returns that as a new object

#

and not as a quasi pointer

errant trout
#

usually you need to copy for that

sage tendon
#

wait
huh
no i give up that makes no sense

#

so if i return a private list of an object, save it to some var, then that object changes the list, and i access the list where i save it, its also changed?? Wtf

#

idk man

errant trout
#

probably

#

just go try it

#

idk

sage tendon
#

(yes)

#

man i feel dumb

#

enough internet for today

errant trout
#

python is funny

sage tendon
#

i hate python now

slender lantern
#

Python is mostly pass-by-reference

edgy nest
#

it doesn't copy the entire object

fresh sierra
#

when im using
view = discord.ui.View.from_message(message).disable_all_items()
await message.edit(embed=final_embed, view=view)
it will remove the view of the message instead of disable it, is it intended ?

fresh sierra
echo wraith
#

Smth containing the view creation etc...

fresh sierra
# echo wraith Can you send a minimum reproductible code
class TestView(LumabotView):
    @discord.ui.button(label="Click Me", style=discord.ButtonStyle.primary)
    async def button_click(
        self, button: discord.ui.Button, interaction: discord.Interaction
    ):
        view = discord.ui.View.from_message(interaction.message).disable_all_items()
        await interaction.response.edit_message(view=view)

#

and send just a command that send the view

echo wraith
fresh sierra
echo wraith
# fresh sierra because i dont have access to the view in my real usecase
class TestView(discord.ui.View):
    @discord.ui.button(label="Click Me", style=discord.ButtonStyle.primary)
    async def button_click(
            self, button: discord.ui.Button, interaction: discord.Interaction
    ):
        view = discord.ui.View.from_message(interaction.message) # returns the View
        view.disable_all_items() # returns None
        await interaction.response.edit_message(view=view)

;)

fresh sierra
echo wraith
#

np

echo wraith
fresh sierra
echo wraith
#

I am addited to the debugger

echo wraith
fresh sierra
#

idk if i can do that through pterodacyl, because my debug bot is there with all db etc etc and api etc

echo wraith
merry ermine
#

One of my project is stuck on 2.5.0 and trying to update it doesn't work

#

Nvm it happens on 2.5.0 as well

#

Nvm, suggestion, add audioop-lts into the dependency list

sage tendon
#

It'll be fixed in 2.7 by using a different implementation altogether, and not audioop

merry ermine
#

Oh ok

quartz umbra
#

Hi! Does py-cord 2.6.1 support python 3.13?

#

I get the following error in 3.13 when trying to import it:

  File "/Users/_/venvs/_/lib/python3.13/site-packages/discord/player.py", line 29, in <module>
    import audioop
ModuleNotFoundError: No module named 'audioop'
sage tendon
#

read above

#

install audioop-lts until 2.7 drops

sly karmaBOT
quartz umbra
echo wraith
#

Np

quartz umbra
#

yk for like has_permission is there a place where i can find all of the different options in the docs? I can't find it

sage tendon
#

I mean, just all the permissions in the role permissions

quartz umbra
#

well i tried manage_server=True and that wasn't found

sage tendon
#

I think there's a list of them all in the discord docs but I always check the role list

sage tendon
quartz umbra
#

unless it doesn't work w bridge commands

sage tendon
#

no

quartz umbra
#

alr

sage tendon
#

manage_guild=True

#

that's what I mean

quartz umbra
#

yea thats what i set

sage tendon
#

you said server

quartz umbra
#

i did that before

#

then i changed

#

    @bridge.has_permissions(manage_guild=True)  # type: ignore let's see
    @bridge.bridge_command(
        description="ADMIN ONLY: Send a message as the bot to a given channel!"
    )
    async def say(self, ctx, message: str, channel: discord.TextChannel | None = None):
        """Sends the given message to the specified channel

        Args:
            ctx (_type_): given by py-cord
            message (str): The message to send
            channel (discord.TextChannel | None, optional): If not given, sends message in the channel the command was run. Defaults to None.
        """
        if channel != None:
            await channel.send(message)
            return
        await ctx.channel.send(message)
sage tendon
#

hm

#

it goes under the command decorator

#

not above

quartz umbra
#

ah

#

alr

verbal torrent
#

@tasks.loop(time=)
what should i insert for "time"?

sage tendon
#

The docs tell you

#

datetime.datetime or datetime.time

#

don't remember rn

errant trout
#

it's time

#

or a list of time

#

then it will run at that time every day

verbal torrent
#

hm. "time" is underlined in yellow in pycharm. but "datetime" not

errant trout
#

i.e. datetime.time

sage tendon
#

also in the docs :)

verbal torrent
#

when i try this:
@tasks.loop(time=datetime.time(6, 30, 0))
it says "unexpected argument" for "30" and "0"

errant trout
#

you need to specify what those values are

verbal torrent
sage tendon
#

check the python docs for datetime.time

#

all options and everything is explained there

sage tendon
verbal torrent
#

ok. thanks for help

sage tendon
#

Remember that timezones suck

#

the default is UTC I believe so it probably won't run on the time you specify if you aren't in UTC

verbal torrent
#

yeah ik. I set it to 1 hour earlier

sage tendon
#

you can also set the timezone in the time object

verbal torrent
#

now with the docs, i set it to "@tasks.loop(time=datetime.time(hour=6, minute=30, second=0))" but it says "unexpected argument" for hour, minute, second

#

oh wait. only time. withour datetime, right?

sage tendon
#

show the error

verbal torrent
#

i haven´t run the programm. it only says "unexpected argument" in pycharm

sage tendon
#

show

#

and never trust your IDE if you think it's right
run it first
pycharm also has a few bugs where it won't re analyze a file and tell you old errors

verbal torrent
#

here. but i just write the datetime

sage tendon
#

does it run

verbal torrent
#

yeah. without the datetime

sage tendon
#

wdym

verbal torrent
#

with datetime:
TypeError: unbound method datetime.time() needs an argument

sage tendon
#

then I think you're importing something wrong

verbal torrent
#

it´s running, when you set it to "@tasks.loop(time=time(hour=6, minute=30, second=0))"

sage tendon
#

show your imports

verbal torrent
sage tendon
#

yea that's the issue

#

you're basically using datetime.datetime.time() because you import datetime from datetime

#

just do import datetime

#

then it'll work

verbal torrent
#

but isn´t it the same, when you import time from datetime or writing datetime.time()?

sage tendon
#

yea but from imports should be limited
says Google in their official python style guide

#

because it makes it less clear where stuff comes from if you don't check every import

verbal torrent
#

ah ok

sage tendon
#

if you just write datetime.time everyone knows what it is, but time could be a third party library too

verbal torrent
#

hm. right

sage tendon
#

in the end it's preference so do what you feel looks best

verbal torrent
#

ok. thanks for helping me

sage tendon
#

np

tiny fractal
#
In rtc_region: Value must be one of ('brazil', 'hongkong', 'india', 'japan', 'rotterdam', 'russia', 'singapore', 'south-korea', 'southafrica', 'sydney', 'us-central', 'us-east', 'us-south', 'us-west').

https://docs.pycord.dev/en/stable/api/enums.html#discord.VoiceRegion
the documentation shows dubai, europe, eu_central, frankfurt as regions as well. but appear to be unselectable

sage tendon
#

prolly not updated to the new ones

tiny fractal
#

weird, those have been around for years from what i can see

sage tendon
#

ive never heard of dubai myself

tiny fractal
#

i've had it appear in automatic mode

#

but automatic mode likes to throw my middle-eastern user base into hongkong, which is absolutely un-usable lol

sage tendon
#

well if the API tells you no then thats a no Shrug_3

tiny fractal
#

ill submit an issue to remove those from the documentation then lol

errant trout
#

voiceregion enum needs a general update to be in line with the results of the List Voice Regions endpoint

#

(the enum should probably be deprecated in favour of a VoiceRegion class?)

echo wraith
#

It might as well be fetched then cached at runtime

#

So it's always up to date

fresh sierra
#

how can here i get the function that got trigger and in which the error occurs (basically the function from the item)

    async def on_error(
        self,
        exception: Exception,
        item: discord.ui.Item,
        interaction: discord.Interaction,
    ):
        error_message = await format_error(exception, item.callback) # here need to get the real fonction with the __name__
errant trout
#

use the traceback module

fresh sierra
#

I don’t really know how I can get the good func name from it

edgy nest
#

item.callback?

fresh sierra
#

found it later since callback is a partial func

deft bronze
#

Can a bot accept a image as command argument?

shell radish
#

yes

#

see the attachment example

rugged lodgeBOT
#

Here's the slash options example.

deft bronze
shell radish
#

no

deft bronze
#

Rip

short linden
fresh sierra
#

how should i do, im getting int has no attribute status
raise discord.errors.Forbidden(50013, "missing permissions")

fresh sierra
#

and i would like to know how should i do to raise it correctly

edgy nest
#

just write your own error class

fresh sierra
quartz umbra
#

hi so i have a simple /say bridge command whereby you choose a channel and a message, the bot will say it. Since it's a bridge command, it works fine as a prefixed command, but when used as a slash command, it gets "The application didn't respond", even when it did send the message. Is there a way to either: remove this message, or, send an ephemeral response that's only responded when its a slash command, but not a prefixed command? Thanks

echo wraith
errant trout
#

(he didn't use respond)

echo wraith
echo wraith
#

I think he wants to isinstance ctx bridge.SlashContext

quartz umbra
#

very simple command

#
    @bridge.bridge_command(
        description="ADMIN ONLY: Send a message as the bot to a given channel!"
    )
    @bridge.has_permissions(manage_channels=True)
    async def say(self, ctx, message: str, channel: discord.TextChannel | None = None):
        """Sends the given message to the specified channel

        Args:
            ctx (_type_): given by py-cord
            message (str): The message to send
            channel (discord.TextChannel | None, optional): If not given, sends message in the channel the command was run. Defaults to None.
        """
        if message == None:
            await ctx.respond(
                embed=discord.Embed(color=0xFF3333, title="You must specify a message!")
            )
        if channel != None:
            await channel.send(message)
            return
        await ctx.channel.send(message)
errant trout
#

you just check ctx.is_app

quartz umbra
echo wraith
#

oh right there's that

errant trout
#

yes

quartz umbra
#

alright thanks

errant trout
#

(it's just isinstance but it's shorter)

echo wraith
quartz umbra
#

another thing which is kinda unrelated, which discord permission corresponds to the mute_members permission in discord.Permissions?
Because i have the timeout members permission in a server, yet the bot says I don't have the Mute Member(s) permission?

errant trout
#

timeout is moderate_members

#

mute refers to VC mute

quartz umbra
#

oooh

#

alr thx

#

wait but

#

1 sec

#

yeah i have the vc mute members permission, so that still shouldn't be an issue

errant trout
#

what exactly is the issue

quartz umbra
#

i have a timeout command

#

is checks for has_permission, and even though i have the permission it says i doesn't

echo wraith
quartz umbra
echo wraith
echo wraith
#

uh

errant trout
#

so it's raising a checkfailure?

rugged lodgeBOT
quartz umbra
errant trout
#

is there a full traceback or do you have some custom handling on that

quartz umbra
#

I handle it here: ```py
@timeout.error
async def on_mute_command_error(self, ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.respond(
embed=discord.Embed(
color=0xFF3333, title="You don't have the permissions to run this"
)
)
else:
raise (error)

#

and that gets called (embed shown)

errant trout
#

mmm just in case, MissingPermissions has an additional missing_permissions attribute - 1) could you check that as well, and 2) has_permissions uses channel.permissions_for - could you use this to validate it returns true in that channel

#

i.e. channel.permissions_for(some_member_object).mute_members

#

if for some reason you have mute members denied in that channel then it'll fail even if you have it on the guild level, in which case you want has_guild_permissions (though there isn't a dedicated bridge decorator for this so you might have to build a custom check instead)

short linden
#

how i can register different command names (according to language)? like loritta do

echo wraith
#

use that

#

and

errant trout
echo wraith
#

discord.SlashCommand

short linden
#

but this is not for options name?

echo wraith
short linden
#

ahh

echo wraith
#

You have it for option and command

short linden
#

hmmm

errant trout
#

you're trying to translate names?

short linden
#

yes, loritta have this

errant trout
#

both commands and options support that

short linden
#

i'm from br and the command name is pt br

#

some of then

short linden
#

aaaaaaa

#

@echo wraith @errant trout ty

errant trout
#

allgood

short linden
#

slashcommand and command is the same thing right?

errant trout
#

if you're using discord.Bot yeah

echo wraith
short linden
#

okay, I'll try spy

echo wraith
#

.tag client

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)
short linden
#

How does the dictionary search work? Will it look for the key with the original command name within the language key? And where does it define the language?

errant trout
#

e.g. py {"pt_BR": "brazilian_command_name"}

errant trout
echo wraith
short linden
#

aaaaaaaa, then i need to configure a key for the command name, and after this configure a {"pt_BR": "brazilian_command_name"} in the key? if want to keep all commands in one dict?

errant trout
echo wraith
short linden
#

like: {"command": {"pt_BR": "brazilian_command_name"}, {"en": "en_command_name"}}, in the argument: dict["command"]

errant trout
errant trout
#

doruk built an extension to support it instead

#

maybe we can make something more convenient for v3 but for now if you want json support that's how you do it

short linden
#

ok, I'll try then, thanks spy

errant trout
#

next major version

short linden
#

of pycord?

errant trout
#

mhm

#

not until next year though

short linden
#

ooooh

#

have any spoiler?

errant trout
#

nothing too exciting so far lol

short linden
lapis dock
#

I thought v3 just going to be a normal update with breaking changes, nothin exciting XD

sage tendon
#

remember that minor pycord updates are also ripe with breaking changes :3

quartz umbra
#

Hi, my bot is responding twice to prefixed bridge commands. This doesn't occur with slash commands. My bot is a bridge bot. Here's my main.py: ```py
import discord
from discord import Embed
from discord.ext import bridge
from loguru import logger as log
from dotenv import load_dotenv
import os

Load the .env file

load_dotenv()
TOKEN = os.getenv("BOT_TOKEN")
GUILD_ID = os.getenv("GUILD_ID")

intents = discord.Intents.all()

bot = bridge.Bot(command_prefix="$", intents=intents)

@bot.event
async def on_ready():
log.info(f"Bot logged on as {bot.user} successfully!")

@bot.bridge_command(description="Get the bot's ping", guild_ids=[GUILD_ID])
async def ping(ctx):
embed = Embed(
title="Pong! 🏓",
description=f"The bot's ping is {round(bot.latency * 1000)}ms",
colour=0x33EE33,
)
await ctx.respond(embed=embed)

Load all extensions

cog_list = ["utilities", "moderation", "economy"]

for i in cog_list:
bot.load_extension(f"cogs.{i}")
log.debug(f"Loaded extension: cogs.{i} successfully.")

bot.run(TOKEN)

even $ping responds twice. Occurs in all cogs. This is only running instance of bot as no command works when I stop execution.
Thanks
#

logs: ```
2024-10-28 22:41:20.121 | DEBUG | main:<module>:38 - Loaded extension: cogs.utilities successfully.
2024-10-28 22:41:20.122 | DEBUG | main:<module>:38 - Loaded extension: cogs.moderation successfully.
2024-10-28 22:41:20.417 | DEBUG | main:<module>:38 - Loaded extension: cogs.economy successfully.
2024-10-28 22:41:26.809 | INFO | main:on_ready:20 - Bot logged on as The LeagueMC Helper#7907 successfully!

sage tendon
#

can you put a print / log in one of the commands and see what happens?

quartz umbra
quartz umbra
echo wraith
quartz umbra
#
@bot.bridge_command(description="Get the bot's ping", guild_ids=[GUILD_ID])
async def ping(ctx):
    log.debug("About to pong!")
    embed = Embed(
        title="Pong! 🏓",
        description=f"The bot's ping is {round(bot.latency * 1000)}ms",
        colour=0x33EE33,
    )
    await ctx.respond(embed=embed)
echo wraith
quartz umbra
quartz umbra
#

but then

#

how does it stop working whaat

#

thanks

echo wraith
#

np

quartz umbra
#

bro istg i don't find it when i know thats the first thing to look for but when i post and someone else says it i find it immediately 😭

dusk flume
#

When my bot is connecting to discord, its instantly getting rate limited. Is this normal? All it does on connect is change its presence once.

@bot.event
async def on_connect():
    await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="the system boot up"))
    print(f'{Colors.YELLOW}Connected to Discord! Locking commands and web access until bootup.{Colors.RESET}')
    print(f'{Colors.BLUE}Caching started (this may take a few minutes)...{Colors.RESET}')
torn barn
#

Yes, it is normal you are getting ratelimites, as you are changing presence in it

#

You have to set the status and activity kwargs on the constructor

dusk flume
torn barn
#

Do you have any more connection-related events? E.g: on_ready

shell radish
#

do you have members intent enabled? If so, it's just fetching all the members for cache which is normal

errant trout
#

you, uh, literally put "Caching started (this may take a few minutes)"

tidal vessel
#

Guys, can anyone help me? I'm following the guide but I get this error, not sure if I missed something

class TasksTest(Cog):
    def __init__(self, bot: Bot):
        self.bot = bot
        self.test.start()
    
    @tasks.loop(minutes=1)
    async def test(self):
        print("test")
    
    @test.before_loop
    async def test_2(self):
        await self.bot.wait_until_ready() 

Error:

Level: ERROR
File: test.py
Function: setup
Message: There is no current event loop in thread 'MainThread'.
Traceback (most recent call last):
  File "C:\Users\Usuario\Desktop\Bot de discord\Michi Explorador\cogs\tasks\tests\test.py", line 107, in setup
    bot.add_cog(TasksTest(bot=bot))
                ^^^^^^^^^^^^^^^^^^
  File "C:\Users\Usuario\Desktop\Bot de discord\Michi Explorador\cogs\tasks\tests\test.py", line 19, in __init__
    self.test.start()
  File "C:\Users\Usuario\Desktop\Bot de discord\Michi Explorador\.venv\Lib\site-packages\discord\ext\tasks\__init__.py", line 333, in start
    self.loop = asyncio.get_event_loop()
                ^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Usuario\AppData\Local\Programs\Python\Python312\Lib\asyncio\events.py", line 702, in get_event_loop
    raise RuntimeError('There is no current event loop in thread %r.'
RuntimeError: There is no current event loop in thread 'MainThread'.
silk spire
#

I think you need to start the task in an async environment

#

Like on_ready or create a task

#
# class
def __init__(self, bot):
    ...
    asyncio.create_task(self.async_init())

async def async_init(self):
    self.my_task.start()
    ...

...
fresh sierra
tidal vessel
fresh sierra
#

i think you are starting it using another asyncio.run tasks or thread

#

and it might be the issue

tidal vessel
#

ok a moment

tidal vessel
# fresh sierra i mean ur main.py file
class MichiBot(Bot):
    def __init__(self):
        self.intent = Intents.default()
        self.intent.message_content = True
        self.intent.guilds = True
        self.intent.members = True
        self.intent.messages = True
        
        super().__init__(
            command_prefix=prefix_server, 
            intents=self.intent,
            case_insensitive=True,
            strip_after_prefix=True, 
            help_command=None,
        )
    
    def execute(self):
        try:
            logging.info("Loading...")
            data = asyncio.run(data_db_cache())
            
            if not data:
                logging.error("Failed to recover data")
                return

            logging.info("Loading extensions...")
            
            self.load_extensions("cogs", recursive=True)
            token = dotenv.get_key(dotenv_path=".env", key_to_get="TOKEN")
            
            if not token:
                logging.error("Token not found")
                return
            
            logging.info("Starting...")
            
            self.run(token)
        
        except Exception as error:
            logging.exception(error)

bot = MichiBot()

if __name__ == "__main__":
    bot.execute()
#

If I start the task with a command manually it works

echo wraith
#

In your code

#

Before starting the bot

tidal vessel
fresh sierra
#

you can do a async get main()

#

using bot.start

echo wraith
fresh sierra
#

and then do asyncio.run(main)

echo wraith
#

np

vestal folio
#

how to chack the cannel of the type anouncement channel

#

As options

broken oxide
#

Hey, is it normal that slash command decorators are not working for a command group ?

Very basic example:

group = discord.SlashCommandGroup("example", "Test group", guild_ids=[...])

@group.command(name="test")
@discord.option(name="Echo", input_type=str, description="Echoes something")
async def echo(ctx, example: str):
  await ctx.respond(example)

For my command, I'll have /example test example: and not /example test Echo:

sage tendon
#

i mean with the code you gave, /example test example: is just how its supposed to work

#

to match the option onto the parameter name, if the name differs, you need to pass parameter_name="example" to your option decorator

#

or, well, just name it the same and not completely different things lol

quartz umbra
#

does @discord.Option, and choices, work with Bridge commands? Especially prefixed bridge commands?

sage tendon
#

no

#

BridgeOption is what yo uneed

quartz umbra
#

and

#

does that work w choice?

sage tendon
sage tendon
quartz umbra
#

ah so it won't so you have to handle it manually, alright thanks

echo wraith
quartz umbra
sage tendon
#

where does it say it doesnt?

quartz umbra
#

it does?

sage tendon
#

it's literally a subclass of discord.Option

quartz umbra
#

oh

#

but how would it work w prefixed commansd?

sage tendon
#

the docs say that -w-

#

try it and see

quartz umbra
#

alr

#

but i got another question, can I ask?

echo wraith
#

sure

quartz umbra
#

is it possible to send data to a view?

sage tendon
#

like?

quartz umbra
#

like say an int

sage tendon
#

just pass it to the constructor?

quartz umbra
#

so like im tryna make an economy bot, and if you press the button, you get that much which is predetermined

quartz umbra
sage tendon
#

just pass whatever int you want and then do self.value = value or whatever

#

you dont have to change anything else

quartz umbra
#

alr

#

thanks

sage tendon
#

in __init__

hazy turret
#

Can someone tell me why I can't delete the message even though it is displayed in print?

<Message id=1300816740560801845 channel=<TextChannel id=1176093845214208002 name='text' position=1 nsfw=False category_id=1176093845214218001 news=False> type=<MessageType.reply: 19> author=<Member id=1153983766665545738 name='Test-Bot' discriminator='2710' bot=True nick=None guild=<Guild id=1176093844324444395 name='Test Server' shard_id=0 chunked=False member_count=11>> flags=<MessageFlags value=64>>

async def button_callback(interaction: discord.Interaction):
   print(self.message)
   await self.message.delete()```

discord.errors.NotFound: 404 Not Found (error code: 10008): Unknown Message
fresh sierra
echo wraith
#

if it's an interaction response u can't

echo wraith
#

Can you send the full view code

sage tendon
#

is it ephemeral?

hazy turret
#

It is a view with buttons. And when I click on the button, I want to delete the message.
Yesterday it still worked. Today I always get the error 😄

fresh sierra
#

is the bot admin ?

hazy turret
fresh sierra
#

well i also have this error a lot in my log, i was thinking it was because of lack of permission but maybe no

little cobalt
#

await Interaction.delete_original_response() or something like that for Interactions

hazy turret
#

I am extremely surprised because it worked yesterday and I didn't change anything and have just tested the function again and now it no longer works 😄

little cobalt
#

I had the same with my command builder

hazy turret
little cobalt
#

I was using decorater for it and it just stopped working after some time

#

Now I use _on_pending_application_commands

hazy turret
#

Okay if I don't set the message with the view and the buttons as ephemeral it works again.
Yesterday it also worked with ephemeral message.

#

I send the message with
await interaction.followup.send

hazy turret
sage tendon
#

its a weird type of message

hazy turret
#

It's driving me crazy right now because I can't understand why it worked yesterday and suddenly doesn't today 😄

lapis dock
#

If the ephemeral message no longer exists it will not be able to delete it. So if you are clicking dismiss message or have just waited a few minutes it will not exist anymore

hazy turret
hazy turret
# lapis dock If the ephemeral message no longer exists it will not be able to delete it. So i...

await interaction.followup.send(embed=edit_prompt_embed, view=AttributeEditView(self.bot, uuid), ephemeral=True)


class AttributeEditView(discord.ui.View):
    def __init__(self, bot: discord.Bot, uuid):
        super().__init__(timeout=None)
        self.bot = bot
        self.uuid = uuid

        # Add buttons for each attribute that can be edited
        attributes = [
            ("Title", "title"),
            ("Starting Price", "starting_price"),
            ("Description", "description"),
            ("Minimum Bid Increase", "min_bid_increase"),
            ("Currency", "currency"),
            ("Duration", "duration"),
            ("Quantity", "quantity"),
            ("Scheduled Start", "scheduled_start"),
            ("Category", "category"),
            ("Subcategory", "subcategory"),
            ("Message", "message"),
        ]
        for label, name in attributes:
            button = discord.ui.Button(
                label=label, style=discord.ButtonStyle.primary, custom_id=name
            )
            button.callback = self.create_button_callback(name, label)
            self.add_item(button)

    def create_button_callback(self, attribute_name, attribute_label):
        async def button_callback(interaction: discord.Interaction):
            logger.info(self.message)
            await self.message.delete()```
errant trout
#

idk why it worked before/doesn't work now, but regardless you're meant to use that method

broken oxide
sage tendon
#

show your code how it is right now

broken oxide
#

I’m on phone, I’ll just show an example

sage tendon
#

you probably didn't pass parameter name if it still doesn't work

broken oxide
sage tendon
#

yea you didn't do what I said

broken oxide
sage tendon
#

it is, because as it is now, your decorator does nothing

broken oxide
#

That’s what I guessed

sage tendon
#

because it can't find a parameter called Echo

broken oxide
#

So to fix that, I just add something like parameter_name="example"

sage tendon
#

yes

broken oxide
#

The docs got me a little confused on that part lol

hazy turret
errant trout
#

That works because followup is a Webhook, and followup.send returns an appropriate WebhookMessags

#

It works on its own logic, not by using the regular delete endpoints

latent hare
#

heya, i am trying to add a modal to a slash command. the modal pops up and when i enter text and hit submit, it pauses for a few and then i get a Something went wrong. Try again

#

all it does currently is async def on_submit(self, interaction: discord.Interaction): await interaction.response.send_message("Send message")

#

im guessing its something simple but i cant figure it out

fresh sierra
#

its on_callback for py-cord

latent hare
#

facepalm works now, thank you!

hazy turret
#

Is it possible to register slash commands only on one server without them being displayed in the DM's?
Because with @commands.guild_only() they are still displayed in the DM's.
My only solution is currently:
@slash_command(name=“”, description=“”, guild_ids=[GUILD_ID])
but this is not the way I want it because I would have to specify every Guild ID. I would like to have it registered on every guild but not displayed in the DM's.

echo wraith
little cobalt
#

guild_ids=[] is the only way to do it

little cobalt
hazy turret
echo wraith
hazy turret
echo wraith
#

like this

hazy turret
#

Ah okay

echo wraith
little cobalt
#

and they still gonna be a normal slash command?

echo wraith
#

But i wanna check smth

#

Yeah the issue was it used commands.guild_only instead of discord.guild_only but the latter is deprecated anyways soo

round heart
#

Do App Emojis (##2501) make for a breaking chance since

Emoji has been renamed to GuildEmoji.

#

(...although it turns out I don't use that class directly, so I suppose it doesn't matter for me. But curious in general)

shell radish
hazy turret
#

Does anyone know why I sometimes have problems when several users use a button at the same time?

I have an embed with a button that is in a view. When a user clicks the button, an ephemeral message with 8 buttons opens. Each button is for a category. If the user then clicks on a category, a paginator opens in an ephemeral message. This should be a separate instance for each user, so that if 4 users click the first button at the same time, each user should have a separate instance of the category selection and then also have a separate instance of the paginator, so that there should be no problems and everyone can browse through their paginator without any problems, right?

But currently I often have the problem that when several users click the first button, the interaction fails. What can I do about this? Or is this unavoidable because it is due to the speed of the Discord API that it cannot process multiple button clicks so quickly?
I'm already working with response.defer in the button callback to give the response to the interaction more time, but that still hasn't made it work properly.
Does anyone have an idea or a solution?

lofty hedge
#

How do I ban someone who’s not in the server?

sage tendon
#
echo wraith
lofty hedge
#

Pycord

#

Let me look

#

That page doesn’t load

sage tendon
#

lol

lofty hedge
#

It tries to load the page initially then before it does it shows that

sage tendon
hazy turret
broken oxide
#

Hey is there a way to reload autocomplete for slash commands (without restarting the bot). I've tried reloading the cogs but it doesn't seem to work

prime hill
#

hey, how can we get attached medias link?

sage tendon
#

attachment.url

#

check the docs

little cobalt
sage tendon
#

you dont know what exactly they want tho lol

errant trout
#

they sound pretty clear to me?

#

if you made an autocomplete function, it'll reload whenever you reload the cog

sage tendon
#

yea but a function doesn't need reloading

#

its stateless

#

thats why i asked why to find out why they want to reload a function

errant trout
#

...? all functions in a cog update their logic whenever you reload

#

are we really arguing the semantics of cog reloading

sage tendon
#

bruh?
the funciton doesnt suddenly change

#

it still has the same result with the same input unless it uses other variables

errant trout
#

we're talking about when someone updates the file

#

that's the implication whenever someone's trying to "reload" it

sage tendon
#

are we though? not part of their message

#

thats why i asked them instead of assuming

#

also to prevent the x-y problem

errant trout
#

ohwell

prime hill
broken oxide
#

Perhaps that’s issue

errant trout
broken oxide
#

To be clear, the autocomplete relies on a database

errant trout
#

is this choices or autocomplete

#

these are two different things

broken oxide
errant trout
#

choices are command metadata, so it requires a restart

broken oxide
#

Damn

errant trout
#

yes

#

if you're trying to get something from a db, you should be using autocomplete

#

since that is fully dynamic

broken oxide
rugged lodgeBOT
#

Here's the slash autocomplete example.

broken oxide
errant trout
#

no?

broken oxide
#

On my experience it is

errant trout
#

unless your db operations are stupidly slow

#

autocomplete generally loads within a second

#

under 3 seconds is required

sage tendon
#

It's slower because it needs to go discord > bot > discord
instead of discord inherently knowing the choices

broken oxide
errant trout
#

i mean, "slow" being "not instant" sure

broken oxide
#

I’ll switch thanks

errant trout
#

allgood

sage tendon
#

see nelo this is why I ask before making assumptions

errant trout
#

they said autocomplete lol

sage tendon
#

typical case of X Y problem

broken oxide
round heart
#

Hey I have a dumb question ... can you pass arguments to the function that autocomplete= uses..? For cases where I might want to re-use the AC method but add additional logic

sage tendon
#

you could just overload it

round heart
#

hwat

sage tendon
#

or i think adding defaulted kwargs should worK?

round heart
#

To give more context, I have a command with two options. I wanted to have the second one use an argument flag so that my AC function will compare it with the value of the first option.

sage tendon
#

oh, not that way i think
but you can access other command options

#

so if first option isnt set, you know you are currently in the first option (98%)

round heart
#

I suppose. But there may be other commands that use this AC without having two of the same options

#

I was hoping to avoid making super-specific AC methods 🙂

errant trout
flat wind
#

is it possible to accept multiple types in a slash command option ?
I am trying to accept str and GuildChannel but it does not work :

    @option(
        name="output_channel",
        description="Set up the channel where the flag reaction message will be sent",
        required=False,
        type=Union[str, GuildChannel],
        choices=[
          "None"  
        ],
        channel_types=[
            ChannelType.text,
            ChannelType.voice,
            ChannelType.stage_voice,
            ChannelType.news,
            ChannelType.forum
        ]
    )
shell radish
flat wind
#

okay... sad, I'm going to need to think of another solution then

#

thanks

sage tendon
#

i mean why do you want a string input?

#

the user can select every channel anyway in the selection popup

flat wind
# sage tendon i mean why do you want a string input?

yeah but I want something like this :
if it is None, then don't touch the configuration
if it is a channel, then add the channel ID to the DB
if it is a string (like "None"), then remove the channel ID from the DB

sage tendon
#

just make it optional (as you already did), then its None if not used

flat wind
#

yes but what about the deletion ?

sage tendon
#

wdym?

shell radish
#

make a separate command or use a command group

flat wind
# sage tendon wdym?

if the users type "remove" in the field, then it just remove the channel from the DB, like as default

sage tendon
#

..and if they leave it empty, itll be none, and then you can just do that as well

#

i dont see the need for a specific user input

flat wind
sage tendon
#

ah

#

yea then I'd probably use a command group, sounds like a more complex feature

flat wind
#

Yeah I will do that

#

is it possible to make a command, and a subcommand of it like if it was a group ?

example :
/command (some options)
/command test (some options)

lapis dock
#

Unfortunately no

flat wind
#

okay, I will rewrite my full command then lol

#

thanks

sage tendon
#

would be very cool but the way discord handles commands it probably will never happen

#

because subcommands are handled as options for the main command..

ivory beacon
#

how to get member count without bots ?

glad spoke
echo wraith
ivory beacon
ivory beacon
echo wraith
echo wraith
#

with with_counts=True

#

then

rugged lodgeBOT
echo wraith
#
guild = await bot.fetch_guild(id, with_counts=True)

count = guild.approximate_member_count
dusk flume
hazy turret
#

Can anyone tell me why my messages are either all sent ephemeral or not at all?

If I do this:

await ctx.defer()
await ctx.followup.send(“Hello”, ephemeral=True)
await ctx.followup.send(“Hello 2”)
await ctx.followup.send(“Hello 3”, ephemeral=False)

everything is not sent ephemeral.
If I do that:

await ctx.defer(ephemeral=True)
await ctx.followup.send(“Hello”, ephemeral=True)
await ctx.followup.send(“Hello 2”)
await ctx.followup.send(“Hello 3”, ephemeral=False)

everything is sent ephemeral

With

interaction.response.defer(ephemeral=True)

it works without problems.

echo wraith
#

uhh

sage tendon
#

afaik ctx.defer is just a shortcut to interaction.response.defer tho so idk why it acts differently according to you

#

Might be a bug where ctx sends every follow-up as ephemeral if you use ctx.defer because it somehow saves that it was deferred, even if it shouldn't do that for future follow ups that aren't a response to the original interaction

#

but that's just blind guesses

hazy turret
sage tendon
#

i mean it literally just calls interaction.response.defer

#

so it shouldnt behave differently

hazy turret
# errant trout can't repro

I have tested it again in an extra cog.
Result:
Normal
Normal
Normal
ephemeral
Normal
Normal

class TestCog(commands.Cog):
    """A Cog for testing defer and followup behavior with slash commands."""

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

    @commands.slash_command(name="test_followup_1")
    async def test_followup_1(self, ctx: discord.ApplicationContext):
        """Test command with defer and multiple follow-up messages."""
        await ctx.defer()
        await ctx.followup.send("Hello", ephemeral=True)
        await ctx.followup.send("Hello 2")
        await ctx.followup.send("Hello 3", ephemeral=False)

    @commands.slash_command(name="test_followup_2")
    async def test_followup_2(self, ctx: discord.ApplicationContext):
        """Test command with defer (ephemeral=True) and multiple follow-up messages."""
        await ctx.defer(ephemeral=True)
        await ctx.followup.send("Hello", ephemeral=True)
        await ctx.followup.send("Hello 2")
        await ctx.followup.send("Hello 3", ephemeral=False)


# Setup function to add the Cog
def setup(bot):
    bot.add_cog(TestCog(bot))```
sage tendon
#

Aren't those results exactly how it's supposed to work tho

hazy turret
#

But in my cog both messages are sent ephemerally although the lower message should not be if no error occurs ?

            await ctx.defer(ephemeral=True)

            result = await HPCGame.play_game(
                discord_server_id=ctx.guild.id,
                discord_server_name=ctx.guild.name,
                discord_user_id=ctx.author.id,
                discord_user_name=ctx.author.name,
                bet_amount=bet_amount,
                chosen_element=element,
            )

            if not result["success"]:
                embed = discord.Embed(
                    title=result["title"],
                    description=result["message"],
                    color=BOTCOLORS.ERROR,
                )
                await ctx.followup.send(embed=embed, ephemeral=True)
                return

            embed = discord.Embed(
                title=result["title"],
                description=result["message"],
                color=(
                    BOTCOLORS.SUCCESS
                    if result["win_amount"] > bet_amount
                    else (
                        BOTCOLORS.ORANGE
                        if result["win_amount"] == bet_amount
                        else BOTCOLORS.ERROR
                    )
                ),
            )
            await ctx.followup.send(embed=embed)
hazy turret
fresh sierra
sage tendon
#

yea

#

the first followup after a defer is equal to ctx.respond

hazy turret
#

In my test cog, only the message await ctx.followup.send(“Hello”, ephemeral=True)
is sent ephemerally and await ctx.followup.send(“Hello 2”)
normal.

But in my real cog, both messages are sent ephemerally

sage tendon
#

because your last followup line replies to the deferred interaction

#

which is forced to be ephemeral

#

And there is no point to use followup.send

#

ctx.respond handles followups all on its own

hazy turret
sage tendon
#

really the only things you ever need are ctx.defer and ctx.respond

#

all the followup stuff isnt necessary to be used by you

hazy turret
sage tendon
#

yea well views are different lol

hazy turret
hazy turret
sage tendon
#

dont defer

#

:>

#

bit uglier way is to
defer ephemeral
if it worked successfully, respond with something to the ephemeral message, delete it (optional), then respond again (this will not be forced ephemeral)

#

its kinda ugly and hacky tho

hazy turret
#

Hmm, I already had that option in mind, but I don't like it 😄

sage tendon
#

does your play_game stuff really take almost 3 seconds tho?

hazy turret
#

I'm surprised because it works with my buttons with interaction.response.defer and interaction.followup.send without any problems 😄

sage tendon
#

yea because views are different

hazy turret
echo wraith
#

It would make no sense if a follow-up to an ephemeral isn't one

quartz umbra
#

What am I doing wrong? I get TypeError: 'BridgeOption' object is not callable: ```py
@bridge.bridge_command()
@bridge.BridgeOption(
str,
description="Which fruit to bet on",
choices=[
discord.OptionChoice("banana"),
discord.OptionChoice("apple"),
discord.OptionChoice("orange"),
discord.OptionChoice("mango"),
],
)
async def bet(self, ctx, amount: int, fruit: str) -> None:

sage tendon
#

it's bridge_option

#

also you don't need an optionchoice, just pass the values as strings

hazy turret
#

Is it possible to return a text with autocomplete and if the user has selected something a value in the background as with OptionChoice?

sage tendon
#

you can use optionchoices in autocomplete yes

hazy turret
sage tendon
#

yea

hazy turret
#

Okay nice. Thanks 🙂

crimson lily
#

I forgot what was the line that was needed to be added so both slash commands and normal commands worked together?

lapis dock
#

You are looking for the bridge extension, I am not super familiar with it

crimson lily
#

i remember it being just a simple line that was needed somewhere and i dont remember it having bridge in it

#

maybe they changed it up

#

oh wait i dont mean that one command serving as both slash and normal

#

I meant that i've got 2 distinct commands in my code
one slash one normal

lapis dock
#

Oh, you need to use discord.ext.commands.Bot instead of discord.Bot

crimson lily
#

on the non slash commands?

lapis dock
#

For your bot instance

crimson lily
#

got it, thanks

#

Curious, whats the downside of using discord.ext.commands.Bot instead of discord.Bot?
id assume if it was the same they'd just let us use both types of commands by default

lapis dock
#

.tag client

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)
echo wraith
#

I wonder how much @bot.command aliasing to @bot.slash_command in discord.Bot is a good idea, as it means that whenever you change your instance to commands.Bot it breaks stuff

lapis dock
#

You will need to use @discord.ext.commands.command for prefix commands and @discord.commands.slash_command for slash commands

sage tendon
#

discord.slash_command is the shortcut for slash btw

#

not sure about prefix

shell radish
#

there’s also like discord.ext.commands.slash_command

sage tendon
#

am i the only one who feels like the library structure could use an overhaul?

lapis dock
sage tendon
#

i legit have no clue why it's even ext

#

like its not an extension really

#

its about as main of a feature as you can get

lapis dock
#

I want the exts to be installed seperatly

shell radish
sage tendon
#

but doesnt it contain about everything command related?

shell radish
#

before commands existed yeah

sage tendon
#

hm

sage tendon
#

like some stuff feels duplicated, some feels random, there are tons of aliases

lapis dock
#

I do think there are way to many aliases

errant trout
#

we already shot down the overhaul that was the old v3

sage tendon
#

Like dont get me wrong i do like top-level aliases like discord.option, because its not really ambiguous

#

but like

#

option / Option has like 3 more aliases at different levels

#

why?

shell radish
errant trout
#

they aren't exactly aliases

#

almost everything is made accessible at the root discord level, beyond that if you do something like discord.commands.Option or discord.user.User that's just regular pathing

shell radish
#

it’s not specific to option

sage tendon
#

I also still wonder, with stuff like the Option typehint
With almost every type checker disliking it, is it even supposed to work? Like it does feel wrong to make a function call that then returns a type essentially

errant trout
#

Option typehint is explicitly coded in

sage tendon
#

yea in pycord, yes

#

but generally, i've never seen typehints being a function call

#

so it feels like it's discouraged?

#

or ive just not seen stuff where its used

shell radish
#

this should be moved to #general or #discussion

sage tendon
#

yes lets go #general

quartz umbra
#

Hi! I have this code ```py
self.disable_all_items()
await interaction.response.edit_message(view=self)


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

I don't know what I'm doing, this code was taken from the Guide, but the page for this is incorrectly formatted.

Learn all about implementing buttons in your Discord Bot using Pycord.

errant trout
#

or make any response before edit_message

quartz umbra
errant trout
#

use interaction.edit instead

quartz umbra
#

alr

#

Also, do aliases work with slash commands? Or do you have to make a slash command for each

shell radish
#

there isn't a good reason to have aliases for slash commands since typing / pulls everything up

sage tendon
#

and it matches descriptions too

short linden
#

but i respond with the same view, updating it before

fresh sierra
#

shouldnt this raise a badargument error ?

#

channel: discord.TextChannel | discord.VoiceChannel = None,

errant trout
#

well, either BadFlagArgument or BadLiteralArgument or BadUnionArgument (the latter 2 are UserInputError)

fresh sierra
errant trout
#

why don't you check the type then GuraSquintSmol

fresh sierra
#

it often give me error.class command invoke error as class, im gonna check for prefix it usually give the good one

errant trout
#

if you got CommandInvokeError then you have to access error.original

fresh sierra
#

yep its a BadUnionArgument

errant trout
#

there you go

fresh sierra
errant trout
#

yes

#

and ApplicationCommandInvokeError

fresh sierra
#
        if isinstance(error, commands.CommandInvokeError) or isinstance(
            error, discord.ApplicationCommandInvokeError
        ):
            error = error.original
#

am i using a wrong path ?

#

or it directly from command or discord

errant trout
#

uhh those would be correct

fresh sierra
#

thanks

#

also python related question but

#

is there a way to do isitance of multiple class

errant trout
#

also isinstance can take a tuple for multiple types

#

yeah LOL

fresh sierra
#

perfect !

errant trout
#

though, ApplicationCommandInvokeError will only raise in on_application_command_error and vice versa

#

the easiest hack with error.original is to just re-raise the same handler

fresh sierra
#

so just raise error.original ?

#

i mean i did put at the beginning of my on_application_command_error the isistance so i think its the same

errant trout
#

mmmm that might work? but perhaps i phrased wrong, i'd just do await on_command_error(ctx, error.original) or so

echo wraith
#

I just do if hasattr original error = error.original

limpid marten
#

i havent ran this code in so long and i get this error browhat

#

did sync_commands() change or something?

#

the rest of the commands run fine, it just wont let me sync any of the commands

fresh sierra
limpid marten
fresh sierra
#

check again

#

its ur 4th command

short linden
sage tendon
versed root
#

if i use thread.members, the data is not accurate, what should i do?

lapis dock
#

Did you follow both notes in the docs?

versed root
#

ok, i know how to do, tq

echo wraith
#

Is it possible to get a member's username color (the color of the highest colored role) ?
I can't read message.author.color

sage tendon
#

wont work with user apps, keep in mind

echo wraith
#

yup exactly

short linden
#

I'm confused about these intents, if I leave them as default, will my program try to respond to several events that I haven't even programmed a function for?

lapis dock
#

No, but there is not much reason to turn on intents that you do not need as it will lead to increased amounts of data discord needs to send you. And in some cases it will increase your RAM usage due to the bot using cache

sage tendon
#

generally default intents are fine, that's why they're default

limpid marten
#

ok i found the problem

#

the problem was that i had 2 @bot.slash_command

sage tendon
#

so you did

autumn narwhal
#

How can I completely avoid this 403 error?

[1;30;40m| 2024-11-02 01:53:49【- test -】: POST https://discord.com/api/v10/channels/1301967446969946125/messages with {"content":"abcdefgh"} has returned 403

this is my code:

dm = await self.member.create_dm()
if dm and dm.permissions_for(dm.me).send_messages and self.member.mutual_guilds != 0 and not self.member.bot: dm.send........
errant trout
#

eh...

sage tendon
#

you dont have to create a DM btw, you can just use member.send()

#

and catch discord.Forbidden if the user disabled DMs

#

or no mutual servers

#

or blocked the bot

lofty parcel
#

That's a long condition lol

torn barn
#

And you dont need to check for permissions on a dm channel lol

#

You have all the text related ones allowed

sage tendon
#
try:
    member.send(...)
except discord.Forbidden:
    ...
errant trout
#

i think they wanted to use permissions to see if you can dm the user, but that doesn't work

#

you basically have to try/except dms

loud kayak
#

At what server count should a public verified bot be converted to an AutoShardedBot?

torn barn
#

Discord sends you a message when needed

errant trout
#

generally after 1000 or so if you notice your bot dropping in performance you should consider it

#

it's required at 2500

autumn narwhal
sage tendon
#

that will leave the log clean

#

unless you have an odd setup

errant trout
#

the point of try-except here is to catch the error because there's too many conditions in which you can't dm a user, and it's not possible to validate without using send

feral plover
#

hey there

#

can anyone explain me what is conditional statements?

#

and how to use it without getting error

fresh sierra
feral plover
#

yep

echo wraith
fresh sierra
feral plover
#

yes

echo wraith
# feral plover yes

feel free to send your code here, we can help, also if you are new to python you have a ton of resources here

#

.learnpython

sly karmaBOT
sage tendon
#

If you don't know what an if statement is, Pycord is too much to head into python with

#

Please learn programming at its base first

shell radish
sage tendon
#

might, else they wouldn't have ended up here

lapis dock
# feral plover okay

This server is for py-cord a library for creating discord bots with python. If you are interested in that feel free to stay :)
If you are just looking for a general python hep community discord.gg/python is a better place

round heart
#

So I have a bit of a dumb question. I seem to remember that some parts of the UI classes auto-magically had access to the view that called it. But I can't find any code to support that.

Am I misremembering that with something else? If I want a Modal to get access to the parent View that called it, I'd have to still explicitly pass in the view instance?

short linden
errant trout
#

seeing that modals aren't directly related to views, that wouldn't be built in

#

when it comes to actual view items (Button, Select) they have a view attribute

short linden
#

modal.view?

round heart
#

Back to Modals, what's the best way to no-op if they submit something and nothing needs to happen (e.g. the text input has a value already and they just submit)?

I lazily though return True would work here, but I guess there's no response to close out the interaction

errant trout
#

for any UI component, a plain defer is fine because it defaults to invisible

round heart
# errant trout defer

Hm, the callback passes interaction, there's no interaction.defer(). What should I be calling?

errant trout
#

have you never deferred?

shell radish
#

interaction.response.defer()?

errant trout
#

yeah we were meant to implement the shorthand to match ctx.defer but it slipped past me

round heart
#

Ahhhh. response.defer, thanks

round heart
#

.rtfm delete

round heart
#

.rtfm message_delete

round heart
#

meh. What's the thing where you can tell a channel to delete messages beyond a certain point

lapis dock
#

purge?

round heart
#

Just to sanity check, I need to purge all messages after a selected message. I'm creating a Message command for that. Looks like after takes a date (or a snowflake time.. is that the same as ID or no? message.id is suggesting an error)

cursive swallow
#

it should be able to take an ID

round heart
#

I guess because message.id is an int, and it's looking for SnowflakeTime specifically

cursive swallow
#

does the code execute correctly?

round heart
#

Haven't tried yet

#

doing now

cursive swallow
#

SnowflakeTime is literally the union of Snowflake and datetime

round heart
#

Oh. Application Command raised an exception: AttributeError: 'int' object has no attribute 'id'
Guess I can just pass in the message itself

cursive swallow
#

well somehow your message is an int

#

or whatever you did .id on

round heart
#

From the screenshot, I initially passed in message.id. If I just pass message (which is received from the message_command), then it's fine. Just a little docs weirdness.

lapis dock
cursive swallow
round heart
#

My bot went haywire and started spamming reminder messages, did about 4-5000 til I was able to kill it. Was trying to quickly get something to clear them out (which I have now done). Thanks again

deft bronze
#

How can i make a command required?

echo wraith
echo wraith
deft bronze
#

Yes

echo wraith
#

Can you send the code you have rn and what option you want to be required ?

sage tendon
#

options are required by default. you dont have to do anything extra

echo wraith
#

yeah

deft bronze
#

I don't remember how to use the option

echo wraith
sage tendon
#

pycord automatically makes those into options

deft bronze
#

alr

sage tendon
#

did you even test it lol

deft bronze
#

Didn't know that happens without the option @

deft bronze
#

How can i do a timed event?

#

like at 8:00:00 (for example)

#

.rtfm tasks

lapis dock
glossy tide
#

Hello, to have a user's invitations, do you have to save them in a database (when the inviting member joins) or is there a way to have it with only {user.invites} for example?

glossy tide
#

Oh okay!

deft kestrel
#

Does pycord support linked roles? (App Metadata for Linked Roles)

echo wraith
echo wraith
#

actually, I think it publishing the roles metadata might be in scope

#

as it's rest api

#

I'll open an issue

deft kestrel
merry ermine
#

Hi, I was wondering if the documentation for the event on_guild_stickers_update was wrong because it claims it uses the type Sticker | None but in reality it's a tuple

#

Might just be me or my IDE but I was wondering this

#

Nvm it's just my IDE tripping

#

I don't know what's happening but the official docs say Sequence, it returns a tuple and my Pycharm thinks it's a Sticker | None?

sage tendon
#

whatever this is, its not pycord

#

events cant even be typed "from pycord" in that way because you write your own listeners for them

#

so you probably typed it that yourself

latent hare
#

when i kill my bot script and the re run it with changes, none of the existing buttons on messages work anymore. the buttons' views have timeout=None set and have custom_ids set. is there a way for them to still work after restarting?

sage tendon
#

you need to do bot.add_view(YourView()) on startup

latent hare
sage tendon
#

that cant be preserved, no

#

you need to save that to a DB

latent hare
#

makes sense, ill play around with that. thx

sage tendon
#

wait but

#

if its only the data of the message the view is attached to, you can just do view.message

#

but i assume youre saving some other stuff too

#

@latent hare

fresh sierra
#

something that might need checkout is command.ext_variant.aliases return None even if the prefix command have some alias

#

i have this issue but idk if because i change my implementation of bridge

echo wraith
lapis dock
fresh sierra
#

The thing that might change is that I changed the alias after the command creation with command.aliases = …
So at the point the bridge command might be already created and not edit

errant trout
#

they mean test it without any of your modifications

eternal kite
#

is it a good idea to store module files in txt format in the database? so that i can update the file in the database and reimport the module without having to restart the bot

fresh sierra
eternal kite
fresh sierra
eternal kite
#

if i update the file in my pc i need to reupload it

fresh sierra
#

Then u update ur file using the git

#

And you reaload the extension

#

No restart needed

eternal kite
#

right never thought of using git

#

i used to just keep my files locally

fresh sierra
#

You can just reload every extension

#

And will not need any got

round heart
#

data.components.0.components.0.options would imply an issue with a dropdown, right? (even if it's not the first child)

#

Oh nvm, I see the issue now. Shit, I have more than 25 entries.

#

Does anyone do anything fancy with dropdowns with datasets of more than 25 options? Maybe having one of the options be a selection that changes the dropdown to a new dataset

sage tendon
#

What I usually see is just multiple dropdowns

#

which are labelled A-F, G-O, P-Z for example

echo wraith
#

yeah I do smth similar

round heart
#

hm. maybe. I guess it would be equally complex (for my application) as making a paginator for the dropdown.

sage tendon
#

or, which is a bit more weird to use, you make a dropdown that selects a range (as before, e.g. A-F) and then you edit the dropdown to show that selection, or add another one below that always shows the currently selected range

echo wraith
#

(and a really good application for my pycord-reactive-views thing)

fresh sierra
#

how should i use that ?

#
)
bot.load_extensions("Slashs", recursive=True)
print(bot.extensions)

#

because even if i have 2 files inside the Slashs, it only load 1

#

the recursive doesnt raise an error or return a error either with store = True when there is an error inside a file

echo wraith
#

default contexts should be a set @fresh sierra

sage tendon
#

i dont see the issue

#

your init is not a cog, i hope

#

so it doesnt load it

echo wraith
#

{discord.InteractionContextType.guild}

fresh sierra
#

see it after, it was a stupid thing

fresh sierra
#

the create is not load

sage tendon
#

ah

#

then dont have an init in your cog folder

fresh sierra
#

except if im loading it directly