#Basic Pycord Help

1 messages · Page 61 of 1

fresh sierra
#

yeah the init might be the issue

#

let me try

#

yep it is

#

i will load my cog using something else then

echo wraith
#

__init__ makes it a module

sage tendon
#

also modules should be lowercase

fresh sierra
#

i will use the function that i usally do

echo wraith
#

@fresh sierra The more standard approach I think if you still want the init is to have a sub folder for each extension inside of slashs

fresh sierra
#

i mean i will just no use the recursive

#

and use the fonction that i used in my regular bot

#

i know i shouldnt use init for that purpose but i want to have a file that show always first

#

well i will use asetup, its a really small bot so i will not do anything complicated

latent hare
#

is there an extra incantation i need to get this to run? currently never runs

fresh sierra
#

session_cleanup.start

lofty parcel
#

Are you starting the task?

latent hare
#

that was it, thanks 👍

sage tendon
#

i still wonder how it works behind the scenes ngl

lofty parcel
#

It just creates a separate task on the loop lolz

sage tendon
#

nono

#

the decorator

#

im looking into it rn

lofty parcel
#

Oh

echo wraith
#

It replaces the method with an attribute of type Task I believe

sage tendon
#

yea i had to look at how decorators work at all

echo wraith
#

Oh right

sage tendon
#

i hate decorators i always forget how they work and they seem weird

#

but i love using them for options

cursive swallow
#

Basic Pycord Help

outer niche
deft kestrel
#
import json
import aiohttp
import os

intents = discord.Intents.all()
client = discord.Client(intents=intents)

TOKEN =
GUILD_ID_1 = 
GUILD_ID_2 = 
CHANNEL_ID_GUILD_2 = 
CHANNEL_ID_TO_SEND = 

@client.event
async def on_ready():
    print("Bot is ready and logged in as Forwards admin")

@client.event
async def on_message(message):
    # Ignore messages from the bot itself, other bots, and webhooks
    if message.author.bot or message.webhook_id:
        return

    # Check if message is from the specified servers and channel
    if (message.guild.id == GUILD_ID_1) or (message.guild.id == GUILD_ID_2 and message.channel.id == CHANNEL_ID_GUILD_2):
        # Define API endpoint to get the last 5 messages in the channel
        url = f'https://discord.com/api/v9/channels/{message.channel.id}/messages?limit=5'
        headers = {
            'Authorization': f'Bot {TOKEN}',
            'Content-Type': 'application/json'
        }

        async with aiohttp.ClientSession() as session:
            async with session.get(url, headers=headers) as response:
                if response.status == 200:
                    data = await response.json()

                    # Find the specific message by ID and check for 'message_snapshots'
                    target_message = next((msg for msg in data if msg['id'] == str(message.id)), None)
                    if target_message and 'message_snapshots' in target_message:
                        snapshots = target_message['message_snapshots']
                        file_content = json.dumps({"message_snapshots": snapshots}, indent=4)

                        # Save the snapshot data to a file
                        with open("deleted.json", "w") as f:
                            f.write(file_content)

                        # Send the file to the specified channel
                        send_channel = client.get_channel(CHANNEL_ID_TO_SEND)
                        if send_channel:
                            await send_channel.send(file=discord.File("deleted.json"))
                            os.remove("deleted.json")  # Clean up the file after sending

                        # Delete the original message
                        message_to_delete = await message.channel.fetch_message(target_message['id'])
                        await message_to_delete.delete()
                else:
                    print(f"Failed to fetch messages. Status: {response.status}")

