#Basic Pycord Help
1 messages Β· Page 41 of 1
I noticed that if you have a command with options but without the self , ctx is not shown as a option
but if you add it, ctx is shown as an option
and I still wonder why I cannot add a description to my slash commands...
how are u trying to add the description ?
yea, because ctx is self in that case..
why cant you
he doesnt know that the things ;)
No, he's saying he cant, so there's a reason why he thinks that
I still wonder why I cannot
for me that mean he doesnt know
One question, what is the maximum number of options that I can put in thechoices parameter?
25
if you want more you can use a autocomplete
ok, ty! 
also fyi you dont need required?True
and you set the name twice lol
you can delete the name=
It asks me for the name of the parameter of the function to which it is associated, or so I read in the documentation. And the parameter is called the same π€ correct?
no
the first positional parameter is the name parameter
if your parameter name in the function header differs from the option name, you set that via parameter_name=
ok! Thank you very much, I am still new to the options 
there is no guid about it
that sad because there is soo munch thing that u can do using those
Learn all about Slash Commands and how to implement them into your Discord Bot with Pycord!
at least the bare minimum ^^
but neither of the ways shown there use the decorator which is sad because the decorator is universally better
is that I used to work with the Option object directly in the function parameter, but for some reason Python gives me an error when I use it there. I'm migrating to @option() decorator
haha
i agree with that
almost the same just its not input_type but type
its working at the main file but not at a cog what is really weird
yes, I got it, I got a little confused, thank you.

