#Basic Pycord Help
1 messages · Page 61 of 1
__init__ makes it a module
also modules should be lowercase
i will use the function that i usally do
@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
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
is there an extra incantation i need to get this to run? currently never runs
yes
session_cleanup.start
Are you starting the task?
that was it, thanks 👍
i still wonder how it works behind the scenes ngl
It just creates a separate task on the loop lolz
Oh
It replaces the method with an attribute of type Task I believe
yea i had to look at how decorators work at all
Oh right
i hate decorators i always forget how they work and they seem weird
but i love using them for options
Basic Pycord Help

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 ?
dont think you can
any other way to auto delete forwarded messages ?
wait for 2.7 or see if forwards are already on the repo and use that
but 2.7 isnt guaranteed to have it
havent heard much about forwarding here tbh
the discord.py already has it ig
no, it doesn't
also.. why do you fetch the channel history instead of just the message that caused the event?
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
im pretty sure single message fetching has much higher ratelimits than history
also why do you send a json of the deleted message lol
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
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
i mean if its a user message, im pretty sure the body of a forwarded message can only contain text / emojis
users can forward bot messages
ah
but you are saving it to disk in your code, just to delete it like 5ms later
I wouldn't need this if that was not possible. the automod is good to block
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?
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
😭
F
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
Also, the older the message, the lower the limit.
uh, no?
Yes?
if you want the actual ratelimit just read the response headers
source?
I'll set it to print the response header too
Dpy and experience 
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
True
it depends on the data structure used
for all we know, they could be using a BST
i would not hope so
probably not but you should get the point
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)
please split your view from the rest of your code
that way you can also control it better
What do you mean?
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
I tried to make subclass
But i don't understand how to make all selectors work, not only last
you can ask here for help
i asked
yeah but i mean send ur code with the subclass and ur issue for we can help u understand how it works
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
I have this now
i'm creating list of lists(because of 25 choose variants limit). And filling selection forms from these lists
Can you pls delete that list?
ok
Thx
Maybe you can help me with my problem?
The menus got a limit of 25 items
If you use autocomplete you can use a lot more
Here's the slash autocomplete example.
Here is a example for it
Its like choices but without a limit, but they still could wirte anything at it because its not "required" to use the stuff from the list
also lets you display the actual role names properly and not just the IDs (tho you could have done that in the select too)
i didn't understood how to make role selection in selector. Because of this i decided to make "get role by id" after user chose it's id in list(temporarily).
I understood what is it, but i don't need it in slash command
Thank you for advice
you can use optionchoices
but the only reason you do the whole select stuff is because of the 25 item limit.-
i know, but the question was how to make all selectors work with callback
)
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?
if you want to show all role
Because of this i asked a question
why dont u use the role_select ?
i didn't understood how to use it
role_select = discord.ui.Select(
placeholder="placeholder",
select_type=discord.ComponentType.role_select,
)
just like so
but you can also just make it a slash command option if you do it like that
i know about slash command method, but it's hard to use it on server with 100+ roles
not really
discord.Role
thats it
and then jsut type the role name
ok, and what's next i need to do?
its not possible
remove the option and th max values since you want the user to select as much role as he want
but if i limit user from getting all roles?
if you want to limit, then put the number that u want
because rn u just limit the user with the number of choice
which mean no limit
you HAVE to check the roles tho
else the bot could give people admin roles if your role setup is wrong
he wants to do an addrole command ?
wierd way to do an addrole command
ok question
what is your goal with this command / select stuff
i need to make selectors where users can choose multiple roles when they enter the server
use onboarding..
ok, so role_select is not the best idea since u want to show only the role that the user can choose
Yes
why dont you use discord's onboarding
its literally the exact thing for this scenario
because to enable that you need to have 5 text channel enable for everyone
and thats stupid!
if your server doesnt even have 5 text channels its not really worth being a server lol
verification roles?
its a support, why would i need all thing to be for everyone
yes
?
i have general, support, command, image and that all
i just made 4 hidden channels that no one can see with some trickery
that way i can bypass that :)
If you have a "verified" role, the @everyone role can only see a single channel
Could you elaborate a bit on this please?
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
so i can just create a channel give everytone the perm to write but not to see and it will work ?
no, the channels just become hidden once they get my autorole
because the autorole has denied permissions for that channel
ooo
i see
but seriously why did discord add this stupid rule
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
isnt it just callback
it is...
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
is there like modal.wait like for views
yeah it wait but i cant get the value from the callback still
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
just set an attribute in the modal class and access it with modal.attribute
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?
try self.message
Nope, that fails too
as?
Unknown message
is it ephemeral?
Yes
Nah, I've def deleted ephemeral messages before.
yea but its weird as you can see
i just passed the instance of the view and i will edit the self.prize
does ur bot has access to the channel ?
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
Hm. Nelo suggests delete_original_response should work here. #1132206148309749830 message
because i think to delete a message you need to have the permission to see the message inside the channel
yeah but it doesnt say that u dont need the perm to view the channel
im not sure about that but i will like its logical
The bot is fully integrated. Shouldn't have anythign to do with perms
so he has access to that channel ?
Yes, of course. Outside of webhooks, are there bots that don't have access to channels it sends messages to...?
with / u can use a command even if the bot doesnt have access to that channel
if you print interaction.original_response() is it returning the message
Nope
interaction.followup was populated, but deleting that returns 404, as well.
did u defer ?
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.
so it send the modal, and then next a response and u are trying to delete that reponse right ?
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.
Ephemeral messages can only be accessed from an interaction so yes
And ..._original_response only work after responding
but can you do msg = the send of the thing.
await msg.delete
(since you first sending a modal, it answer to the interaction so the other one is a followup
I mean, deleting should sorta bypass all that. I know I have an interaction message I want to remove; Discord making it more complicated than it needs to be
aaaa no because its ephemeral you cant if i understood
Nope.
Yup
its not a message yet if you never ever responded tho (?)
if you send a modal it is
Except it clearly is, it has an ID and everything.
can i use jishaku with PyCord ?
sure
discord.errors.ExtensionFailed: Extension 'jishaku' raised an error: AttributeError: module 'discord.ui' has no attribute 'TextInput'
uhh dont remember how to fix that exactly lol
but i do know i used it on pycord
isnt that InputText for py-cord
and dpy is TextInput
might be the issue
maybe do a fork
and some more issues
i found
2.3.2 should still work but yeah anything after that is targeted for dpy 2.0 from this server
are you using rn ?
no
then use 2.3.2 ig lol
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?
You're using python 3.13. You have to install audioop-lts
ah sweet, cheers 🙂
or don't use 3.13 yet, but wait for Pycord 2.7
or install audioop-lts
.tag audioop
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.
why when i create a slash command it is working for once but the command get unregistered right after someone or i use it
do you use bot.sync_commands anywhere
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
remove it wherever you have it, its not needed
ok but it still doesn't work at all
i tried making a simple greet command it didn't worked
so it disappears from your command list when you use it?
but it works? or does it not do anything
it works
show your main bot file and the code of the command if its somewhere else
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")
does it happen to someone else too?
also, make very sure your bot isnt running twice
yeah he used it and i couldn't use it after
and neither could he?
as in i think you have 2 files running the bot with the same token
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
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
ok i'll try
what for if its not cogs?
still not fixed, same issue
how do you start your bot
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
for me this is easier to have multiple files for single purpose each
ye
yea, thats the issue
Cogs, often known as modules or extensions, are used to organize commands into groups. This is useful
fine i'll read it
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
.rtfm timeout
(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)
I don't think there's a max.
Maybe it's ephemeral interactions. I remember having a weird issue with the Paginator - been a while, though
as long as your bot is running
By default is 15 I think, but if I pass timeout = None it should last as long as the bot is running
Isnt it 180s by default?
180 I just check
-remindme 2h this thing
Set a reminder in 2 hours from now (<t:1730970284:f>)
View reminders with the reminders command
How does work the this thing ? For then it give u thing
wdym
Nah I just tough for a moment that the view was related to the previous message
I just need more sleep
Reminder for @echo wraith
this thing
Done
What did u do ?
It was already doc
Not in the docstring
I added it here
can we achieve auto-reloading of cogs whenever we create, modify, or delete a file
Why?
auto-reloading could speed up our development workflow by instantly reflecting changes without manual reloads
py-cord 2.6.1
Why did you delete it?
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'```
And the bot?
@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# ```
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)
problem was in index.py
You have to change it to bridge.Bot
thx bro
can u help me @little cobalt
You could write a scrips which checks for changes at the files
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()
You would have to change some stuff if you want to do the reload stuff
pressing 1 button isnt fast enough?
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
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
can pycord do user commands?
user commands as well as user apps
i cant find anywhere how to do them
.rtfm user_command
well, i take it you want a user app and not a user command?
because thats the thing thats new
Or maybe they do want user commands lol
100% of people so far who asked for user command wanted user apps
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
did their solution not work for you?
I would like to look into this, but could you share a minimal reproductible code please ?
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
didn't it throw an exception in that case?
Yeah, but where should it be handled? Or how
I think you can try to run a loop that starts the bot and close in the exception and check the internet connection before the bot starts, in a loop
Well, I'm assuming that the loss of connection throws an error outside of the async event loop.
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
I'm not sure if there is a ready-made option for this
I don't think so, but maybe someone has a better alternative
how can i specify allowed command context per command?
use the decorator, but you can only do it per command and not subcommand
@contexts
thx
you should run it somewhere with stable internet like a VPS
.tag vps
Need to run your bot 24/7? Get a cheap VPS.
Scaleway - EU
Time4VPS - Lithuania
Infomaniak - Western EU/CH
Hetzner - Germany/US
DigitalOcean - US
Vultr - US
GalaxyGate - US
- Self-hosting: Any computer
- Free hosting:
Herokudead 🦀 - Kinda free: GCP, AWS (one year free micros)
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
Id imagine they have the same IP for many users 🤔
and thats a problem why
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
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
what about the free oracle VPS?
Well, I don't know how to share this here exactly, but for those who want to play around, there are some TV boxes that you can install a Linux system on, and they are very cheap, around 20 dollars. Well, it was an option I found to avoid spending money on a VPS.
I can't create one 
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)
why dont you try it out
yes
also for slash commands you should consider using @discord.default_permissions
Server owners have all permissions
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"?
I dont get the warning but you can use the decorator version of option instead
As shown in this example
https://github.com/Pycord-Development/pycord/blob/master/examples/app_commands/slash_options.py
Pretty much the same thing but you have to provide an argument to let pycord know what option coraspons with what function argument
FWIW, mypy says
Variable "..." is not valid as a type
See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases
and pylance says
Variable not allowed in type expression
and links to https://github.com/microsoft/pyright/blob/main/docs/configuration.md#reportInvalidTypeForm
working through the docs just exchanges one error for another.
Yes rhat happens when you typehint Option
Sometimes python doesnt like it
If you really wanna typehint Option, you can add # type: ignore
i'd like to type hint it to input_type, that'd be awesome.
use the decorator, then you can use regular typehints accordingly in the function signature
Pyright doesn't like it as well
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?
I think so

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
can you show the command code ?
.tag paste
you might have in ur code a
how do i use that
async def command(self, ctx, test= None, test)
but the test = None should be the last option
you open the website, paste your code there then send the link here
the thing wasn't scrolling to show the button
https://mystb.in/200983c2bc129e2408 here's the whole cog
wouldn't that trip the error every time?
yeah
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,
):
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
was i not supposed to move the decorator with it when i tried that
broke
i tried that on the similar command farther down too but still nothing
Are there any other commands somewhere else ?
not loading this cog gets rid of the error permanently so i don't think the problem is somewhere else
Can you load only this cog
And see of you still have it
And send here the error too
I want to see the number in the error
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
show your code.
comment the commands out one by one to see which one it is
Or enable debug logging and show the output
debug logging?
.tag logging
Pycord logs errors and debug information via the logging python module. It is strongly recommended that the logging module is configured, as no errors or warnings will be output if it is not set up...
Set it to debug, not info tho
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!
makes sense
i found it by looking at the json the debug log spat out in one of the PUT lines
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?
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
Read the message directly under I fixed it
Can you share the fix
The message below literally has the solution.
Bot's aren't member objects?
A stage channel isn't a member object.
ctx.guild.me is the bot's member object of the server
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
don't use python 3.8..
3.8 is EOL and not even supported by Pycord anymore for all I know
@lapis torrent
hello
Is there something specific you can't find, or do you just want to find everything related to your example?
it would be really helpful
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
@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
ik how to make buttons and embeds
you have to search for the options for that
like u see how it's asking me to fill the boxes
Those are options
You can search discord.Option
i literally can not find anything I want on the documentation page
wait
is it this
this is a reference of the type of the input / output you have to pass
the arguments like message, choice1... are this type : https://docs.pycord.dev/en/stable/api/application_commands.html#discord.Option
These are decorators of the async function, just with the @bot.slash_command
yea I get that
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)
so if I want a channel ID
ask for a channel in your option, and the input type will be a channel. Then you can get the channel ID with channel.id
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....)
you probably wanna limit the option to discord.TextChannel
do you even know python at all..
Das frage ich mich bei einigen sehr oft
naja wir setzen grundwissen schon vorraus.. eigentlich könnn wir sagen "fick dich" und gut is
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)
input type is also the second positional argument so you dont have to pass it as kwarg
git install is on readme
so just pip install --force-reinstall git+https://github.com/Pycord-Development/pycord.git@refs/pull/2564/head ?
yes, looks good.
Will it be in the 2.7 ? The PR has not been merged
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 ?
just restart the bot if its not a big one
yea, don't use sync commands
well you can use it
restart something like 20 shards take time for fixing just an issue
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
okay, thanks.
I have put the sync as an argument of a command to avoid raising it everytime I reload a cog
that's only when needed
I just kinda wonder how you change a command without restarting the bot
or do you reload the cog
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()
This looks like some asyncio error
yeah but i dont really understand why im getting this
and why does it block my code
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
this is blocking
As client.run
the bot.run call retains the loop until the bot closes
i dont remember why i was not using it,
that is why anything after that that involves the bot (i.e.: command creating) are ignored
but anyways everytime im using client.start it doesnt work
Could you show the code you have tried?
im not the only one but the bot just never start and raise some error
.
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())
i put the same thing
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
as always, what did you change since it last worked
i mean he knows
he assumes
nah he knows what is my last change
because he pasted it 5min ago
if you dont wanna tell us then you cant expect good help
you asks me what i change to my code when 5min before anonymous asked me to use this to start my bot
so ofc the only thing that changed is what he asked me to add
ive sent it here lol #1246104091780710471 message
No
I was asking what you changed BEFORE that error appeared
well nothing because it was from the library side
yea but you did something before you started getting that error
no, it just randomly happen
is it possible to disable link buttons ?
Nope
fake it with a link emoji and a regular button
Kek can you do that?
but you can't open a link directly with it tho
it's disabled
Pretty sure you can disable a link button
nope
wtf it does
await ctx.send(view=discord.ui.View().add_item(discord.ui.Button(url="https://google.com", label="lol", disabled=True)))
What a waste of lines /s
same, im really chocked
can you still click it?
Can you click a disabled component?
no
No, it just does not make sense to disable a link button, its not like the link is not available anymore
yes but it doesnt do anything 🤓
You can't click it tho
True
we should make an announement for that revolutionary thing
let me tell you about editing the button out instead
wdym
remove the button from the view
to do what im a bit lost
make people unable to click it
you can just disable it for that
thought you couldnt disable link buttons
we all thought that but.
@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...
try it and see if it works
but you got the argument order the wrong way around
its button then interaction
this doesn't work because there isn't a response to delete
(if it does then screw me i guess but it shouldn't?)
Yeah I always get confused how it works... Thx, maybe I really should just try it xD
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
you mean defer and then delete original response?
(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
yeah I'm on discord.py for this project, they don't have interaction.respond
yeah, thx 🙂
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)
you sure it isn't your server
my server seems to work without issue
im using pterodactyl and i dont see anything problematic
i mean i got it 2 times in a while so if there is no evident thing i might let it like so
Do fetch calls like fetch_user automatically get cached?
Doesn't look like: https://github.com/Pycord-Development/pycord/blob/c8eee71238a0dce5c938617f12c12e54cbc17f22/discord/client.py#L1813
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
There's store_user (bot._connection.store_user)
I dunno why they don't get cached though, thought they did for some reason.
That works thanks
Also, seems like the cache is persistent right?
There's no TTL I believe
user cache is yes
Yes
Using the discord.File
How can i convert a attachment to a Discord.file?
discord.File
discord.File.description
discord.File.filename
discord.File.fp
discord.File.spoiler
discord.file.File
discord.Guild.filesize_limit
discord.sinks.Filters
discord.utils.filter_params
discord.CheckFailure
discord.ContentFilter
discord.ContentFilter.all_members
discord.ContentFilter.disabled
discord.ContentFilter.no_role
discord.LoginFailure
I did not have to change the commands. When I try some changes, I make them on a beta bot, and after all tests I push them on the real one, and restart the bot. But it is so rare.
In case it is just a small change that only affect the backend and not the interaction itself (client side), I just reload the cog
Pretty sure you have to explicitly sync commands after reloading a cog, too
Yes
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.?
you have member.timed_out
Models are classes that are received from Discord and are not meant to be created by the user of the library. Attributes key, url. Methods def is_animated, async read, def replace, async save, def ...
Thanks, apparently I really am blind 
No
this if you want to know for how long
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
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 ?
i would say its client side like for any mention
the message itself doesn't contain the info, but you can use Client.fetch_invite on any valid invite code/URL to get it
can i somehow detect when my bot gets mentioned?
you can listen to the on messahe event and then check every message
when i did events last time some of the reaction add events were not listened to somehow, do you know why?
There could have been many reasons but one might have been that you would have had to listen to on_raw_reaction_add with the"raw"
If you encouter a specific issue using events feel free to share it here
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?
it listents to all messages including all available channels and dms
To add to this: https://docs.pycord.dev/en/stable/api/models.html#discord.Message.mentions
The mentions parameter of messages might come in handy
ah nice thx
oh okay thanks
how do i get the full command used by users? including argument values
for command name, ctx.command.qualified_name
for options, ctx.selected_options
thx
how do i create a permanent button that will work even after restarting the bot?
Here's the persistent example.
Use that example ^
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
That usually happens when there is blocking code somewhere
Yeah but my thing doesn’t detect any blocking code
And for debug logging, you can filter out the logs you receive, usually the ones that you should not care are on discord.state
Do you open any files?
simply do in any part of your code
import logging
logging.getLogger('discord').setLevel(logging.DEBUG)
logging.getLogger('discord.state').setLevel(logging.WARNING)
Sometime yes
Then that's it
How do you open them?
You should open it either on another thread or run it on another executor
Im gonna try thanks, will this also show why for exemple sometime my bot stop complètely working without errror
As I say my bot doesn’t detect any blocking code before those log
Everything is async and not blocking
with open is blocking
(I mean I do have sometime blocking code but there are from asyncio session
Or how do you open your files?
I have something that detects every blocking code
And no blocking code is detected before
Using the rie
No because that’s a dumb way to detect blocking code
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)
yeah but only for that shard, and it doesnt also appear everytime
it does not need to be from your code but can also come from any library you use
cant it be cache etc before the cog are loaded ?
yeah i know
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
you should not depend on that
but this process only start after the loading of the code so if there is a blocking code before
well it tell me in case my code was blocking so i know where to fix it
that can take >0.5s for way more reasons than just blocking code
how does an asycio.sleep(0) can take more than 0.5s without a blocking code ?
and blocking code can take less than 0.5s (although i cant assure this lol)
depends on the machine
yes but im checking for 0.5 since i think under its not that important
well i never add an issue of it showing some false positive so
but if a shard cant keep up from 50s does that mean the shard was block for 50s ?
yes
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)
well yeah did not read that
anyways, yeah it appears to be something with the machine internet connection
im at hetzner so its a bit strange
just bumping that
what is the ack diff ?
difference between acks in the gateway
i don't know what acks mean ;)
so because it took more than 10s to say the shard was blocked it can be internet issue ?
yes
ok, but why i have slow internet i need to figure that out
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
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))
Just pass choices
platform: discord.Option(str, choices=['Platform 1', 'Platform 2'])
I think this would get messy if there are a loot
thats why I ask if I can pass an enum
Uhh prefixed commands do support enums but idk if slash options do
Do you know what this warning is about?
vsc being dumb
because its not a real ide
If you wanna avoid the annoying warning add # type: ignore
thanks
Looking at the docstring, you may be able to just use Platform as your type. Curious if that resolves the warning.
https://docs.pycord.dev/en/stable/api/application_commands.html#discord.Option.input_type
If a
enum.Enumis used and it has up to 25 values, choices will be automatically filled.
you mean like this?
this will error
Then the docs are wrong. 😬
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?
yes
👍
I tried to add my bot to another server, but it does not seem to work, I get a seccess message, but the bot is not getting added.
Any ideas?
You don't have the bot scope
What's that gotta do with the bot scooe
Installation tab > guild install > add the bot scope
ahh ok, interesting that it worked for the other server
probably because you did pick the bot scope last time
hmm, same bot, but probably
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
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)
I just did, but its still the same.
yea well reading the rest of my messages and not just the first will help
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
it only works that way for prefix commands
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
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
I had it in the cog from the start, but maybe I did have the cog registration run once outside the startup and since I only edited the content of the command I didn’t nitice that my cog registration didn’t work anymore
hahahah true
and how do i remove a persistent view?
alright thanks
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 ?
isnt that just a default
i think something like that exists tho but im not sure if you have to manually parse it
yeah same idk
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
a button click is an interaction, and an interaction can be responded to by a modal
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
the issue here is that the ctx in ctx.send_modal is not the context author i wanted to send the modal, instead it should send to the user whoever interacted with the view, while the ctx author is the person who initiated the command
no, you respond in the view
in the callback of the button
interaction.response.send_modal()
Note, that discord does not allow for you to send a model in response to a model being submitted.
(modal)
stupid spelling, I hate spelling :
oh btw, how can i handle the event when the user clicked cancel in a modal?
using the callaback mb I didn’t read
does it even call the callback when clicking cancel?
yea then you can't lol
I guess you could wait for the modal and see if it was used or not
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
That shouldn't be related though
every button click is it's own interaction
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
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
so you already answered the question?
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
?
That is kinda the same at the bot/client
so I dont really get it right now
yeah but I searched where I can get this information, I just did not know where to find this information
ctx.me.joined_at
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
that's a lot of prints
it rely on cache doesnt it ?
no erros
I have no idea what you're asking
It probably gets the user object once it connects to the gateway.
my exct not load
It fetches it from login()
You don't load extensions on on_ready
You do it before runtime.
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):
...```
Inside the __init__?.... you have self... that's your bot...
use just self
self will be ur self.bot in that case because self is the class which is ur bot
to do what ?
i need to laod ext async
load_extension isn't a coro
i dont understand what ur trying to do
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("...")
ah i need to load the ext before the bots start right?
That's literally what I said 10 messages above
yes so before the bot.run but you can still put it after the Bot()
ah ok sry guys
rq can u help me with somethin
I wanna be able to sync my slash commands as soon as I start my bot instead of refreshing discord everytime
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
I forgot what it was
ctrl + R?
...
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
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
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
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
I just restarted the bot in the terminal
What you are trying to do is not possible, that is just how discord works
At a big bot that could create problems, at a small one I also would just restart it
There's nothing to put in your code that affects how your discord client works
That doesn't make any sense at all
it was like guilds_ids
something like that
made it so that the commands werent globally synchronized, just in one server
Even if you register a command to a guild, you sometimes need to refresh your client.
Yes that's what guild_ids do
Registers the command to a specific guild
@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.
Can anyone shed some light on this issue? Github issue hasn't been updated in a while. I upgraded python version and pycord version but error still persists. Note it only happens when joining a stage channel, but when joining a regular voice channel
can someone help
pip install audioop-lts
Thanks
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
discord error, just wait a few seconds
is there a way to get a bridge command ?
are ctx.guild_locale, ctx.guild.preferred_locale the same ?
The first is gotten from the interaction itself afaik
yeah but like can it be different ?
Idk
or it relly on the guild preferred locale
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
Using less event/using less intents
The presence intents takes a lot of ram afaik
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
21.5k now
smth about 2.5M
So the 1.5g is not a lot
Considering shard takes lot of ram too because it multiple the instance
the current stats
For 10 shard I don’t think 1.5g is a lot
to be expected with that many users
Im at 500g for 4 shards so
okay lol, so I will buy new RAM, from 16gb to 64gb will be fine I think (I have other services on my server)
If you have other services in case you don’t know you should have other ip too
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)
why ? the other services are not discord related
O so it should be okay mb
pms, arr suite... things like that
I get that, everytjme I change a function inside my client class I need to restart every bot for it takes that into account
Even if it’s just a fonction like that
it does not disturb me if I add / edit something, but just for 1 new shard, I have to restart the bot
If you add something inside your client class you don’t need to restart it ? Or just you don’t care because you change something
How much time does ur on ready takes ?
I don't care because I edit something, so it is "for the community" not "for discord"
I should automate this by doing some API calls to the platform, and do a sys.exit if the shard_count is different of the one after the API call. By using it in Docker with a restart unless-stopped, it will just restart from itself
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
just make the API call every 1h 🤷
and I don't think the number is a specific one for the change of shard number.
Ex : if at 4550 servers I get 5 shards, I don't think it will tell me 4 shards anymore except if I get down to 4450 servers
No idea for how it decide the shard so you might want to check
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
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)
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
no, it sends the shards too, it is explained here :
https://discord.com/developers/docs/events/gateway#get-gateway-bot
I have made a small bash script that just sends the request and return the number of shards using curl and jq, before adding the loop (I used this script since like 6 months)
Idk maybe we can find a place for that in discord.utils but idk
Yeah if you want I know some missing things too, I coded them in my thing but I think you can do them without issue
Like the get bridge command
If you have questions you can ask them here
I don’t have question, that’s just some missing things too the library
That was not to you, the other person deleted there message
Oups on
:3
~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: type 'Option' is not subscriptable
getting this error
should be () not []
ThenI get : Call expression not allowed in type expression
As an actuall error or just a warning? You can # type: ignore it (if that is the correct syntax)
still
~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: type 'Option' is not subscriptable
even after using ()
you're 100% sure you changed it
yes
and saved the code?
as far as i can tell you just pasted the same error, it only happens if you're doing Option[...]
LMAO
I forgot
mb and ty
I thought I saved it but I guess I didnt
Real devs spam ctrl + s
idk why VS code does not autosave when you run the code. Seems like a basic QOL feature for an IDE
this is why IDLE is superior
I think you can configure it
Or i think it's just when you switch windows / tabs
Well that's kinda obvious isn't it
i don't really mind it
?
did you ever took a look at the settings?
okay, "by default"
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}")`
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
Application Commands Not Showing Up?
- Refresh Discord by restarting or pressing
Ctrl+R(orCommand ⌘ + R) - Uninstall libraries that conflict with the
discordnamespace (e.g.discord.py). - Invite your bot with the
application.commandsscope. - Load cogs before
bot.run()(e.g. not inon_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.
and dont use ctx.send with slash commands
also i think .command is just a prefix command, use bot.slash_command
its discord.Bot so its fine
^^
ah yea i keep mixing them up
works! tysm!
🎉
if you dont mind me asking what is this about? and what could i do to make my code better?
That was toothy just reading wrong.
The other thing toothy said
and dont use ctx.send with slash commands
Is correct
You should usectx.respondwhen using slash commands
-# Docs: ApplicationContext