client.run(TOKEN)```
#

currently I need to check message history to get the raw data. is there way to get it on message event ?

sage tendon
#

dont think you can

deft kestrel
#

any other way to auto delete forwarded messages ?

sage tendon
#

wait for 2.7 or see if forwards are already on the repo and use that

#

but 2.7 isnt guaranteed to have it Shrug_3 havent heard much about forwarding here tbh

deft kestrel
sage tendon
#

no, it doesn't

#

also.. why do you fetch the channel history instead of just the message that caused the event?

deft kestrel
#

I will try that. but again it will have to fetch for each message

#

wouldn't that still cause rate limits ?

#

I'll try anyways

sage tendon
#

im pretty sure single message fetching has much higher ratelimits than history

#

also why do you send a json of the deleted message lol

deft kestrel
#

Just for logging

#

what was the message

sage tendon
#

yea but why dont you just put it in clear text

#

and there's zero reason to save it to disk if you're just gonna delete it 5s later

deft kestrel
#

because there are embeds, buttons and more

#

I need to see all

#

and I don't download it. I see it directly on discord by expanding

sage tendon
#

i mean if its a user message, im pretty sure the body of a forwarded message can only contain text / emojis

deft kestrel
#

users can forward bot messages

sage tendon
#

ah

sage tendon
deft kestrel
#

I wouldn't need this if that was not possible. the automod is good to block

sage tendon
#

i think at least lol

#

nvm i think it doesnt actually save to disk nvm

#

well does it work better if you only fetch the single message?

deft kestrel
#

it saves but then sends and then deletes

#

just restarted it

#

lets see

#

it still works but I need to see if it throws 429 error later

#

Thanks for the message id solution. I hope it has high rate limits

#

😭

sage tendon
#

F

deft kestrel
#

I think the entire https://discord.com/api/v9/channels/{message.channel.id}/messages has the same rate limit

#

no matter what we put after that

silk spire
#

Also, the older the message, the lower the limit.

deft kestrel
#

I just need the latest message

#

should be high limit

sage tendon
silk spire
#

Yes?

errant trout
#

if you want the actual ratelimit just read the response headers

sage tendon
deft kestrel
#

I'll set it to print the response header too

silk spire
sage tendon
#

so "i made it up" essentially, good

#

for all i know, message fetches all fall under one combined bucket

#

and i dont see how some requests could count more or less than others, that makes no sense

#

and it doesnt make any sense either
its not like older messages are more costly to retrieve for discord

#

and reading the little documentation discord has on ratelimits, it makes even less sense

silk spire
#

True

silk spire
#

#1130595287078015027 message true for editing tho

shell radish
#

for all we know, they could be using a BST

sage tendon
#

i would not hope so

shell radish
#

probably not but you should get the point

tribal grail
#

Hello, i have 1 question about selection in a View. I'm creating selection boxes with a loop and connecting callback to them. But bot callbacks work only from last selection form, others return "None"
Here is the code which i use

@bot.slash_command()
async def roles_select(ctx: discord.ApplicationContext):

    view = View() #создание View

    # roles_array = [1227979001977634917, 1227979045904449607, 1227979089244065803, 1227978875997257749, 1227978940694659152, 1227978972910846035] # all roles


    max_roles_in_role_selector = 2 

    def divide_array(roles_array, max_roles_in_list):
        for i in range(0, len(roles_array), max_roles_in_list): 
            yield roles_array[i:i + max_roles_in_list]
    
    new_roles_lists_array = list(divide_array(roles_array, max_roles_in_role_selector))

    for new_roles_array in new_roles_lists_array:

        selector_roles_array = []

        for role in new_roles_array:
            selector_roles_array.append(
                discord.SelectOption(
                    label=f"Role {role}"
                )
            )
        
        role_select = Select(
            min_values=1,
            max_values=len(selector_roles_array),
            options=selector_roles_array
        )

        view.add_item(role_select)

    async def RolesSelected(interaction):
        await interaction.response.send_message(f"You selected {role_select.values}")

    for child in view.children:
        child.callback = RolesSelected

    await ctx.send("Select roles", view=view)
sage tendon
#

please split your view from the rest of your code

#

that way you can also control it better

tribal grail
#

What do you mean?

sage tendon
#

you have the entire code for the view inside of the command

#

don't do that, it gets extremely messy and chaotic

#

make a subclass instead and put all the code for the view in there, there's also a guide on views

tribal grail
#

I tried to make subclass

#

But i don't understand how to make all selectors work, not only last

fresh sierra
tribal grail
#

i asked

fresh sierra
# tribal grail i asked

yeah but i mean send ur code with the subclass and ur issue for we can help u understand how it works

sage tendon
#

also i dont get it.. you seem to try to divide the role list, but then you just flatten it into a list again, with the new_roles_list_array line

#

so the result list is the same as the list of all roles if i read it right

tribal grail
little cobalt
#

Can you pls delete that list?

tribal grail
#

ok

little cobalt
#

Thx

tribal grail
#

Maybe you can help me with my problem?

little cobalt
#

The menus got a limit of 25 items

tribal grail
#

I know

#

Because of this i divide the list

little cobalt
#

If you use autocomplete you can use a lot more

tribal grail
#

What is autocomplete?

#

I don't know what is it and how to use it

rugged lodgeBOT
#

Here's the slash autocomplete example.

little cobalt
#

Here is a example for it

little cobalt
sage tendon
#

also lets you display the actual role names properly and not just the IDs (tho you could have done that in the select too)

tribal grail
tribal grail
#

Thank you for advice

sage tendon
#

you can use optionchoices

sage tendon
tribal grail
#

)

#

I know that i can make 5 selectors not in loop and fill them with loop and connect to all of them callbacks with functions, but what if i'll need more selectors?

fresh sierra
tribal grail
#

Because of this i asked a question

fresh sierra
#

why dont u use the role_select ?

tribal grail
#

i didn't understood how to use it

fresh sierra
#
role_select = discord.ui.Select(
            placeholder="placeholder",
          select_type=discord.ComponentType.role_select,
        )

#

just like so

sage tendon
#

but you can also just make it a slash command option if you do it like that

tribal grail
sage tendon
#

not really
discord.Role
thats it
and then jsut type the role name

tribal grail
sage tendon
#

i dont think you can combine those

#

choices with a select type, but not sure

fresh sierra
#

remove the option and th max values since you want the user to select as much role as he want

tribal grail
#

but if i limit user from getting all roles?

fresh sierra
#

because rn u just limit the user with the number of choice

#

which mean no limit

sage tendon
#

you HAVE to check the roles tho

#

else the bot could give people admin roles if your role setup is wrong

fresh sierra
#

he wants to do an addrole command ?

sage tendon
#

i think lol

#

idk

fresh sierra
#

wierd way to do an addrole command

sage tendon
#

ok question
what is your goal with this command / select stuff

tribal grail
sage tendon
#

use onboarding..

fresh sierra
tribal grail
#

Yes

sage tendon
#

why dont you use discord's onboarding

#

its literally the exact thing for this scenario

fresh sierra
#

because to enable that you need to have 5 text channel enable for everyone

#

and thats stupid!

sage tendon
#

if your server doesnt even have 5 text channels its not really worth being a server lol

fresh sierra
tribal grail
sage tendon
fresh sierra
#

i have general, support, command, image and that all

sage tendon
#

i just made 4 hidden channels that no one can see with some trickery

#

that way i can bypass that :)

frail basin
#

If you have a "verified" role, the @everyone role can only see a single channel

frail basin
sage tendon
#

I have a role everyone gets
that role hides the 4 "fake" text channels that @ everyone can text in
but no one ever sees them because everyone has that role

fresh sierra
sage tendon
#

no, the channels just become hidden once they get my autorole

#

because the autorole has denied permissions for that channel

fresh sierra
#

i see

#

but seriously why did discord add this stupid rule

fresh sierra
#

the on_callback is not trigger, any idea ?

class PrizeModal(discord.ui.Modal):
    def __init__(self):
        super().__init__(title="Modifier le Prix de la Tombola")
        description = "\n".join([f"{i}. " for i in range(1, 101)])
        self.add_item(
            discord.ui.InputText(
                label="Description du Prix",
                value=description,
                style=discord.InputTextStyle.long,
            )
        )

    async def on_callback(self, interaction: discord.Interaction):
        print("ok")
#

and no error

sage tendon
#

isnt it just callback

fresh sierra
sage tendon
#

why is your description 100 newlines

fresh sierra
# sage tendon why is your description 100 newlines

a client ask a tombola bot (french name idk in english), so there is 100 numbers where she put the price that she wants for some number, then the member choose some number and they get the price of the number

#

how can i return some value from a modal ?, like i use the modal, and the on_callback return some value inside the first class

sage tendon
#

is there like modal.wait like for views

fresh sierra
#

i would like to do something like so :

    async def prize_callback(self, interaction: discord.Interaction):
        modal = PrizeModal()
        await interaction.response.send_modal()
        await modal.wait()
        self.prize = get value return in my modal
sage tendon
#

just set an attribute in the modal class and access it with modal.attribute

round heart
#

meh. Okay, so from a button response, I've tried

self.message.delete()
interaction.message.delete()
interaction.delete_original_message()
interaction.delete_original_response()

None of these deletes the message the View is attached to (first one is unknown message, other two are unknown webhook). What incantation am I missing?

sage tendon
#

try self.message

round heart
#

Nope, that fails too

sage tendon
#

as?

round heart
#

Unknown message

sage tendon
#

is it ephemeral?

round heart
#

Yes

sage tendon
#

give up /hj

#

ephemeral messages are very weird to delete

round heart
#

Nah, I've def deleted ephemeral messages before.

sage tendon
#

yea but its weird as you can see

fresh sierra
fresh sierra
sage tendon
#

set an attribute in the modal, which you then access in the view to set an attribute in the view, which you then access in your command

round heart
#

Hm. Nelo suggests delete_original_response should work here. #1132206148309749830 message

fresh sierra
#

because i think to delete a message you need to have the permission to see the message inside the channel

fresh sierra
#

im not sure about that but i will like its logical

round heart
#

The bot is fully integrated. Shouldn't have anythign to do with perms

fresh sierra
round heart
#

Yes, of course. Outside of webhooks, are there bots that don't have access to channels it sends messages to...?

fresh sierra
fresh sierra
round heart
#

interaction.followup was populated, but deleting that returns 404, as well.

fresh sierra
round heart
#

Not directly on this button. The original View spawns Modals that do defer as a 'no op' response, but don't think that should affect anything here.

fresh sierra
round heart
#

It sends a message with a View. The View has various buttons, etc etc. But it has a Submit. When the person clicks that Submit, I want the parent Message to be deleted. I know it can be done, but there's something funky here.

#

Ah-hah #1132206148309749830 message

You have to respond to the interaction first.

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

I suppose the reason why it worked in other code is because I was sending a followup (which responds to the interaction) whereas my button's intention was to delete the ephemeral and then send a seperate public message.

silk spire
#

Ephemeral messages can only be accessed from an interaction so yes

And ..._original_response only work after responding

fresh sierra
#

(since you first sending a modal, it answer to the interaction so the other one is a followup

round heart
fresh sierra
#

aaaa no because its ephemeral you cant if i understood

silk spire
#

Yup

sage tendon
#

its not a message yet if you never ever responded tho (?)

fresh sierra
round heart
#

Except it clearly is, it has an ID and everything.

ivory beacon
#

can i use jishaku with PyCord ?

sage tendon
#

sure

ivory beacon
# sage tendon sure
discord.errors.ExtensionFailed: Extension 'jishaku' raised an error: AttributeError: module 'discord.ui' has no attribute 'TextInput'
sage tendon
#

uhh dont remember how to fix that exactly lol
but i do know i used it on pycord

fresh sierra
#

and dpy is TextInput

#

might be the issue

#

maybe do a fork

ivory beacon
#

i found
2.3.2 should still work but yeah anything after that is targeted for dpy 2.0 from this server

sage tendon
#

no

radiant grotto
#

just installed pycord, run the same code from the quickstart section of the website to test it works, and i get this.

tried uninstalling and reinstalled with pip, verified i had discord.py uninstalled aswell and no conflicting libraries. when i try and install audioop i get the message it doesnt exist.

any ideas?

lofty parcel
radiant grotto
#

ah sweet, cheers 🙂

silk spire
#

or don't use 3.13 yet, but wait for Pycord 2.7

sage tendon
#

or install audioop-lts

echo wraith
#

.tag audioop

sly karmaBOT
#

Pycord 2.6.1 works with Python 3.13, but you may need to pip install audioop-lts for voice features until Pycord 2.7 includes a Python-based audioop implementation.

sudden canyon
#

why when i create a slash command it is working for once but the command get unregistered right after someone or i use it

sage tendon
#

do you use bot.sync_commands anywhere

sudden canyon
#

i tried both using it or not but both doesn't works

#

and i put it in on_ready()

#

i mean it didn't worked first time so i use bot.sync_commands() and still doesn't works

sage tendon
#

remove it wherever you have it, its not needed

sudden canyon
#

ok but it still doesn't work at all

#

i tried making a simple greet command it didn't worked

sage tendon
#

so it disappears from your command list when you use it?

sudden canyon
#

yeah it appear but when i use it it get removed from list

#

like it was 1 time use

sage tendon
#

but it works? or does it not do anything

sudden canyon
#

it works

sage tendon
#

show your main bot file and the code of the command if its somewhere else

sudden canyon
#
import discord

bot = discord.Bot()

@bot.slash_command(name="hello", description="say hello!")
async def hello(ctx):
    await ctx.respond("hello world")

@bot.event
async def on_ready():
    print("hello world")

bot.run("token here")

sage tendon
#

does it happen to someone else too?

#

also, make very sure your bot isnt running twice

sudden canyon
#

yeah he used it and i couldn't use it after

sage tendon
#

and neither could he?

sudden canyon
#

it's just when someone use it the command get removed from list

#

for everyone

sage tendon
#

yea i think your bot is running twice

#

reset your token to make sure

sudden canyon
#

wdym it run twice

#

is it a problem if i have multiple bot codes?

sage tendon
#

as in i think you have 2 files running the bot with the same token

sudden canyon
#

yeah i use multiple files but not for the same slash command

#

each for different purposes

#

i don't have any slash commands

#

but they works fine

sage tendon
#

No, what i think is that bot token is logged in twice at discord

#

once with the slash command and once without

#

just reset your token and try if it still happens

sudden canyon
#

ok i'll try

sage tendon
sudden canyon
sage tendon
#

how do you start your bot

sudden canyon
#

in my server i run all the bot codes within a single python file, i use os.system() then run all the python codes for my bot running "python example.py & python example2.py" and etc, i have like 5 codes and the other is working fine but the slash command

sage tendon
#

...no

#

that doesnt work

#

at all

#

why do you have multiple files?

sudden canyon
#

for me this is easier to have multiple files for single purpose each

sage tendon
#

then use cogs

#

you are probably running the bot in every file right?

sudden canyon
#

ye

sage tendon
#

yea, thats the issue

sudden canyon
#

fine i'll read it

deft bronze
#

Whenever i lose my internet connection, the bot never goes online again until i restart it manually, any way to solve this?

#

In running the bot on a docker container

round heart
#

.rtfm timeout

round heart
#

(Anyone know if there's an effective max timeout for a View? For some reason 15 mins is in my head but I don't know if that can be overridden to be more)

round heart
#

Maybe it's ephemeral interactions. I remember having a weird issue with the Paginator - been a while, though

fresh sierra
fresh sierra
rugged lodgeBOT
echo wraith
#

-remindme 2h this thing

lofty vaultBOT
#

Set a reminder in 2 hours from now (<t:1730970284:f>)
View reminders with the reminders command

fresh sierra
#

How does work the this thing ? For then it give u thing

torn barn
#

huh

fresh sierra
# echo wraith wdym

Nah I just tough for a moment that the view was related to the previous message

#

I just need more sleep

lofty vaultBOT
#

Reminder for @echo wraith

Reminder from YAGPDB

this thing

echo wraith
#

Done

fresh sierra
echo wraith
fresh sierra
echo wraith
echo wraith
keen relic
#

can we achieve auto-reloading of cogs whenever we create, modify, or delete a file

keen relic
# little cobalt Why?

auto-reloading could speed up our development workflow by instantly reflecting changes without manual reloads

little cobalt
#

Can you show the pip list?

#

And how did you define the bot?

#

?

keen relic
#

py-cord 2.6.1

little cobalt
#

Why did you delete it?

keen relic
#

sorry i delete wrong

#

one

#
  File "/home/container/.local/lib/python3.11/site-packages/discord/cog.py", line 796, in _load_from_module_spec
    setup(self)
  File "/home/container/cogs/yt.py", line 111, in setup
    bot.add_cog(YouTubeNotifier(bot))
  File "/home/container/.local/lib/python3.11/site-packages/discord/cog.py", line 666, in add_cog
    cog = cog._inject(self)
          ^^^^^^^^^^^^^^^^^
  File "/home/container/.local/lib/python3.11/site-packages/discord/cog.py", line 552, in _inject
    bot.bridge_commands.append(command)
    ^^^^^^^^^^^^^^^^^^^
AttributeError: 'Bot' object has no attribute 'bridge_commands'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "/home/container/index.py", line 13, in <module>
    bot.load_extensions('cogs')
  File "/home/container/.local/lib/python3.11/site-packages/discord/cog.py", line 1025, in load_extensions
    loaded = self.load_extension(
             ^^^^^^^^^^^^^^^^^^^^
  File "/home/container/.local/lib/python3.11/site-packages/discord/cog.py", line 933, in load_extension
    loaded = self.load_extension(
             ^^^^^^^^^^^^^^^^^^^^
  File "/home/container/.local/lib/python3.11/site-packages/discord/cog.py", line 918, in load_extension
    self._load_from_module_spec(spec, name)
  File "/home/container/.local/lib/python3.11/site-packages/discord/cog.py", line 801, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.errors.ExtensionFailed: Extension 'cogs.yt' raised an error: AttributeError: 'Bot' object has no attribute 'bridge_commands'```