i think name and description have to be put prior to the bot running
im doing like that :
description = cmd_default.get("description")
if description is not None:
command.description = description
and its working so i guess the issue can either be from the description, either because of the decorator( which will be strange)
if you add some print before the command.description
are they triggered ?
that still not explains why its working at the main file but not at a cog at the same command
main file is run prior to the bot running
so maybe it put those description at that moment
and then when the bot has run it cant place the description no more
i guess
I can test it without running the .run and the stuff is getting added to the command
like in the cog ?
both
how can you test without running the bot i dont understand
so in ur test the description is set but when ur bot is running its not set
well, I can just print it at the config one and see
at the cog
can you send me the code in codeblock, i will try to do it and make that work
and just how look the json for one command
I have a problem that I can see the slash commands, but my friend can't. Any ideas why it's like that?
just restart ur discord
we both did and it still only shows up for me
its just a basic json file with name and description
so
i tried a bunch of thing
and its not possible
i forgot that nelo already told me that
when i was trying to do that
command.name cant be done after bot is run because it will send that to the api before
its all before of it
and even by changing the local like so :
def test_config(command: discord.SlashCommand) -> discord.SlashCommand:
with open(f"test.json", "r", encoding="UTF-8") as file:
data: dict = json.load(file)
if "name" in data:
if (current := getattr(command, "name_localizations")) in (None, discord.MISSING):
setattr(command, "name_localizations", {"fr": data["name"]})
else:
current["fr"] = data["name"]
if "description" in data:
if (current := getattr(command, "description_localizations")) in (None, discord.MISSING):
setattr(command, "description_localizations", {"fr": data["description"]})
else:
current["fr"] = data["description"]
return command
the @config is run before the command
but its not run with the load extension i think
(from what i remember nelo told me
if you want i have another solution without decorator that im using
but why do I still get the print of it?
so its getting run with load extension
i will check what is sent to the api wait
yeah
{'id': '1246890345002827857', 'application_id': '1127255044182507662', 'version': '1246890345002827858', 'default_member_permissions': None, 'type': 1, 'name': 'test', 'description': 'No description provided', 'dm_permission': True, 'contexts': None, 'integration_types': [0], 'options': [{'type': 3, 'name': 'test', 'description': 'No description provided', 'required': True}], 'nsfw': False}
here what is sent to the api
using ur decorator
as you can see neither name or description are different
still weird, because it was working for some time x3
i agree with that
because after looking at dorukmng
i kill his name sorry
he was using something similar
which is not working either
so if you want i have another solution but ur thing doesnt appli neither name or description
whiche one?
so basically
you do a function before the bot run
that itinerate into the self.bot._pending_application_command
and you do ur thing
its like easier and faster
for command in self.bot._pending_application_commands:
ur function
if you need help with that let me know
at the main file?
or just at the config file for the command?
you can do it in the main file
however you will need to handle the sub command
for example :
def add_default_commands(self):
for command in self.bot._pending_application_commands
self.add_default_command(cmd)
def add_default_command(self, command: discord.ApplicationCommand | discord.SlashCommandGroup):
if isinstance(command, discord.SlashCommandGroup):
for cmd in command.walk_commands():
self.add_default_command(cmd)
name = ...
if name is not None:
command.name = name
description = ...
if description is not None:
command.description = description
this is an example so it cant have some mistake its just for u have a little idea of how to do it
for me i have done a file lang.py that have an instance to do all the traduction throught my bot etc and then in my bot client i have a setup_hook that will trigger those function
recursion
yeah its for handle the sub command and sub sub command
i think im the only one using pycord that use a setup_hook
what does the library does for me ?
the setup hook ?
adding commands etc...
why?
because i dont want to do for each single command
name =
description =
name_locazliation =
for each single options of each single command
when i can just do a function and then never touch about that
because why not? its literaly right there
why write extra code that does nothing but complicate existing features
but you still need to put the descriptions somewhere
you write the same amount
nope
plus the code of whatever that mess is
@subcommand("bot")
@commands.slash_command()
@discord.option(name="test", type=str, required=True)
async def test(self, ctx: LumabotContext, test: str):
await ctx.respond(ctx.translator.bot.test.success.format(test=test))
its just like that
and then i have a yaml file which each thing
@subcommand("bot")
@commands.slash_command(name = "test", description = "test", name_localization = {"fr": "test", description_localization = {"fr":"test"})
@discord.option(name="test"name = "test", description = "test", name_localization = {"fr": "test", description_localization = {"fr":"test"}), type=str, required=True)
async def test(self, ctx: LumabotContext, test: str):
await ctx.respond(ctx.translator.bot.test.success.format(test=test))
no way im doing that
so instead of just writing the localizations where they belong, you write them somewhere else, and then write a whole bunch of extra code just to put the localizations where they belong
to do the multilang i already need to use yaml file
so im actually coding less
why
and by doing like so
every single localization is set
no need to do anything else
you can remove the "" at the text
i know i can but i like to put it
idk why but its stress me without it
and also i will need to do \'
and i also find that 100 times more messy
but why do you need to use a yaml
like this is simple nothing to do
how would i do to put each languages ?
with a dict? lol
you literally already did
just add more languages lol
im not doing that
im doing that
where is there dict here ?
here..
there is no need to use a yaml
i say i dont want to do that
because it take more time
and also
but you said you need a yaml
yes for the reponse in the embed
how would i do there to send the good lang
instead of this :
await ctx.respond(ctx.translator.bot.test.success.format(test=test))
if you have a better way than that :
@subcommand("bot")
@commands.slash_command()
@discord.option(name="test", type=str, required=True)
async def test(self, ctx: LumabotContext, test: str):
await ctx.respond(ctx.translator.bot.test.success.format(test=test))
im listening, im always open to new idea ;)
(ik for the requiered = true but i like letting them)
It's possible to send few messages with 'for' with interact buttons, for example, 3 messages with same buttons when clicked, the context of the message to which the buttons are attached will be sent
Or its will be broken?
M1: content 1
Button answer: content 1
M3: context 3
Button answer: 3
yes
How I can do that for example?
my usage example should be like this:
/players_list
[Message1]
(Button)<User ID>(Button)<delete>
. . .
[Message22]
(Button)<User ID>(Button)<delete>
End of list
How to get slash commands ID?
all the commands of your bot?
No just one command
You can use get_application_command() of the Bot object
Also how can I make a command humans only
Like I have a on_message_edit event
And many bots are triggering it
I only want humans to trigger it
How can I do it
Other bots activate the commands?
you have to check it if its a bot or not
check message.author.bot... but only humans can trigger slash commands anyway, unless you're talking about prefix commands or something else in messages
they said on message edit
how I can stop everlasting "is thinking"? I want after 5 seconds output message
You respond to the interaction ?..
I didn't quite understand your surprise
If you defer, you then have to respond as you always do
Defer isn't a replacement
I don't quite understand what's your question exactly
That is, if there is a defer, then I will always have to respond?
You must always respond
Defer is not a replacement.
If you do not respond, itll just stay as "bot is thinking..." until it times out after 15 minutes.
I connect to the socket, and if the connection failed, then it returns nothing and thinks everlasting
Well, yes? If your bot goes down while processing the command then it'll just stay in that thinking state
I don't get what your exact issue here is?
Okay, it doesn't matter, I'll solve my problem in practice
How can I get a certain message with id? Because if I give '.get_message' id of an existing message that was sent when the bot was offline, I get None while if it's a message that was sent when the bot is online, it finds it without a problem. How to find the message as this probably just searches through cached messages?
for what use case
When I'm using a command, the bot sends a message and I want it to delete the one that he sent when the command was used last time
always in the exact same channel?
That's the case, I want it to work with any channel, otherwise I would probably just search through channel history and I'm thinking of an easier solution
well it depends
if you want the message to exist only once per channel you probably wanna use a db to store the channel id, to then get the channel, to then fetch the message
if you want the message to exist once globally then its probably fine to just make a single json file with the channel id saved in it
already did that, as I said it before, the problem is with finding that message
bc if the bot didn't cache it, the 'get_message' method will return None
ah, so you do store the channel id?
wait, you meant both, channel and message id
damn, can't read
:>
thanks
If you just want access to a message's API calls without any of its content, use channel.get_partial_message; it supports both edit and delete
okay, thanks :D
what's the benefit over just get_message
get_message relies on cache
oh, get_partial_message just creates a fake object to be sent to the API or
Well yeah, because it only needs the ids
yea ok, good to know
Is it ok to have an empty string as the author name in an embed?
does it work for you? then yes
why does guild.get_member return None?
no member intent usually
will check it, ty
.tag get_x
Any function that starts with get_ in Py-cord is retrieving the related object from your bots cache. If the object is not in the bots cache the get_ method will return None. Because of this behavior you should check if the get_x method is None and if it is use the fetch_x method.
Why Is Using fetch_ Without Using get_ First Bad?
The fetch_ method makes a call to the discord API. This API call is unneeded if you already have the information. It will also make your command take longer because it will have to send and than wait for a response from the discord API. It will also contribute to the discord APIs global rate limit of 50 requests per second.
What Is Cache?
The cache is a temporary storage inside your bot. It holds many objects from members to messages. When you restart your bot the cache will be empty. When the cache is full it will delete older objects to make space for the new objects.
get member should never fail as long as the member is in the guild and member intents are there, though
in this case it was missing intent
but still thanks for all that info
Is there any way to disable formatting in embed.description? the descriptions im working with have "```" a lot of times and it messes up the looks of the output
and nope i cannot edit the content of description by placing backslashes
why not?
one thing i didnt wanna do lol
why?
too slow for large files
but yeah if theres no way to disable it then i guess ill just live with it thanks for the help
Eh..?
Embed descriptions arent thousands of characters
and string manipulation is so fast
makes sense in the real world but after getting into leetcode i cannot convince myself to traverse the entire string over a mild inconvinience
its one line of code lol
wont be able to live with myself π π
embed.description = content.replace()
you donβt need to edit the file in itself
how to change my bot profile pic in a single server?
Its possible to update bot status every 15 seconds from @task.loop in another file? I just need to take out a function that updates the status to another file, but a nonetype error appears there
show your code
not possible
@bot.event
async def on_ready():
print(f"{bot.user.display_name} is ready and online!")
channel = bot.get_channel(1243993814419636278)
await channel.send(f"***{bot.user.display_name} - Online!*** :white_check_mark:", delete_after=3)
update_counter.start()
@tasks.loop()
async def update_counter():
headers = {
'User-Agent': config.user_description
}
ulr = 'https://vrchat.com/api/1/visits'
response = requests.get(ulr, headers=headers)
if response.status_code == 200:
current_online = response.text
activity = discord.Activity(type=discord.ActivityType.streaming, name=f'VRC Online: {current_online}!', url="https://twitch.tv/vrchat")
await bot.change_presence(activity = activity)
else:
print("Error fetching status", response.status_code, response.text)
await asyncio.sleep(15)
- Don't use requests
- You're missing the interval
Why about requests
this is the working code at the moment, but when I do the same thing in another file so that it just runs here, it will get the change_presence error
It's not an async library and it blocks your running code
Because you're probably missing the bot object. You have to use a cog or probably pass the bot object
What I can use then for api requests, most of functions its api requests
You use asyncio
Or httpio or something like that which is more closer to the requests library but async
?tag requests
Why you should not use the requests library for your bot
requests is a popular HTTP library for Python. It is however not a good option for Discord bots, since it is not async and blocking.
This essentially means that your bot will not be able to execute any code at all while a request is happening. Since requests usually take a few seconds to complete, this can have a detrimental effect on your bot's performance. E.g if a user executes a command that performs a request taking 5 seconds to complete, no one else will be able to use your bot for those 5 seconds.
Please look at using a HTTP library that has async support, such as aiohttp or httpx
Wow, thanks, I will know that now
You should not put update_counter.start() in on_ready as it is possible for on_ready to run multiple times (IE when your bot reconnects after losing connection) Instead you can start the task before bot.run and use await bot.wait_until_ready() as the first line in the task callback.
Also use aiohttp as py-cord uses it so it is already installed
Oki Doki ill try, also I have another question I know about defer, but is there another way to bypass 3 seconds of timeout? Sometimes api answer a bit longer then 3 second
Nope. Defer is the only way to extend the timeout for interactions. Why does defer not work in your case?
Im not sure, close vs for now, but I get errors like interaction already called if I adding defer
When you defer that counts as a "response" to the interaction so you need to use interaction.followup or ctx.followup after deferring. If you are sending messages in a slash command you can use ctx.respond(...) and it will choose automatically for you
If even the defer is failing, that's your network
what is timeout time with defer?
15 minutes
well, that's definitely enough for me, I don't think it will take me 15 minutes for 2 requests with json data
Haha
Definitely not lol
I meant that if you can't defer under 3 seconds, it's definitely your network
Maybe you right too, because sometimes its working fast, about 1.4+- s to respond
is the defer the first statement?
Any inbuilt method to save discord.Attachment locally to the specified path?
oh yeah i saw that but couldnt figure out the use
bot.save(file) doesnt work, neither does ctx.save
How to get channel id in which a message was sent?
@errant trout
Can you help pls
it's an async function Attachment.save
go on
@bot.event
async def on_message(modmessage):
channel_id_modmail = 12394748474744
reaction = 'β
'
if modmessage.channel.id == None:
chl = bot.get_channel(channel_id_modmail)
await modmessage.add_reaction(reaction)
embed = discord.Embed(title='Are you sure you want to send this modmail?',description=f'Your message- `{modmessage.content}`')
modmessage.send(embed=embed)
@bot.event
async def on_reaction_add(reaction,modmessage):
await modmessage.send('ok')
Nothing is being sent to me for some reason @errant trout
All intents are fine
Cuz that's a dm
Dm has no channel id
So it should be
if message.guild.id == None
??
no, just message.guild
otherwise that would raise an error in DMs
you can just do if not message.guild
So
Like this?
if not message.guild:
...
yeah
Ohk
OH so it's Attachment.save and not the variable that I stored the attachment in?
no, it is the variable
like, if you called it file then literally await file.save(path)
@bot.event
async def on_message(modmessage):
channel_id_modmail = 1247498881818951700
reaction = 'β
'
if not modmessage.guild:
chl = bot.get_channel(channel_id_modmail)
# Add a reaction to the user's message
await modmessage.add_reaction(reaction)
# Send a confirmation embed (only if it hasn't been sent before)
confirmation_msg = await modmessage.channel.history().find(lambda m: m.author == bot.user and m.embeds)
if not confirmation_msg:
embed = discord.Embed(title='Are you sure you want to send this modmail?', description=f'Your message: `{modmessage.content}`')
await modmessage.channel.send(embed=embed)
await confirmation_msg.add_reaction(reaction)
@bot.event
async def on_reaction_add(reaction, user):
if user != bot.user:
if reaction.emoji == 'β
':
# Get the original message that was reacted to
original_message = reaction.message
# Your code to handle the confirmed modmail here
await original_message.channel.send(f'Confirmed: {original_message.content}')
This code should add the reaction to only the message but it's adding the reaction to the bot message aswell. And the event of on reaction add is working for th bot message too can u help @errant trout
@errant trout i gotta go can u help me fast pls π
well
What's the error?
the 2nd last line?
so remove the await confirmation_msg.add_reaction(reaction)
this will add the regaction to the confirmation message
so not only to the modmail message
well..you have it set to react on every message
just check the user before using add_reaction
Hello! Some of my people have troubles with button callbacks. Sometimes when button is getting disabled and the message is updated all buttons just disappear. Any ideas? The chances of this happening is pretty rare and right now we're trying to understand why exactly does this happen. Any Ideas on this? If you need any info just tell me, I will ask them and respond to you this evening
are you using disable on timeout ?
Basically, we're just calling View.disable_all_items and updating the view via interaction.response.edit_message()
because im using that and im facing the this issue, the view is disappearing sometime
The timeout for view is set to None
That's what I'm saying. I tried browsing github issues about this but couldn't find anything
are you passing the view each time with view = ...
Yes: interaction.response.edit_message(view=view)
And right before: view.disable_all_items(). Maybe some logic in between but nothing related to the view itself
so i think there is a small chance where discord remove a view if everything is timeout
because im not using disable_all_items, and i got that also using the disable_on_timeout
but not everytime
If everything is timeout?
if everything i timeout / disabled
When did this started happening to you?
i think it has always been the case when using disable_on_timeout
so i will say more than 6 month
but i think is not a bug from py-cord but from the library that removed it
i think
Alright. Hope they will fix it soon
im not so sure about it
since it has been 6 month i think no one really know why its happening
Yeah, we cant fix it unless we can track down the problem and no one has found it yet.
and not even sure we can even if we know cos that can come from discord
i doubt it's a discord issue tbh
if you wanna fix it, mess with the default View.on_timeout code and see if it's possible to prevent https://github.com/Pycord-Development/pycord/blob/master/discord/ui/view.py#L364
Donyou think it can come from the on_timeout even with the disabled all item ?
And the issue is that doesnβt appear everytime so it will be harder to guess but if it can only come from this one I think
I will try to change it a title bit to see
If the issue is caused by disable_on_timeout, then the code I linked is where the problem is
It's not a problem I've ever encountered, so ultimately i can't really test it
not only, ΠΠ½Π΄ΡΠ΅ΠΉ experience also it using disable_all_item and edit the message
This started happening recently, anyone ever come across this or at least can understand what might be happening here?
ERROR:asyncio:Task was destroyed but it is pending!
task: <Task pending name='pycord: on_ready' coro=<Client._run_event() running at [...]/python3.10/site-packages/discord/client.py:400> wait_for=<_GatheringFuture pending cb=[Task.task_wakeup()]>>
pycord
yeah it was happening for me as well, I saw there what a issue raised on git about it
I had to remove one coroutine from on_ready where I init the database connections
Oh sweet, thanks for the reply. Any chance you have a link? I tried doing a couple of searches and didn't come up with anything that matched this issue.
it happens for more than juste on_ready
Do you got any blocking func?
Or librarys?
Ah. Okay, it's "The Bug". Thanks.
Not that I'm aware of. I am forcing a non-async library (pycognito) into an executor, but that doesn't use on_ready
This is also 2.5
got that same issue with on_message using an async library to get the message by doing some trick (running async function for the message which should be def)
yeah a fiew people got the same issue, I think the cause is a bit hard to find tho π
But I wonder which Version did you use?
version doesnt change anything in this case
Why requests and aiohttp do they give me different responses?
how can I get the same answer through aiohttp as in requests
?
For example,
import requests response.text giving me text
Import aiohttp response.text() giving me another text that not similar what I getting in requests library
I used to get certain lines from the server response, for example DisplayName, but I can't do this in the aiohttp library because I get another response where these lines are not present
although I send all the data to the request the same
What is the best way to make my slash command responses in multiple languages? With a json file?
or yaml or a simple text file with your own decoder
itβs really up to you
I would use a json or yaml file
personally I would try to build a language thing by yourself for fun
yaml is more easy to write into it and then you can convert it into dict likens on
Json
Is there a good explanation for this?
About why itβs easier to write in a yaml ?
Just the format like you donβt need to mind about {}
Okay. Yes, I meant whether there is an example somewhere where you can see how to implement it in the code structure.
How to implemente it really depend about u, I can tell u what Iβm doing if u want but itβs I think kinda advanced
How to check if message has view attached to it or not?
I've seen the View.from_message() method that constructs new view from message but I'm kind of hesitant to use it. I only need to know if the view is present or not
message.components
Thanks!
How to fetch a discord message? In docs, bot.get_message() method does not do an API call to fetch the message and there is no bot.fetch_message() method that could've helped me
channel.fetch_message()
I currently have it this way, but I may be looking for another method, as I often get an error with my current method (see pictures). As can be seen in the last screenshot, for example.
You should use handle the case with a default language
with else : load_translation(default)
For me Iβm doing like that :
ctx.translator.bot.test.name
To get for example the name for the test command in the bot group
when the bot joins a server, the language is automatically set to english. that's why i always thought it didn't matter.
https://max1385.no-friends.xyz/Code_zI7j5yiAgT.png
Handle the case
If the bot is off, or it bug
Or any reason
It will not work so just handle it will a English yaml for example
https://max1385.no-friends.xyz/Code_RvnxvDeJ8x.png
https://max1385.no-friends.xyz/Code_6TozLbQGZ8.png
I have all the english translations in there.
I mean, it doesn't matter which language it loads. when the bot joins the server, every server gets the language english by default. so the bot then calls up the language english with a command or german.
if in ur database there is no result spit will not work
so yeah it matter to put a default thing with the else
and that ur issue
i'll have a quick look to see if a language has been defined in the database for the server when executing the command.
man itβs if language data and, so if there is not result which can occur when the bot is off, it will not work
just do an else language = βenglishβ
itβs 2 lines and will handle all ur issue
So you think that will solve my error?
I donβt think Iβm sure
Since the if is not trigger
The language = is not set
So language is not associated with a value
The error does not occur when a command is executed on a server I think
Since there would be a guild id in my error report I guess
because it depend if the thing is in the database
if a guild has beeen joined and the bot didnβt add it for any reason like offline a bug or else
the guild will not be able to do command
well i have told u how to solve it, if u donβt want to listen i canβt do anything im sorry
no, all good, i recognize your point of view and appreciate it. i just checked mongodb and yes, i only have 7 entries for languages although i have 9 servers on the bot.
I think the keyword there is "Temporary" It might just be discord or your internet provider or something in between is having troubles
If it still does not work after 10min than it might be something else but you should be able to just wait a few minutes
Is it working now?
the DNS is having issues
so whatever DNS you use was dead for a sec
or as wolfy said the entire internet but I'm pretty sure that would be a different error
How would I go about checking a purge both for the user and a specific string in the message?
I have the user (the bot) working so far:
def is_me(m):
return m.author == bot.user
channel = bot.get_channel(xxx)
await channel.purge(check=is_me, before=ctx.interaction)
Thanks in advance π
def check(m):
return m.author == bot.user and "abc" in m.content
Oh duh thanks.
can i add bridge command in cog
@lapis dock
..
Here's the bridge commands example.
is there a native way to do
nsfw_group = discord.SlashCommandGroup(name="nsfw", guild_only=True, checks=[discord.is_nsfw()])
using checks
for the command appear in the list of / but will not run if its not a nsfw channel
You mean with checks on command use
This one already work with guild_only = true in it
NSFW = true was working but not showing the command
But I will try command. Nsfw
Is the command marked as nsfw? Checks should not effect what commands show up in the list
i still not tried the check=
what?
Also I might be wrong but I think it is discord policy that nsfw commands are not to be shown except for in nsfw channels. What you are doing might be against the policy
oooo i wasnt knowing that
thanks i will correct that
I am trying to check to see if it is actually true, I just remember something like that a while ago
Prohibited behaviors and activities include those that:
- Distribute adult content to users under the age of 18, and without age-restricted labels where applicable and appropriate to users 18 and older;
- Unless your Application is labeled as age-restricted, you will make sure your Application is appropriate for users under the age of eighteen (18) and complies with all applicable laws (including those applicable to users under the age of eighteen (18)).
So it is still, on the line. I think in general it would be safer to just hide them in non nsfw channels
The commands need to be marked nsfw anyways. And discord might autohide based on that fact
idk if you ever want your bot verified, but making it as "clean" as possible will help a lot. From what I can tell is that they will deny off of any little thing that they deem wrong
is there a way to set modal input can only filled by integer? so if contains non integer then the placeholder will be red
like how slash commands options do
str only
you would have to check it at your own
i just had a ping here, what
how to get the guild of on_member_join event?
with the member object
;3
docs = friend
^
.rtfm Member.guild
.rtfm discord.Interaction
discord.Interaction
discord.Interaction.app_permissions
discord.Interaction.application_id
discord.Interaction.channel
discord.Interaction.channel_id
discord.Interaction.client
discord.Interaction.custom_id
discord.Interaction.data
discord.Interaction.delete_original_message
discord.Interaction.delete_original_response
discord.Interaction.edit_original_message
discord.Interaction.edit_original_response
discord.Interaction.followup
discord.Interaction.guild
discord.Interaction.guild_id
discord.Interaction.guild_locale
discord.Interaction.id
discord.Interaction.is_command
discord.Interaction.is_component
discord.Interaction.locale
I am not sure I understand the difference between these 2 slash commands decorator
from discord.commands import slash_command
from discord import slash_command
Does anyone know the difference ?
Hmmm, in the repository examples, the commands.slash_command() decorator is used in Cogs. But I'm not sure, and the slash_command() decorator is used outside of Cogs.
If I'm wrong, someone correct me. 
It depend if you are using discord.Bot or commands.Bot si only / or also prefix
Not totally true
I am using from discord import AutoShardedBot
So i think itβs discord.slash_command()
I see because both of them seem to be working without any problem
so not sure if they are the same
or which one I should use over the other
I think they refer to the same thing at the end, it depend of the bot.command() at the end which is different
But normally itβs discord.slash_command if u are using discord.Bot
Because with commands.Bot it can either be commands.commands or commands.slash_commands
And I think you can even but discord.command() with discord.Bot
I see I will stick with them in that case ! Thank you
How do you wait for a button press, just like how you wait for reaction_add
you dont
is it not possible?
So given a situation where you have to find out when a user clicks on a button sent by another bot, you can't find out that right
yes the bot cant know if a user click on a button
also the case for any view
Hi, my bot takes ~10 min to fetch data from multiple endpoints (I'm using requests). After 6-7 minutes the bot goes offline (on Discord, the script still runs) and then comes back with the answer automatically.
Why is it so?
Donβt use requests
Request is not asynchronous so because of that it blocked ur whole bot for 7min
.tag norequests
Why you should not use the requests library for your bot
requests is a popular HTTP library for Python. It is however not a good option for Discord bots, since it is not async and blocking.
This essentially means that your bot will not be able to execute any code at all while a request is happening. Since requests usually take a few seconds to complete, this can have a detrimental effect on your bot's performance. E.g if a user executes a command that performs a request taking 5 seconds to complete, no one else will be able to use your bot for those 5 seconds.
Please look at using a HTTP library that has async support, such as aiohttp or httpx
where is the docs for this thing
you've bot answers for everything π where is it stored I'll ctrl+F
there is not really doc about it, like in the doc it just prevents to use only async function (await)
im doing my best to help ;ββββ)β, it also help me to improve my code ;)
no no, you have @sly karma with common FAQs, where is this FAQ stored
about all the tags, you can do .tags in commands
.tag
alias - None
info - View info for a tag
edit - Edit a tag
delete - None
add - None
search - None
with a s
With helps
is there a limit to how many commands my bot can have ?
Ignoring exception in on_connect
Traceback (most recent call last):
File "C:\Users\SOHAM\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\client.py", line 400, in _run_event
await coro(*args, **kwargs)
File "C:\Users\SOHAM\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\bot.py", line 1178, in on_connect
await self.sync_commands()
File "C:\Users\SOHAM\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\bot.py", line 735, in sync_commands
registered_commands = await self.register_commands(
File "C:\Users\SOHAM\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\bot.py", line 599, in register_commands
registered = await register("bulk", data, _log=False)
File "C:\Users\SOHAM\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\http.py", line 373, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 30032): Maximum number of application commands reached (100).
i got this wierd error
You reached the slash command limit
sad, then i create subgroups that should work
Yes
for cogs can u share me an example
Here's the slash cog groups example.
thank you
well any idea how to mention the subgroup channels ?
we cant
options are being screwy
AttributeError: Option does not take min_value or max_value if not of type SlashCommandOptionType.integer or SlashCommandOptionType.number
note that this is on an option that declares that it's an integer
Check to make sure date.today().year is returning an integer.
and yes i'm using from discord import SlashCommandOptionType for the typings
that same error happens on each thing that uses type number
Can you show use the code ?
here
Can you try to put only int
i just did that and its even weirder
Did u try wifh the decorator ?
ik
its input_type
wolfy is too fast for me
type is only using option not Option
So it was defaulting to str and ignoring whatever you put in type
replacing type= with input_type= seems to return the same error
is it better if i just forego defining types
you can use decorator
will try
Did you replace it on all of the options? Or is it still erroring on added year?
all options
But the same exact error?
Traceback (most recent call last):
File "C:\Users\mrmax\PycharmProjects\FE2TimerBot\.venv\Lib\site-packages\discord\cog.py", line 778, in _load_from_module_spec
spec.loader.exec_module(lib) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<frozen importlib._bootstrap_external>", line 995, in exec_module
File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed
File "C:\Users\mrmax\PycharmProjects\FE2TimerBot\cogs\maps\maps.py", line 43, in <module>
class Maps(commands.Cog):
File "C:\Users\mrmax\PycharmProjects\FE2TimerBot\cogs\maps\maps.py", line 69, in Maps
normal_buttons: discord.Option(input_type=SlashCommandOptionType.integer,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\mrmax\PycharmProjects\FE2TimerBot\.venv\Lib\site-packages\discord\commands\options.py", line 297, in __init__
raise TypeError(
TypeError: Expected <class 'NoneType'> for min_value, got "int"
ye
can you try int ?
current version and the original one from first ghostbin
might want to correct tabbing lol
na its fine
just your IDE doesnt like it
your first option has input_input_type sub i doubt that is the issue for the current error
masterful gambit on my part
odd that it doesnt cause an error tho
i also tried the option decorator
that throws a whole new error
well
first
min value cant be 0
2nd
2024-06-07 18:27:55 [WARNING] : Failed to load extension Slashs.Bot.test: Extension 'Slashs.Bot.test' raised an error: AttributeError: Option does not take min_value or max_value if not of type SlashCommandOptionType.integer or SlashCommandOptionType.number
yeah thats the same error i was getting
i think there is some issue with typing using Option
is it still happening if you just do int?
also it not being able to be 0 is a weird limitation
let me try with my decorator
yeah its what i tried
yep
i also just converted everything to decorator
can you try it with discord.option?
just send a screenshot
of the code or the traceback
I think if you specify a type with input_type= you have to use SlashCommandOptionType if you want to pass int just pass it positionally.
what decorator code did you use?
discord.option
@commands.slash_command()
@discord.option(name="name", description="Name of the map", type=str, required=True)
@discord.option(name="mappers", description="Comma separated list of map creators/contributors", type=str, required=True)
@discord.option(name="addition_month", description="What month was the map added to FE2?", choices=['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], required=True)
@discord.option(name="highlight", description="Is the map a highlighted map?", type=bool, required=True)
@discord.option(name="normal_buttons", description="Amount of normal buttons in a map", type=int, min_value=0, required=True)
@discord.option(name="group_buttons", description="Amount of group buttons in a map", type=int, min_value=0, required=True)
@discord.option(name="thumbnail", description="Link to a picture of the map", type=str, required=True)
async def add_map(self, ctx: discord.ApplicationContext, name: str, mappers: str, addition_month: str, highlight: bool, normal_buttons: int, group_buttons: int, thumbnail: str):
await ctx.respond('Almost done! Please select the events that the map supports using the menu below.')
you can remove the type= stuff, you already do it at the async def name()
you made me learn something thanks
oddly enough this works but the code i had doesn't, this is weird as hell
i need to see a diff of these two hold on
i think i will let it,
@subcommand("bot")
@commands.slash_command()
@discord.option(name="test", required=True)
async def test(self, ctx: LumabotContext, test: str):
this doesnt look great
ohhhh wait
is this in a cog or no
because you use @commands.slash_command() while mine uses @discord.slash_command()
and yours worked
actually wait it still bugs if i change that in my code
hm
that doesnt change anything
just im using prefix + the other
yea i tried and nothing changed
does ur code still have issue
@little cobalt thanks because of you i can even remove the decorator completly.
uhhh, I found the answer
Remember when I said use input_type, you just are not supposed to have anything there at all
Option(int, ...) aparently input_type is positional only. You cannot use it as a kwarg.
...
buh
so the first comma of each option regardless of decorator or not
should always be the SlashCommandOptionType?
or the int
or whatever else
not sure about decorator, but for useing discord.Option yes
That does not matter, either works
im gonna give the same thing a shot for decorator then one sec
So in theory if you remove input_type= from all the options in maps.py from this message it should work.
i'll give it a shot
well the bot loads but it throws this instead, giving current vers of maps.py
Ignoring exception in on_connect
Traceback (most recent call last):
File "C:\Users\mrmax\PycharmProjects\FE2TimerBot\.venv\Lib\site-packages\discord\client.py", line 400, in _run_event
await coro(*args, **kwargs)
File "C:\Users\mrmax\PycharmProjects\FE2TimerBot\.venv\Lib\site-packages\discord\bot.py", line 1178, in on_connect
await self.sync_commands()
File "C:\Users\mrmax\PycharmProjects\FE2TimerBot\.venv\Lib\site-packages\discord\bot.py", line 754, in sync_commands
app_cmds = await self.register_commands(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\mrmax\PycharmProjects\FE2TimerBot\.venv\Lib\site-packages\discord\bot.py", line 599, in register_commands
registered = await register("bulk", data, _log=False)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\mrmax\PycharmProjects\FE2TimerBot\.venv\Lib\site-packages\discord\http.py", line 373, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In 1.options.7: Required options must be placed before non-required options
In 1.options.8: Required options must be placed before non-required options
In 1.options.9: Required options must be placed before non-required options
plagued by horrors
That is just a discord limitation
how much is positional?
wdym?
everything in this is required tho
like all the options have required=True
and its throwing the error on the last 3 options
oh, 
yeahhhhhh
i feel that
hmmm
the only significant differences in the last 4 are that max time uses default, and all 3 of those number/int requiring options do not use max_value
so what happens if i add a max value
WHAT
IT FUCKING WORKS WHEN I REMOVE DEFAULT
bro
Oh yeah, default forces it to be non-required
you never need required=True btw
ahhhhhhhhhhhhhhhhhhhhhhhh
some poeple like it for clarity tho
float values suck for options btw
from a user perspective
Because it depends on the client locale on whether you use . or , as the decimal point
horror.
i can probably do away with it for max_time but im basically required to use it for the difficulty one, because the game i'm building the bot for utilizes a decimal difficulty system
then agani
oh wait yeah this is gonna be fun later on
oh well, later me's problem
again, thank you all sm
np
and if thats minutes, btw, decimals really dont make much sense
unless you really wanna make sure that something runs half a minute longer
just doing it because some maps have previously used max times with .500 or simila
im the only one using this command anyhow so
its not too bad
i hope you mean discord.Option
i hope you stub your toe
(im using it only for the choices)
?
discord.Option gang π―
oh also wait one quick question
when you use a view, how does the original command that creates the view actually use the data from the view
like discord.option is not useful in my case since the only thing that i cant pass directly in the func is choices, max_value and min_value. And since im not using max and min value i need it only for the choices
you can use await View.wait() and then access the views attributes but generally you are able to "use" all you need in the callback of the component.
well i made this, the reply it gives to selecting stuff is from the callback, but is it possible for the slash command to see the selections or no
see wolfy's message
ah i see
so just for clarification, am i able to get this block of data in the view's callback?
and if so how
docs are a bit confusing
holy shit
congratulations, i have never before seen a command with that many options, and that total length
nah i got more, so give me the title
no
:3
eh i'm still kinda toying with ideas and seeing what works best
I wanted to say "use modals" but i forgot discord never made modals anywhere near useful
But yeah, you have to pass it to the view
@subcommand(f"stats setup")
@commands.slash_command()
@discord.option(name="mode", type=str, choices=["enable", "disable"], default=True, required=False)
async def add(self, ctx: LumabotContext, role: discord.Role, mode: str, time: str = None, voice: str = None, message: int = None, mandatory: discord.Role = None, forbidden: discord.Role = None):
but its not a competition
ok so when passing things to the view, just dropping them all in the view=Events() works?
if your __init__ makes use of them
its just basic OOP, not complicated
ye, just realized that and now i feel fine again
also i will say, the only other idea i had for getting around this was starting like a back and forth conversation between the bot and the user, where the user just has to keep using replies so i dont have to apply for message content intent
both are lengthy either way though
I think the command is a better option. In reality this is not something you will be doing very often so its ok if it is long. If you are on PC there will be no issues
mobile it might be hard to see but oh well
mhm
and im the only one doing this command
and on pc so
definitely reassuring tho ty
@fresh sierra the client._pending_application_commands is working well
and I have to write less code
perfect then !
with that you will need only
@commands.slash_command()
@discord.option(name="kind", choices=["add", "remove", "edit"])
async def channel_rate(self, ctx: LumabotContext, kind: str, channel: discord.TextChannel, rate: float = 1.0):
to put all name, localization, options etc etc
I only use slash_command()
yeah but i mean you can also pass each option name, etc etc
here a part of my yaml if it can help you
yeah but that the same
i mean options, name description choices
also why are you using json and not yaml ? yaml isnt easier to write than json ?
i will never understand why y'all overcomplicate it like this
its not complicated
is actually easier to use it for me like that
and I dont really have to change any code like that
If you had a bot that was performing badly but had no apparent errors aside from interaction failures, how would you go about profiling it?
"performing badly" how
All commands seem to intermittently stop responding, games etc get interaction failed
It's a big, not great codebase and I can't find anything about profiling cogs
I try not to but there's definitely stuff like that going on that I am unaware of or forgot
Yeah, tons, I try to use async for all of that
That'd be where you'd look first?
do you use anything like requests, time.sleep or a None asyncio DB?
requests yes, only async sleep, and no
requests is gonna block your bot
I didn't consider that, ngl
Well, that's a few good places to start
appreciate it π
.requests
Why you should not use the requests library for your bot
requests is a popular HTTP library for Python. It is however not a good option for Discord bots, since it is not async and blocking.
This essentially means that your bot will not be able to execute any code at all while a request is happening. Since requests usually take a few seconds to complete, this can have a detrimental effect on your bot's performance. E.g if a user executes a command that performs a request taking 5 seconds to complete, no one else will be able to use your bot for those 5 seconds.
Please look at using a HTTP library that has async support, such as aiohttp or httpx
@bot.event
async def on_message(message):
if message.author == bot.user:
return
if message.content.lower() == "bien":
await message.channel.send("mercii!!")```
why is this not working ??
how did you define your bot?
bot = discord.Bot()
.tag idw
Saying it doesn't work or asking what's wrong with this code is not helpful for yourself or others.
Describe what you expect and/or tried (with your code), and what isn't going right.
Please provide any errors you get for optimal assistance.
there's no errors because the code should work and i think i found the solution it's basically intents
probably message_content
it is also at the docs mentioned...
who needs docs when we have chatgpt amirite
how do i get who clicks the button? e.g. interaction.author to mention them?

@warm linden ^^
lowercase
eek >.<
thanks!
.rtfm interactions.defer
Target not found, try again and make sure to check your spelling.
how am i able to remove the "application failed to respond" when it did work though
You're most likely responding incorrectly
Or you're taking more than 3 seconds
should i send the bit of the code?
im using
return await interaction.channel.send(embed=e)
yeah no,
oh
you're supposed to respond to the interaction
you must respond to all interactions
you use interaction.response.send_message
quick one - what if i dont want it to reply to to first messsage
What are you trying to do
just trying to make it send a message in the interaction channel
without it replying to the first message
You can't hide the reply.
You can have a workaround by deffering the interaction and sending the normal message. The defer will "prevent" the interaction from "failing"
Target not found, try again and make sure to check your spelling.
how
It is interaction.response.defer
how comes i have 2 or more buttons in a msg but only 1 of them is showing?
i dont understand you're questions
can you explain the usage for i can better undrstand ?
because if a message has more than 1 button it mean than more than 1 button will be shown, but maybe you mean more than 1 button in ur class but only some in the message, and for that it will depend or the self.add_item. Or maybe you want to refer to the disable optio,ns
Because you're not doing it right
Show your code
if i can tell right from the indentation, your button isn't on the right indentation level
or wait no i think it is
can you show the code where you send the message with the view
just screenshot that part, i hate pastebin ngl
this bit?
the one you sent here is called differently
nah i was testing something out π
interaction.guild isn't working for me no more
lemme quickly give some background - it's a ticket system t
the command i screenshoted send out the public message to click a button and create a private channek
once thats made it send another embed
to close and or claim the ticket
but only one of these buttons are sending
yea, and i asked for the code that is supposed to send the message with this 2 button view
but the one you sent uses a different view
is this what u mean?
yea
now show that message inside discord
await channel.send(f"Hey {interaction.user.mention}, a <@&1088673223996096542> or a member in our <@&1088673224998531225> team will be with you shortly.", embed=support, view=ComSupportOptions())`
wait, do you use Replit?
yes
yeah im trying to fix the interaction.guild bit
bc now its not working
so i cant actually show nothing
bud show the view code
is this part of a command or where is this in
no its not
"or where is this in"
your buttons are named the same thing in your view
its in a differnt class
change the name of one of them
different
oh, i thought the label was the "name" used
that's not how python works
wait to see if it works can i not use interaction.guild?
nothing to do with how python works though
i just misunderstood the decorator then
if the two functions are named the same they override
ahhh
it has everything to do with how py works
yea i thought the decorator would like just eat them and yknow do different stuff with it
man idk
whats not working about interaction.guild?..
guild = interaction.guild
AttributeError: 'Button' object has no attribute 'guild'
you might want to learn python
tbf the order of those parameters is a little random, but yes, it should be clear from the error :>
i coulda sworn it was working yesterday
unless someone came to your room and switched that, no, no it wasnt
the order is self, button, interaction
that
is the order its in
@discord.ui.button(label="Contact Us!", row=0, style=discord.ButtonStyle.success, emoji="βοΈ")
async def button_callback(self, button, interaction):
guild = interaction.guild
i do gotta say though, i dont really like how the self is an explicit argument in python
i just dont like that
i like the java way where you just use this
do you realize you can name it the hell you want?
i mean that its an argument at all in the function header
then you have a library conflict
in java its silently passed
Can you just print discord.__version__
Because d,py uses it the other way around.
@discord.default_permissions(manage_messages=True)
``` can i not do this on a command group because it just doesnt work, it allows users to invoke who doesnt have that permission
show all the decorators, it needs to be in the right place
2.3.2
yea, that's discord.py
yep
yea so fix that lol
OH
@tags.command()
@discord.default_permissions(manage_messages=True)
@commands.guild_only()
@commands.cooldown(1, 2, commands.BucketType.user)```
bot = discord.Bot()
AttributeError: module 'discord' has no attribute 'Bot'
show your pip list
you need to define it in the slashcommandgroup itself i think
you cant further restrict commands in groups i think
thats what im thinking but then i couldnt make it command specific
eh
cause its a group of 3 commands, only two needs manage messages
Well, not possible
figured thanks for the help
because in discord's UI as well, you can only edit the permissions of the main group command
why if i doing view with 6 buttons in main bot file then everything work fine, but in paginator ValueError: item would not fit at row 2 (6 > 5 width)
for the Option type, how can i make the autocomplete grab all the roles in a discord server? like Option(discord.Guild.roles) or something like that
sorry if im being dumb and stupid but im coding after a while
i tried installing py-cord using pip install py-cord as stated on the guide, it says it successfully installed but i cannot import it.
any solution?
check if you also have discord.py installed
i don't
run pip freeze and send an ss
do you use a venv?
yeah chances are vscodes interpreter is using the wrong one?
no
do you get an error at the Terminal if you run the file?
ModuleNotFoundError: No module named 'discord'
did you already restart the IDE?
yes
im trying to use the slash commands in cogs by first starting on the example code: https://guide.pycord.dev/popular-topics/cogs but the slash commands aren't showing up - recieving no errors as well.
- My bot does have application cmds
- Cog has been loaded
Cogs, often known as modules or extensions, are used to organize commands into groups. This is useful
whys this happening?
slash commands are only working for me in main file
its everything on the link but
breh doesnt let me send here
can i use pastebin
yes
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
do you also load the cog in your main file
bot.load_extensions("cogs") if your cogs folder is called, well, cogs
yes
did you restart discord after adding the commands?
yes
i even make bot print the loaded cogs
nd greetings is being loaded
can you send your main bot file too?
also make sure to try /goodbye, the others might not show up depending on your bot definition, and greet is a user command for example, not a slash command
hello works
only the slash cmds
do you really need both slash and prefix commands?
i mean theres jus some commands i want hidden
then change to discord.Bot first of all
and you do that by using the @discord.default_permissions(manage=members=True) decorator under the slash command decorator
ahh thanks man
does this work? @commands.is_owner()
that wont hide the command
but you can add that to hide it + limit execution to yourself
aright bet thanks
you load the cogs at the on_ready event
@sage tendon ^
that is why its not working
ahh
yea i was also confused about that but i thought that was just how it was in the guide
@warm linden why did you use while True at the events?
also why do you have discord webhooks installed?
that already comes with py-cord
i cant?
no
no
oh breh
just add bot.load_extensions('cogs') anywhere before bot.run
can you show the pip list pls? I ask because of your webhook import
and you rarely need webhooks when using bots anyway, so, whats your plan with webhooks