little cobalt
#

And the bot?

keen relic
#

@little cobalt

#
Traceback (most recent call last):
  File "/usr/local/lib/python3.10/dist-packages/discord/cog.py", line 796, in _load_from_module_spec
    setup(self)
  File "/var/lib/pterodactyl/volumes/95e8e434-498b-4428-9c43-bcb6ef1ed159/cogs/yt.py", line 111, in setup
    bot.add_cog(YouTubeNotifier(bot))
  File "/usr/local/lib/python3.10/dist-packages/discord/cog.py", line 666, in add_cog
    cog = cog._inject(self)
  File "/usr/local/lib/python3.10/dist-packages/discord/cog.py", line 552, in _inject
    bot.bridge_commands.append(command)
AttributeError: 'Bot' object has no attribute 'bridge_commands'

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

Traceback (most recent call last):
  File "/var/lib/pterodactyl/volumes/95e8e434-498b-4428-9c43-bcb6ef1ed159/index.py", line 13, in <module>
    bot.load_extensions('cogs')
  File "/usr/local/lib/python3.10/dist-packages/discord/cog.py", line 1025, in load_extensions
    loaded = self.load_extension(
  File "/usr/local/lib/python3.10/dist-packages/discord/cog.py", line 933, in load_extension
    loaded = self.load_extension(
  File "/usr/local/lib/python3.10/dist-packages/discord/cog.py", line 918, in load_extension
    self._load_from_module_spec(spec, name)
  File "/usr/local/lib/python3.10/dist-packages/discord/cog.py", line 801, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.errors.ExtensionFailed: Extension 'cogs.yt' raised an error: AttributeError: 'Bot' object has no attribute 'bridge_commands'
root@xesjhcn9g5:/var/lib/pterodactyl/volumes/95e8e434-498b-4428-9c43-bcb6ef1ed159# ```
little cobalt
#

do you use discord.Bot?

#

Or commands.Bot?

keen relic
#

thx

#
from discord.ext import commands
from dotenv import load_dotenv
import os
load_dotenv()

TOKEN = os.getenv('DISCORD_TOKEN')

intents = discord.Intents.all()

bot = commands.Bot(command_prefix='!', intents=intents)

bot.load_extensions('cogs')

bot.run(TOKEN)
little cobalt
#

You have to change it to bridge.Bot

keen relic
little cobalt
#

You could write a scrips which checks for changes at the files

keen relic
#

i have this code by chatgpt ```import discord
from discord.ext import commands
from dotenv import load_dotenv
import os
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import time

Load environment variables

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')

Set up bot intents

intents = discord.Intents.all()
bot = commands.Bot(command_prefix='!', intents=intents)

Load initial cogs

bot.load_extensions('cogs')

FileSystemEventHandler for monitoring changes in cogs folder

class CogReloadHandler(FileSystemEventHandler):
def on_modified(self, event):
if event.src_path.endswith('.py'):
cog_name = os.path.basename(event.src_path)[:-3] # Remove .py to get the cog name
try:
bot.reload_extension(f'cogs.{cog_name}')
print(f"Reloaded cog: {cog_name}")
except commands.ExtensionNotLoaded:
try:
bot.load_extension(f'cogs.{cog_name}')
print(f"Loaded new cog: {cog_name}")
except Exception as e:
print(f"Error loading new cog {cog_name}: {e}")
except Exception as e:
print(f"Error reloading cog {cog_name}: {e}")

Set up the observer to watch the cogs directory

observer = Observer()
observer.schedule(CogReloadHandler(), path='./cogs', recursive=False)
observer.start()

Define an event to confirm the bot is ready

@bot.event
async def on_ready():
print(f'Logged in as {bot.user} (ID: {bot.user.id})')
print('------')

Run the bot

try:
bot.run(TOKEN)
finally:
observer.stop()
observer.join()

little cobalt
#

You would have to change some stuff if you want to do the reload stuff

sage tendon
#

besides most IDEs have a feature that let you auto-run a command on save

#

There's no point to overcomplicate it because reloading cogs is still whacky

errant trout
#

eh

#

if you want autoreload just make a task that checks if a cog file was updated every few secons

#

watchdog or wtv might work but idk if it's blocking

wary lava
#

can pycord do user commands?

sage tendon
#

user commands as well as user apps

wary lava
lofty parcel
#

.rtfm user_command

sage tendon
#

well, i take it you want a user app and not a user command?

#

because thats the thing thats new

lofty parcel
#

Or maybe they do want user commands lol

sage tendon
#

100% of people so far who asked for user command wanted user apps

lofty parcel
#

True tbh

#

It's kinda confusing

sage tendon
#

not at all

#

people just need to learn the difference

tidal estuary
#

I'm having difficulty playing audio in a stage, even when properly not suppressed. This guy appears to have had the same issue I am seeing. Is there a known trick/complication here? The same code path seems to work in a non-stage vc

#1212491741018456134 message

sage tendon
#

did their solution not work for you?

echo wraith
deft bronze
#

Whenever i lose my internet connection, the bot never goes online again until i restart it manually, any way to solve this?
In running the bot on a docker container

short linden
deft bronze
short linden
#

Well, I'm assuming that the loss of connection throws an error outside of the async event loop.

deft bronze
#

Yeah, maybe, but doesn't seem like a great option

#

i'll wait for other alternative maybe

#

if i can't find any i may go that way

short linden
#

I'm not sure if there is a ready-made option for this

deft bronze
#

I don't think so, but maybe someone has a better alternative

floral ice
#

how can i specify allowed command context per command?

fresh sierra
#

@contexts

floral ice
#

thx

sage tendon
jolly tundra
#

Host it somewhere like squarecloud or some other service. It's not that expensive

echo wraith
#

.tag vps

sly karmaBOT
sage tendon
#

pythonanywhere also works but has limited CPU time, never tested a discord bot with it, might work with limited intents and little command usage, but thats really a last resort

frail basin
#

Id imagine they have the same IP for many users 🤔

sage tendon
#

and thats a problem why

lapis dock
#

You have to share IP based rate limits and bans. That's why replit was bad for discord bots. People kept having their bots be blocked because of someone else

sage tendon
#

Yea, but on python anywhere, if you have a bot that is used any much, you'll be out of luck either way due to the cpu time limits

#

I think it's like a minute of CPU time a day which you can make work, but it's not much

sage tendon
short linden
short linden
maiden bloom
#

Will this slash command decorator still allow server owners to run the command even if they aren't explicitly given admin permissions?
@has_guild_permissions(administrator=True)

sage tendon
#

why dont you try it out

sage tendon
#

also for slash commands you should consider using @discord.default_permissions

lofty parcel
#

Server owners have all permissions

devout linden
#

i'm trying to use Option as a type annotation to a slash_command but every linter and type checker i have hates it, in-line or as a variable. i tried searching for the various output strings here but i can't find anything that i think would apply. how do you folks typically handle this sort of static checker "warning"?

lapis dock
devout linden
#

working through the docs just exchanges one error for another.

lofty parcel
#

Yes rhat happens when you typehint Option

#

Sometimes python doesnt like it

#

If you really wanna typehint Option, you can add # type: ignore

devout linden
#

i'd like to type hint it to input_type, that'd be awesome.

sage tendon
#

use the decorator, then you can use regular typehints accordingly in the function signature

echo wraith
hybrid fossil
#

Hi, quick question:
Unless you store the connection time of a user in a vocal channel in a database, there's no way to know the exact time they joined, right?

hybrid fossil
stoic hazel
#
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In 9.options.1: Required options must be placed before non-required options

why does this sometimes appear and sometimes not? i literally did not change the code between 2 different runs, first time it worked fine second time i got this

echo wraith
#

.tag paste

sly karmaBOT
#

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

stoic hazel
#

it's multiple commands in a cog

#

i don't know which one is the issue

fresh sierra
stoic hazel
fresh sierra
#

async def command(self, ctx, test= None, test)

#

but the test = None should be the last option

echo wraith
stoic hazel
#

the thing wasn't scrolling to show the button

echo wraith
#

save paste at the bottom

#

yeah exactly

stoic hazel
stoic hazel
echo wraith
stoic hazel
#

except it isn't happening every time

echo wraith
# stoic hazel except it isn't happening every time
    @discord.option(
        "essential_exefs",
        discord.Attachment,
        required=False,
        description="...the essential.exefs of the console to soap",
    )
    @discord.option(
        "console_json",
        discord.Attachment,
        required=False,
        description="...the .json of the console to soap",
    )
    @discord.option(
        "serial",
        str,
        description="the serial on the sticker, use 'skip' to skip the check (only skip if u smart)",
        max_length=11,
    )
    async def doasoap(
        self,
        ctx: discord.ApplicationContext,
        serial: str,
        essential_exefs: discord.Attachment,
        console_json: discord.Attachment,
    ):
stoic hazel
#

i've tried redoing each command (excluding the actual code, i just used a ctx.respond) outside of the cog but it doesn't replicate the error

echo wraith
#

I moved serial at the start

#

try with that

stoic hazel
#

was i not supposed to move the decorator with it when i tried that

stoic hazel
#

i tried that on the similar command farther down too but still nothing

echo wraith
stoic hazel
#

not loading this cog gets rid of the error permanently so i don't think the problem is somewhere else

echo wraith
#

And see of you still have it

#

And send here the error too

#

I want to see the number in the error

stoic hazel
#

still errors

#
Ignoring exception in on_connect
Traceback (most recent call last):
  File "/home/crudefern/frank-bot/.venv/lib/python3.13/site-packages/discord/client.py", line 412, in _run_event
    await coro(*args, **kwargs)
  File "/home/crudefern/frank-bot/.venv/lib/python3.13/site-packages/discord/bot.py", line 1214, in on_connect
    await self.sync_commands()
  File "/home/crudefern/frank-bot/.venv/lib/python3.13/site-packages/discord/bot.py", line 742, in sync_commands
    registered_commands = await self.register_commands(
                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        global_commands, method=method, force=force, delete_existing=delete_existing
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    )
    ^
  File "/home/crudefern/frank-bot/.venv/lib/python3.13/site-packages/discord/bot.py", line 606, in register_commands
    registered = await register("bulk", data, _log=False)
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/crudefern/frank-bot/.venv/lib/python3.13/site-packages/discord/http.py", line 374, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In 2.options.2: Required options must be placed before non-required options
``` this is the whole traceback
sage tendon
#

show your code.

sage tendon
#

comment the commands out one by one to see which one it is

echo wraith
#

Or enable debug logging and show the output

stoic hazel
#

debug logging?

echo wraith
#

.tag logging

sly karmaBOT
echo wraith
#

Set it to debug, not info tho

stoic hazel
#

i have found the problem

#

a typo

#
    @discord.option("donor_exefs_name", discord.Attachment, required=False)
    @discord.option(
        "note",
        str,
        required=False,
        description="any notes you want attached to the donor",
    )
    async def uploaddonortodb(
        self,
        ctx: discord.ApplicationContext,
        note: str,
        donor_json_file: discord.Attachment,
        donor_exefs_file: discord.Attachment,
    ):

decorator says exefs_name while function says exefs_file

#

fixing that made the error go away, thanks!

stoic hazel
#

i found it by looking at the json the debug log spat out in one of the PUT lines

tidal estuary
#

If anyone has tried to play audio via ffmpeg on a stage you've probably noticed there's funny business. Anyone find a workaround that is reliable?

lapis torrent
#

Does anyone know the fix for this issue to get a bot to join a stage? Seems like OP fixed it but didn't elaborate

dusk flume
lapis torrent
lofty parcel
lapis torrent
lofty parcel
#

A stage channel isn't a member object.

lapis torrent
#

Is anyone familiar with this error when listening to voice channel audio:

Traceback (most recent call last):
  File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner
    self.run()
  File "/usr/lib/python3.8/threading.py", line 870, in run
    self._target(*self._args, **self._kwargs)
  File "/home/ubuntu/project/lib/python3.8/site-packages/discord/voice_client.py", line 863, in recv_audio
    self.unpack_audio(data)
  File "/home/ubuntu/project/lib/python3.8/site-packages/discord/voice_client.py", line 740, in unpack_audio
    data = RawData(data, self)
  File "/home/ubuntu/project/lib/python3.8/site-packages/discord/sinks/core.py", line 115, in __init__
    self.decrypted_data = getattr(self.client, f"_decrypt_{self.client.mode}")(
  File "/home/ubuntu/project/lib/python3.8/site-packages/discord/voice_client.py", line 611, in _decrypt_xsalsa20_poly1305_lite
    return self.strip_header_ext(box.decrypt(bytes(data), bytes(nonce)))
  File "/home/ubuntu/project/lib/python3.8/site-packages/nacl/secret.py", line 149, in decrypt
    plaintext = nacl.bindings.crypto_secretbox_open(
  File "/home/ubuntu/project/lib/python3.8/site-packages/nacl/bindings/crypto_secretbox.py", line 79, in crypto_secretbox_open
    ensure(
  File "/home/ubuntu/project/lib/python3.8/site-packages/nacl/exceptions.py", line 88, in ensure
    raise raising(*args)
nacl.exceptions.CryptoError: Decryption failed. Ciphertext failed verification

I see an open but unresolved github issue about it: https://github.com/Pycord-Development/pycord/issues/2033

GitHub

Summary I'm using a bot based on pycord during long conversations on discord. Sometimes (it occur very rarely tho) a nacl.exceptions.CryptoError is raised, and i have no way to handle it other ...

sage tendon
#

don't use python 3.8..

#

3.8 is EOL and not even supported by Pycord anymore for all I know

#

@lapis torrent

undone merlin
#

hello

lapis dock
#

Is there something specific you can't find, or do you just want to find everything related to your example?

undone merlin
#

it would be really helpful

flat wind
# undone merlin hello

for your example, search for Embed, Button, View, and ApplicationContext. These are all you need.

If you need to create an embed, search on what are the methods and parameters of the Embed object. For that, search for Embed and click on the result discord.Embed

undone merlin
#

@bot.slash_commands(name="test", description="Testing)
async def test(ctx: discord.ApplicationContext)
await ctx.respond("testing)

but what do I do next to make it so that I can use a / command and then the bot asks me the channel where I want to send it

undone merlin
flat wind
undone merlin
#

like u see how it's asking me to fill the boxes

lapis dock
#

Those are options
You can search discord.Option

undone merlin
#

i literally can not find anything I want on the documentation page

#

wait

#

is it this

flat wind
#

this is a reference of the type of the input / output you have to pass

flat wind
lapis dock
#

There is an example at the bottom of the options section. Basically you type hint your args with Option
Or you could use the decorator like this
@discord.option(arg_name, input_type=type, **kwargs)

undone merlin
#

so if I want a channel ID

flat wind
#

if you are asking for a channel in your option, the member will give you a channel, so the type of a channel is abc.GuildChannel, next (from the documentation) you will find the id attribute (depending if it is a TextChannel, StageChannel....)

sage tendon
#

you probably wanna limit the option to discord.TextChannel

unkempt cipher
#

do you even know python at all..

little cobalt
unkempt cipher
#

naja wir setzen grundwissen schon vorraus.. eigentlich könnn wir sagen "fick dich" und gut is

flat wind
#

btw, just a question for me. But is there a way to test a specific version of pycord ? like a specific PR ? I wanna try the Plun's PR about the SKU and subscriptions (#2564)

sage tendon
flat wind
unkempt cipher
flat wind
# unkempt cipher

yes, looks good.
Will it be in the 2.7 ? The PR has not been merged

unkempt cipher
flat wind
#

if I edit some options of slash commands, or command names. when I do a sync_commands, will it update it or do I need to add the force argument ?

little cobalt
sage tendon
#

yea, don't use sync commands

little cobalt
#

well you can use it

flat wind
sage tendon
#

from experience it eats through the command ratelimit faster than you can look

#

if you really don't wanna restart you can sync the commands but don't force it

flat wind
#

that's only when needed

sage tendon
#

I just kinda wonder how you change a command without restarting the bot

#

or do you reload the cog

fresh sierra
#

Hello, recently my not run a lot into blocking code

#

When I’m looking at the trace back it’s only some pycord thing that’s I don’t understand, any idea ?

#

this is the kind of thing im getting

    bot.run(BOT_TOKEN)

  File "/home/container/.local/lib/python3.11/site-packages/discord/client.py", line 772, in run
    loop.run_forever()

  File "/usr/local/lib/python3.11/asyncio/base_events.py", line 608, in run_forever
    self._run_once()

  File "/usr/local/lib/python3.11/asyncio/base_events.py", line 1936, in _run_once
    handle._run()

  File "/usr/local/lib/python3.11/asyncio/events.py", line 84, in _run
    self._context.run(self._callback, *self._args)

  File "/usr/local/lib/python3.11/asyncio/selector_events.py", line 956, in _read_ready
    self._read_ready_cb()

  File "/usr/local/lib/python3.11/asyncio/selector_events.py", line 988, in _read_ready__get_buffer
    self._protocol.buffer_updated(nbytes)

  File "/usr/local/lib/python3.11/asyncio/sslproto.py", line 439, in buffer_updated
    self._do_handshake()

  File "/usr/local/lib/python3.11/asyncio/sslproto.py", line 560, in _do_handshake
    self._sslobj.do_handshake()

  File "/usr/local/lib/python3.11/ssl.py", line 979, in do_handshake
    self._sslobj.do_handshake()
torn barn
#

This looks like some asyncio error

fresh sierra
#

yeah but i dont really understand why im getting this

#

and why does it block my code

torn barn
#

well, it is retaining the loop

#

maybe making a asyncio.run call instead could fix it

#

instead of doing loop.run_forever which

#

(by the library side)

#

Try using asyncio.run(client.start(TOKEN)) instead of client.run

torn barn
#

As client.run

fresh sierra
#

well, it also block the loop as i remember

#

or something else

torn barn
#

the bot.run call retains the loop until the bot closes

fresh sierra
#

i dont remember why i was not using it,

torn barn
#

that is why anything after that that involves the bot (i.e.: command creating) are ignored

fresh sierra
#

but anyways everytime im using client.start it doesnt work

torn barn
#

Could you show the code you have tried?

fresh sierra
#

im not the only one but the bot just never start and raise some error

torn barn
fresh sierra
#

but let me do it again

torn barn
#

Do something like:

import asyncio

async def runner():
    try:
        await bot.start(TOKEN):
    finally:
        if not bot.is_closed():
            await bot.close()

asyncio.run(runner())
fresh sierra
torn barn
#

What is the output?

fresh sierra
# torn barn What is the output?

RuntimeError: Task <Task pending name='Task-1' coro=<runner() running at /home/container/main.py:24> cb=[_run_until_complete_cb() at /usr/local/lib/python3.11/asyncio/base_events.py:181]> got Future <Future pending cb=[_chain_future.<locals>._call_check_cancel() at /usr/local/lib/python3.11/asyncio/futures.py:387]> attached to a different loop

#

when im using the rie

sage tendon
#

as always, what did you change since it last worked

fresh sierra
sage tendon
#

he assumes

fresh sierra
#

because he pasted it 5min ago

torn barn
#

attached to a different loop

sage tendon
#

if you dont wanna tell us then you cant expect good help

fresh sierra
#

so ofc the only thing that changed is what he asked me to add

torn barn
#

ive sent it here lol #1246104091780710471 message

sage tendon
#

No
I was asking what you changed BEFORE that error appeared

fresh sierra
sage tendon
#

yea but you did something before you started getting that error

fresh sierra
echo wraith
#

is it possible to disable link buttons ?

lofty parcel
#

Nope

shell radish
#

fake it with a link emoji and a regular button

lofty parcel
#

Kek can you do that?

echo wraith
shell radish
#

it's disabled

silk spire
#

Pretty sure you can disable a link button

fresh sierra
silk spire
#

Did you try it

#

Because it does work

fresh sierra
#

wtf it does

silk spire
#
await ctx.send(view=discord.ui.View().add_item(discord.ui.Button(url="https://google.com", label="lol", disabled=True)))
fresh sierra
#

dark, i will be always doubting you from now

silk spire
#

What a waste of lines /s

lofty parcel
#

I thought you couldnt

fresh sierra
shell radish
lapis dock
#

can you still click it?

silk spire
#

Can you click a disabled component?

sage tendon
#

no

lapis dock
#

No, it just does not make sense to disable a link button, its not like the link is not available anymore

fresh sierra
silk spire
#

You can't click it tho

echo wraith
#

WAIT YOU CAN

#

OMG

fresh sierra
#

we should make an announement for that revolutionary thing

sage tendon
#

let me tell you about editing the button out instead

sage tendon
#

remove the button from the view

fresh sierra
#

to do what im a bit lost

sage tendon
#

make people unable to click it

fresh sierra
sage tendon
#

thought you couldnt disable link buttons

fresh sierra
vital bramble
#
    @discord.ui.button(label="Cancel", style=discord.ButtonStyle.danger)
    async def cancel(self, interaction: discord.Interaction, button: discord.ui.Button):
        await interaction.delete_original_response()
        await interaction.response.send_message("❌ | Cancelled.", ephemeral=True)

Do you see any problems with this or is it fine?

#

Like can I respond after deleting the original response?
I always get confused about what the original response is...

sage tendon
#

try it and see if it works

#

but you got the argument order the wrong way around

#

its button then interaction

vital bramble
#

oh yeah, totally forgot I was using discord.py for this project lol

#

sorry xD

errant trout
#

(if it does then screw me i guess but it shouldn't?)

vital bramble
errant trout
#

if you want to delete the message, you can defer > delete

#

the final response.send_message will still send

#

ok not send_message

#

since you deferred you need to followup

vital bramble
errant trout
#

(just use interaction.respond it's easier)

#

yes

#

my personal preference for this would be edit content and view=None, but defer > delete > followup does work

vital bramble
errant trout
#

isee

#

then whatever method they use for sending followups

vital bramble
#

yeah, thx 🙂

fresh sierra
#

Hello, i just run into an issue where my bot simply stop answering, every command/interaction just give me some unknow interaction, i dont have any error in my log etc. It happened to me like 2 times so i dont really have an idea of what should i look like

#

my other bot seems to work without issue,

#

(and they have the same code)

errant trout
#

you sure it isn't your server

fresh sierra
#

im using pterodactyl and i dont see anything problematic

errant trout
#

Maybe switch logging mode to DEBUG

#

Idk not a lot to go off of

fresh sierra
#

i mean i got it 2 times in a while so if there is no evident thing i might let it like so

arctic oar
#

Do fetch calls like fetch_user automatically get cached?

slender lantern
arctic oar
#

I'm confused on how I'm able to cache members

#

Because there is .get_or_fetch_user

#
async def get_or_fetch_user(self, id: int, /) -> User | None:
    user = self.get_user(id)
    print("User", user)
    if user is None:
      print("Fetching user")
      user = await self.fetch_user(id)
      return user
#

I overrided the default function with this, is there a way I can access the cache? And manually add every user from the fetch call to the cache

lofty parcel
#

There's store_user (bot._connection.store_user)

#

I dunno why they don't get cached though, thought they did for some reason.

arctic oar
#

That works thanks

#

Also, seems like the cache is persistent right?

#

There's no TTL I believe

errant trout
#

user cache is yes

deft bronze
#

Now can i send a Discord.Attachment as image in a message?

#

Without the ugly url

fresh sierra
#

Using the discord.File

deft bronze
flat wind
round heart
autumn minnow
#

Anyone here in the know about anything that might help me check if a user is currently timed out? My brain is not braining at the moment and scouring the docs didn't really help me. Something along the lines of member.timed_out_until or something that just returns a timestamp or None ig.?

rugged lodgeBOT
sage tendon
autumn minnow
#

Thanks, apparently I really am blind LULW

sage tendon
#

wait i thought you asked for a duration

#

nvm

autumn minnow
#

No

echo wraith
autumn minnow
#

I just need a status of whether they are timed out or not, I don't care for the duration really

#

Thanks to both of you

echo wraith
#

When a message contains an invite link like this one discord.gg/pycord , and the message is accessed by a bot, does the message object contain information about it containing this invite, or is that purely client side ?

fresh sierra
#

i would say its client side like for any mention

errant trout
floral ice
#

can i somehow detect when my bot gets mentioned?

echo wraith
floral ice
echo wraith
#

If you encouter a specific issue using events feel free to share it here

floral ice
#

okay, i will try the on_message

#

do i have to specify server where to listen or it just auto listens everywhere and just works?

echo wraith
lapis dock
floral ice
#

ah nice thx

eternal kite
#

how do i get the full command used by users? including argument values

errant trout
eternal kite
#

thx

eternal kite
#

how do i create a permanent button that will work even after restarting the bot?

rugged lodgeBOT
#

Here's the persistent example.

torn barn
#

Use that example ^

fresh sierra
#

at the start of my bot i got this :
2024-11-14 17:19:50 [WARNING] : Can't keep up, shard ID 3 websocket is 41.3s behind.

is it normal ?
i cant put debug mode there is too much log for me too see anything

torn barn
#

That usually happens when there is blocking code somewhere

fresh sierra
torn barn
#

And for debug logging, you can filter out the logs you receive, usually the ones that you should not care are on discord.state

little cobalt
torn barn
fresh sierra
torn barn
little cobalt
#

How do you open them?

torn barn
#

You should open it either on another thread or run it on another executor

fresh sierra
fresh sierra
#

Everything is async and not blocking

torn barn
#

with open is blocking

fresh sierra
#

(I mean I do have sometime blocking code but there are from asyncio session

torn barn
fresh sierra
#

And no blocking code is detected before

#

Using the rie

sage tendon
#

so it detects every single variable assignment?

#

doubt

fresh sierra
torn barn
#

you surely have blocking code somewhere

#

because that warning is only sent when the event loop is blocked for too long

#

(e.g. blocking code)

fresh sierra
#

yeah but only for that shard, and it doesnt also appear everytime

torn barn
#

it does not need to be from your code but can also come from any library you use

fresh sierra
#

cant it be cache etc before the cog are loaded ?

fresh sierra
#

basically my detector check if some code cant be executed in the bot.loop

#

like it will try to asyncio.sleep(0) and then check the before and after, and it will show me if the code took more than 0.5s to execute which mean a code was blocking

torn barn
#

you should not depend on that

fresh sierra
#

but this process only start after the loading of the code so if there is a blocking code before

fresh sierra
torn barn
#

that can take >0.5s for way more reasons than just blocking code

fresh sierra
torn barn
#

and blocking code can take less than 0.5s (although i cant assure this lol)

fresh sierra
fresh sierra
#

but if a shard cant keep up from 50s does that mean the shard was block for 50s ?

torn barn
#

yes

fresh sierra
#

the cause can be slow internet (from silly message)

#

if it was a blocking it would add also show
eartbeat blocked for more than X seconds?

#

(from what i understood from silly message)

torn barn
#

well yeah did not read that

#

anyways, yeah it appears to be something with the machine internet connection

fresh sierra
#

im at hetzner so its a bit strange

torn barn
#

the ack diff is greater than 10

#

so it must be that

fresh sierra
torn barn
#

difference between acks in the gateway

fresh sierra
#

i don't know what acks mean ;)

torn barn
#

ack = acknowledge

#

like, letting the client know the gateway session is still alive

fresh sierra
#

so because it took more than 10s to say the shard was blocked it can be internet issue ?

torn barn
#

yes

fresh sierra
#

ok, but why i have slow internet i need to figure that out

torn barn
#

i dont know, will need to check that with hetzner

#

🤷

fresh sierra
#

and also about the log, the issue is that the presence update flowwwww

#

so it hide everything, and i dont know if i disable event it will also hide the issue of why sometime my bot just stop working

oak onyx
#

Is there a way to set the type of an option to an StrEnum?

import discord
from discord.ext import commands

from models.riot import Platform


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

    @commands.slash_command(
        guild_ids=[632876897142833176]
    )
    async def verify(self, ctx: discord.ApplicationContext, game_name: str, tag_line: str, platform: Platform):
        await ctx.respond(f"Game name: {game_name}, Tag line: {tag_line}, Platform: {platform}")


def setup(bot):
    bot.add_cog(Auth(bot))
lofty parcel
#

Just pass choices

#
platform: discord.Option(str, choices=['Platform 1', 'Platform 2'])
oak onyx
#

thats why I ask if I can pass an enum

lofty parcel
#

Uhh prefixed commands do support enums but idk if slash options do

oak onyx
#

ohh, they do

#
platform: discord.Option(str, choices=Platform)
lofty parcel
#

Oh cool

#

Keep in mind the limit of choices is 25

oak onyx
#

Do you know what this warning is about?

shell radish
#

because its not a real ide

oak onyx
#

hahaha

#

it works

lofty parcel
#

If you wanna avoid the annoying warning add # type: ignore

oak onyx
#

thanks

round heart
oak onyx
round heart
#

Then the docs are wrong. 😬

oak onyx
#
class Confirm(discord.ui.View):
    def __init__(self, something):
        super().__init__()
        self.something = something

    @discord.ui.button(label="Verify", style=discord.ButtonStyle.green)
    async def button_callback(self, button, interaction):
        await interaction.response.send_message(f"Something: {self.something}")



class Auth(commands.Cog):
    # ...
    await ctx.respond(embed=embed, view=Confirm(something))

Is this how you would pass things from the command to the button_callback?

oak onyx
#

👍

oak onyx
#

Any ideas?

lofty parcel
#

You don't have the bot scope

oak onyx
#

But I was able to add it a different server before

#

🤔

#

or what do you mean?

lofty parcel
#

What's that gotta do with the bot scooe

#

Installation tab > guild install > add the bot scope

oak onyx
#

ahh ok, interesting that it worked for the other server

sage tendon
#

probably because you did pick the bot scope last time

oak onyx
#

hmm, same bot, but probably

oak onyx
#

ok, sorry to bother, I have no idea why now nothing is working and before everything was working...

main.py

import os
import discord
from dotenv import load_dotenv

load_dotenv()

BOT_TOKEN: str = os.getenv('BOT_TOKEN')

bot: discord.Bot = discord.Bot()

@bot.event
async def on_ready() -> None:
    print(f"Logged in as {bot.user}")

    COGS_LIST: list[str] = [
        'greetings',
        'auth',
    ]
    for cog in COGS_LIST:
        bot.load_extension(f'cogs.{cog}')
        print(f'Loaded {cog}')

    print("Bot is ready")

bot.run(BOT_TOKEN)

cogs/greetings.py

import discord
from discord.ext import commands


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

    @commands.slash_command(guild_ids=[1306734193635491951])
    async def hi(self, ctx: discord.ApplicationContext):
        await ctx.respond("Hi, this is a global slash command from a cog!")


def setup(bot):
    bot.add_cog(Greetings(bot)) 
Logged in as RiotAuth#9820
Loaded greetings
Bot is ready

but the on the server with the id 1306734193635491951 there are no commands, I also tried to do the same without specifying guild_ids, but that gives me the same output but also don’t work...

Does this also have something todo with my Bot configuration in the portal

sage tendon
#

restart discord

#

and first of all, dont load your cogs in on_ready

#

its too late then

#

(but you still need to restart discord after adding new commands)

oak onyx
sage tendon
#

yea well reading the rest of my messages and not just the first will help

oak onyx
#

I did, I just didn’t think that this was the problem, since it worked before, but I will rewrite it since you are right

sage tendon
#

it only works that way for prefix commands

oak onyx
#

idk. as I said it worked an hour ago (with slash commands), thats why I didn’t thout it was the issue.
But after the rewrite it does work now. So idk why it worked before...
Thanks for the help

sage tendon
#

probably because you put that command in the main bot file and not a cog

#

and why do you typehint a list you use once, and which you define right there lol
you dont have to do it that hard, python isnt java

oak onyx
eternal kite
eternal kite
#

alright thanks

echo wraith
#

So I'm not familiar with prefixed commands at all. I was wondering, is there a way to set boolean values as "flags" ? If it is in the command, it should be considered as true, else as false ?

sage tendon
#

isnt that just a default

sage tendon
#

i think something like that exists tho but im not sure if you have to manually parse it

eternal kite
#

is it possible to send a modal twice? because from the docs interaction.response can only be responded once, so im wondering if i can create a button that will send the user a modal when clicked

sage tendon
#

a button click is an interaction, and an interaction can be responded to by a modal

eternal kite
#

so basically i have a message object

await view.wait()
if view.value == True:
    await ctx.send_modal(modal)

how am i supposed to obtain the application context from the view?
i tried get_application_context() but it requires an interaction, but msg is a discord.Message object so msg.interaction_metadata returns InteractionMetadata instead of discord.Interaction

eternal kite
sage tendon
#

no, you respond in the view

#

in the callback of the button

#

interaction.response.send_modal()

lapis dock
#

Note, that discord does not allow for you to send a model in response to a model being submitted.

round heart
#

(modal)

lapis dock
#

stupid spelling, I hate spelling :angy

eternal kite
#

oh btw, how can i handle the event when the user clicked cancel in a modal?

fresh sierra
sage tendon
#

does it even call the callback when clicking cancel?

eternal kite
#

nope

#

i just tried it

sage tendon
#

yea then you can't lol
I guess you could wait for the modal and see if it was used or not

eternal kite
#

but the interaction is considered responded

#

if i click cancel and click the button again, it will show interaction failed instead of showing me the modal again

sage tendon
#

That shouldn't be related though
every button click is it's own interaction

eternal kite
#

it just stucks at modal.wait()

#

seems like its not possible to handle such event

sage tendon
#

can't you set a timeout for the wait?

#

if yes, set it to the modal timeout I guess

#

and well, typically it's not really necessary to handle a modal not being submitted
like nothing happens after that really and the views would just time out eventually

flat wind
#

is it possible to know the datetime of when a bot joined a server ?

#

from pycord btw, from discord client we can see this on the bot profile

little cobalt
flat wind
#

I want to know if my bot came in a server before X date, from the bot itself, not from the client side, do you know the argument ?

#

the pycord way (if there is)

#

okay that's Member.joined_at

little cobalt
#

That is kinda the same at the bot/client

#

so I dont really get it right now

flat wind
#

yeah but I searched where I can get this information, I just did not know where to find this information

little cobalt
#

at the docs from Py-cord

#

;3

sage tendon
#

ctx.me.joined_at

lethal loom
#

why its print none by bot.user?

from bot import Bot
async def main():
    print("Bot startet...")

    bot = Bot()

    bot_mode = None

    print("test")
    # Bot-Token abrufen und den Bot starten
    if get_config("bot.json", "development"):
        bot_mode = "Dev"
        print(f"Bot Mode: {bot_mode}")
        print(bot.user)
        await bot.start(get_config("bot.json", "tokens", "dev"))
    else:
        bot_mode = "Public"
        print(f"Bot Mode: {bot_mode}")
        print(bot.user)
        await bot.start(get_config("bot.json", "tokens", "privat"))

if __name__ == '__main__':
    asyncio.run(main())```

Bot startet...
test
Bot Mode: Dev
None

lofty parcel
#

Because you didn't start the bot?

#

You're printing bot.user before running the bot

undone merlin
#

that's a lot of prints

fresh sierra
#

it rely on cache doesnt it ?

lethal loom
#

no erros

lofty parcel
#

I have no idea what you're asking

lofty parcel
lethal loom
#

my exct not load

torn barn
lofty parcel
#

You do it before runtime.

lethal loom
#

but how i dont can use self.bot or bot in here

    def __init__(self):
        intents = discord.Intents.all()
        command_prefix = commands.when_mentioned_or("-")
        default_command_context={InteractionContextType.guild}
        default_command_integration_types={IntegrationType.guild_install}
        super().__init__(command_prefix=command_prefix, intents=intents, default_command_context=default_command_context, default_command_integration_types=default_command_integration_types)
    
    
    #here not 
    
    async def on_ready(self):
        ...```
lofty parcel
#

Inside the __init__?.... you have self... that's your bot...

fresh sierra
#

use just self

#

self will be ur self.bot in that case because self is the class which is ur bot

lethal loom
#

but my init is not async

#

i need asyn

fresh sierra
#

to do what ?

lethal loom
#

i need to laod ext async

lofty parcel
#

load_extension isn't a coro

fresh sierra
#

i dont understand what ur trying to do

lofty parcel
#

It's a normal method

#

You don't await it

fresh sierra
#

and also you shouldnt put it in async i think, you should just put it after ur bot method

#

like
bot = Bot()
bot.load_extension("...")

lethal loom
#

ah i need to load the ext before the bots start right?

lofty parcel
#

That's literally what I said 10 messages above

fresh sierra
#

yes so before the bot.run but you can still put it after the Bot()

lethal loom
#

ah ok sry guys

undone merlin
#

I wanna be able to sync my slash commands as soon as I start my bot instead of refreshing discord everytime

lofty parcel
#

That's default behaviour

#

You refresh your client because you refresh the applications command cache on your client

#

Sometimes you don't even need to refresh your client, they just show up

undone merlin
#

I forgot what it was

lapis dock
#

ctrl + R?

undone merlin
#

...

lofty parcel
#

Refresh and restart are the same thing.

#

If what wolfy said isn't it, then you're not making sense on what you actually mean

lapis dock
#

You are going to need to be more specific. All you should need to do is refresh/restart discord for commands to show up/change

lofty parcel
#

Once you make changes and restart your bot, you just refresh your discord client for changes to show up like wolfy said

#

You have to... the cache isn't going to clear itself

lapis dock
#

You can unload your cog -> reload your cog -> sync commands if that is what you mean. But it is a lot easier to just restart your bot

undone merlin
#

I just restarted the bot in the terminal

lapis dock
#

What you are trying to do is not possible, that is just how discord works

little cobalt
lofty parcel
#

There's nothing to put in your code that affects how your discord client works

#

That doesn't make any sense at all

undone merlin
#

it was like guilds_ids

#

something like that

#

made it so that the commands werent globally synchronized, just in one server

lofty parcel
#

Even if you register a command to a guild, you sometimes need to refresh your client.

lofty parcel
#

Registers the command to a specific guild

undone merlin
#

alr I figured it out

#

don't have to refresh discord everytime

fresh sierra
#

@echo wraith i might have some ideas for you:
Suggestion:

  • Enhance the get_application_command function to support localization.
  • Introduce a qualified_name_localization feature to retrieve the full localized name.
lapis torrent
frank kraken
#

can someone help

silk spire
frank kraken
eternal kite
#

what does this error mean? Application Command raised an exception: DiscordServerError: 503 Service Unavailable (error code: 0): upstream connect error or disconnect/reset before headers. reset reason: overflow

sage tendon
#

discord error, just wait a few seconds

fresh sierra
#

is there a way to get a bridge command ?

fresh sierra
#

are ctx.guild_locale, ctx.guild.preferred_locale the same ?

echo wraith
rugged lodgeBOT
fresh sierra
echo wraith
#

Idk

fresh sierra
#

or it relly on the guild preferred locale

flat wind
#

is there any way to reduce the ram used by the bot ? Mine is taking 1.6 GB, and sometimes goes up to 2.5 GB

fresh sierra
#

The presence intents takes a lot of ram afaik

flat wind
# fresh sierra Using less event/using less intents

here are my intents :
intents = Intents(guilds=True, messages=True, reactions=True, message_content=True, voice_states=True)
and my events are on_guild_join, on_guild_left, on_message, and on_raw_reaction_add

#

btw I have on_ready and on_shard_connect too

fresh sierra
#

Ur bot have 20k guild right ?

#

For how many user ?

flat wind
fresh sierra
#

Considering shard takes lot of ram too because it multiple the instance

flat wind
#

the current stats

fresh sierra
#

For 10 shard I don’t think 1.5g is a lot

sage tendon
#

to be expected with that many users

fresh sierra
#

Im at 500g for 4 shards so

flat wind
#

okay lol, so I will buy new RAM, from 16gb to 64gb will be fine I think (I have other services on my server)

fresh sierra
flat wind
#

the only thing I hate with sharding is that we have to restart the bot for each new shard (or create a new instance using CI/CD)

flat wind
fresh sierra
flat wind
#

pms, arr suite... things like that

fresh sierra
#

Even if it’s just a fonction like that

flat wind
fresh sierra
#

How much time does ur on ready takes ?

flat wind
flat wind
#

2m today

fresh sierra
#

Yeah you can automatically put something for it add the shard count by itself and then restart according to the guild

#

You will just need to be careful for it doesn’t add and remove every time when it’s between 2 number

flat wind
fresh sierra
flat wind
#

tbh, I will make the request every 30minutes so I don't really care of it too, I will ask later if I get any problem about this function

flat wind
# fresh sierra No idea for how it decide the shard so you might want to check

looks good like this :

    @tasks.loop(minutes=30)
    async def check_shard_count(self):
        headers = {
            "Authorization": f"Bot {TOKEN}",
            "Content-Type": "application/json"
        }
        resp = await client.get("https://discord.com/api/v9/gateway/bot", headers=headers)

        # format of resp.json :
        # {"url":"wss://gateway.discord.gg","session_start_limit":{"max_concurrency":1,"remaining":978,"reset_after":62984486,"total":1000},"shards":22}

        if resp.status_code == 200:
            resp = resp.json()

            if resp["shards"] != bot.shard_count:
                print(f"=== Shard count changed ! {bot.shard_count} -> {resp['shards']} ===")
                sys.exit(0)
fresh sierra
#

I didn’t know that like that discord sends a number of shard, I thought it only sent with the client at the bot.start

flat wind
echo wraith
fresh sierra
#

Like the get bridge command

lapis dock
#

If you have questions you can ask them here

fresh sierra
lapis dock
fresh sierra
#

Oups on

lapis dock
#

:3

undone merlin
#
             ~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: type 'Option' is not subscriptable
#

getting this error

lapis dock
#

should be () not []

undone merlin
lapis dock
#

As an actuall error or just a warning? You can # type: ignore it (if that is the correct syntax)

undone merlin
errant trout
#

you're 100% sure you changed it

undone merlin
lapis dock
#

and saved the code?

errant trout
#

as far as i can tell you just pasted the same error, it only happens if you're doing Option[...]

undone merlin
#

I forgot

#

mb and ty

#

I thought I saved it but I guess I didnt

lofty parcel
#

Real devs spam ctrl + s

lapis dock
#

idk why VS code does not autosave when you run the code. Seems like a basic QOL feature for an IDE

errant trout
#

this is why IDLE is superior

lofty parcel
#

Or i think it's just when you switch windows / tabs

#

Well that's kinda obvious isn't it

undone merlin
#

i don't really mind it

sage tendon
#

which IDE doesnt autosave everything

#

oh yea vsc

#

but thats not an IDE so fair

little cobalt
#

did you ever took a look at the settings?

sage tendon
#

okay, "by default"

unique wyvern
#

im having a bit of a problem
ive made a bot and its now running on my computer, but whenever i try to run the ping command that ive made it doesnt appear in the slash commands dialogue

this is my code
`import discord

bot = discord.Bot()

@bot.event
async def on_ready():
print(f"{bot.user} is ready and online!")

@bot.command(description="Pong!")
async def ping(ctx: discord.ApplicationContext):
await ctx.send("Pong! Latency is {bot.latency}")`

lapis dock
#

Try reloading discord with Ctrl + R, discord caches the command lists for bots so it can take a while to update on its own

#

Otherwise

sly karmaBOT
#

Application Commands Not Showing Up?

  • Refresh Discord by restarting or pressing Ctrl+R (or Command ⌘ + R)
  • Uninstall libraries that conflict with the discord namespace (e.g. discord.py).
  • Invite your bot with the application.commands scope.
  • Load cogs before bot.run() (e.g. not in on_ready).
  • Do not override on_connect.
  • Update to the newest version of py-cord (see ?tag install).
  • Turn off User Settings > Accessibility > Chat Input > Use legacy chat input.
  • Share your code and errors.
sage tendon
#

and dont use ctx.send with slash commands

#

also i think .command is just a prefix command, use bot.slash_command

little cobalt
lapis dock
#

^^

sage tendon
#

ah yea i keep mixing them up

unique wyvern
#

works! tysm!

lapis dock
#

🎉

unique wyvern
lapis dock
#

That was toothy just reading wrong.
The other thing toothy said

and dont use ctx.send with slash commands
Is correct
You should use ctx.respond when using slash commands