#Basic Pycord Help (Quick Questions Only)
1 messages · Page 31 of 1
but a slash command's invocation isn't a message
you can't really put any extra args in them either
without having them predefined
?tag message-content
ahhhh i understand. ok i am trying to add an extra message to split from that
you could just add a 3rd catch-all arg which would hopefully work
whats weird about the message being empty is that sometimes it returns the actual message successfully and then at other times just fails
in prefix commands, ctx, *, var works to make the final arg a kwarg which will capture the rest of the message as your variable
don't have message intent enabled on my bot until i saw pycord 5
so theoretically if you did that then in the slash command it would do the same
hate it. now my command is outdated and i have to wait 😄
i think you can just run it again or reload your client
the outdated message is related to your client's command cache, not necessarily on discord's end
ah okay so strg+r reloads it. nice to know
ok works for now. but there is another question. in the prefix command i can edit the message with mess.edit(content="..." ).
Is there a way to do this with the response?
i think you use interaction.edit_original_response
interaction? not ctx?
you get it from ctx.interaction
if it's in a slash command, ctx.edit is the shortcut method for it
is there a way to retrieve the interaction object given its id?
I've been having my bot respond by editing its initial interaction message
but now I want to be able to store the initial messages and access them later
then store the message id
interaction.edit_original_response only works for 15 minutes
ok it´s working now. Thanks @proud mason and @cyan quail 🙂
allgood
I've tried get_message on the original message id but it seems to only return None
interaction.edit_original_response only works for 15 minutes
I guess I should send a proper message then, I can get_message on that right?
get_message isn't ideal because that checks the local cache
which won't persist over restarts and is capped to 1000 messages by default
I'm assuming I have to write my own get_or_fetch for messages?
I know there's a get_or_fetch for users
well there's a universal get_or_fetch but you don't need to unless you definitely need the message content
just get the channel object, then use channel.get_partial_message to generate a PartialMessage object
https://docs.pycord.dev/en/master/api/models.html#discord.TextChannel.get_partial_message
this acts as a way to interact with the message without making an extra API call, assuming you're sure it still exists
https://docs.pycord.dev/en/master/api/data_classes.html#discord.PartialMessage.edit
doesn't look like that worked, I'm going to try with a new message instead of editing the original response to the slash command
@proud pagoda
@vivid plaza don't ghost ping. Really don't ping helpers at all someone will help you when they have time.
Okay Thanks
My slash autocompletes have been working just fine until recently, suddenly now there is the error In data: Field "_choices_type" is required to determine the model type., if I look at https://github.com/Pycord-Development/pycord/blob/master/examples/app_commands/slash_autocomplete.py they also just return an array of strings the same way I do, I am confused pls help
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/slash_autocomplete.py at master · Pycord-Development/pycord
Also the /example autocomplete of the toolkit bot here doesn't work, so I am assuming its a general issue? Did I miss something?
this is giving me Unexpected <class \'TypeError\'>: Object of type File is not JSON serializable
is this me or the library being wrong
images are jpeg images in bytes form
I'm not sure if this is the same issue, but my autocompletes have suddenly stopped working. No code updates on my end. There might be some Discord issue atm?
Task exception was never retrieved
future: <Task finished name='Task-20' coro=<ApplicationCommandMixin.on_application_command_auto_complete.<locals>.callback() done, defined at /Users/tiltowait/Library/Caches/pypoetry/virtualenvs/inconnu-qKm_l4La-py3.10/lib/python3.10/site-packages/discord/bot.py:759> exception=HTTPException('400 Bad Request (error code: 50035): Invalid Form Body\nIn data: Field "_choices_type" is required to determine the model type.')>
Traceback (most recent call last):
File "/Users/tiltowait/Library/Caches/pypoetry/virtualenvs/inconnu-qKm_l4La-py3.10/lib/python3.10/site-packages/discord/bot.py", line 762, in callback
return await command.invoke_autocomplete_callback(ctx)
File "/Users/tiltowait/Library/Caches/pypoetry/virtualenvs/inconnu-qKm_l4La-py3.10/lib/python3.10/site-packages/discord/commands/core.py", line 935, in invoke_autocomplete_callback
return await ctx.interaction.response.send_autocomplete_result(choices=choices)
File "/Users/tiltowait/Library/Caches/pypoetry/virtualenvs/inconnu-qKm_l4La-py3.10/lib/python3.10/site-packages/discord/interactions.py", line 984, in send_autocomplete_result
await self._locked_response(
File "/Users/tiltowait/Library/Caches/pypoetry/virtualenvs/inconnu-qKm_l4La-py3.10/lib/python3.10/site-packages/discord/interactions.py", line 1057, in _locked_response
await coro
File "/Users/tiltowait/Library/Caches/pypoetry/virtualenvs/inconnu-qKm_l4La-py3.10/lib/python3.10/site-packages/discord/webhook/async_.py", line 223, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data: Field "_choices_type" is required to determine the model type.
Yeah exactly the same for me
Hrm
Pycord version?
I'm on 2.2.0, and it looks like 2.2.2 is out (no announcement in #library-updates, though)
I'm on 2.2.0 as well
how can u use a slash command and return an embed?
Still the same error
like this
Same
No, sorry
Why doesn't PartialMessage.edit have a file/files parameter?
Are you sure you have pycord installed and not discord.py?
(And even if you are sure: pip3 install py-cord just to be safe)
Did Autocomplete randomly break for anyone else?
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data: Field "_choices_type" is required to determine the model type.
(Edit: Discussion in #general suggests yes)
I am having an issue where a modal functions correctly, and the callback happens and functions when the button is clicked. But I get an error message in the modal that "something went wrong" and the modal doesn't close
I have gone through the documents and looked at examples, and I can't see what would be causeing the issue.
Update. I have stripped the modal down to the bare minimum, and it still occurrs, but it does not trigger the on_error() code of the modal
discord being discord
oh wth yeah
If you're going to have commands, you need to add from discord.ext import commands and then do bot = commands.Bot()
Which I see you're creating a command.
there is nothing wrong with Spookz’s code
please type pip list and show output
Since when do you not have to import the commands module
if it's only slash commands
since py-cord 2.0a
you don't need it if you use discord.Bot()
So what's the purpose of commands module then
text commands
afaik, events
Eh, okay.
and that
:L
Is it possible to send two images in one embed? Something like this, I know that this is working for some people
I think they combing the 2 into 1 image probably using pillow
https://www.reddit.com/r/discordapp/comments/raz4kl/finally_a_way_to_display_multiple_images_in_an/ There is also this but I believe this is only for discord.js
12 votes and 2 comments so far on Reddit
That's exactly the code for it lol
Idk why it doesnt work for me, im using the latest pycord version and i uninstalled discord.py before
I fixed it
I have a question, I'm not sure if it's a stupid one but: Why use cogs? What advantages do cogs give you?
Is this:
# file 1
bot = commands.Bot()
bot.load_extension('file_2.py')
# file 2
def setup(bot):
bot.add_cog(CogClass(bot))
Better than this in some way?
# file 1
bot = commands.Bot()
# file 2
from file_1 import bot
If there is an advantage I would like to know it to use it properly
so you don't have to have everything in one py file
it helps to organize commands, functions etc to your needs
it is not needed but it helps a lot to keep track of everything
having a 10000+ line file to scroll through every time you make a change is never optimal
I mean, in both examples I use 2 files
yes and i used my own example
But you didn't answer their question lmao
i did
i told them what advantages it gave. not particularly to their example because it was such a niche and bad example
They're asking what's different from using cogs than importing the bot instance themselves
i answered their first two questions
You're right, but... in the context I showed... there is no advantage... it's practically the same
but why would you use the improper one?
one is designed to work multi filed and the other one is not
You can work multi files with both
Why is improper?
yeah but cogs are specifically made to work flawlessly with multiple py files. importing from your main is not meant to be done that way afaik
I mean... python libraries work like that
Kind of a silly question, but what's the preferred way of setting intents?
If I do something like
intents = discord.Intents.default()
intents.members = True
# etc
then the IDE complains about the intents object being read-only. Are there better ways to set these flags?
no. not all work like that. sure, you import the actual library, but you rarely import an instance of an object if an alternative to it exists. use cogs. there are no benefits to not doing so.
I do this
intents = discord.Intents.none()
intents.members = True
intents.guild_reactions = True
intents.guilds = True
intents.guild_messages = True
intents.message_content = True
isn't that basically all? it is not
Right .. I know that works, it's just "wrong" from an IDE standpoint because the object is supposedly read-only.
no clue. i just told pycharm to shut up about it
I mean, internally they work like that
why do you think cogs exist then? go ahead and import all you want. it is improper as you'll have to import it into all files for no reason when a better solution exists. ofc the source code includes it- but that does not mean it is equal to adding to an already existing object. you're not writing a library- you're writing a bot with a library that have a built-in handler to make multi-file managing easier. do whatever tf u want but you're wrong in that it is equal just because a library imports its modules (ofc it does; that is not the same as you importing an object from that library as opposed to using the appropriate object builder)
"omg the library uses import, therefore i should use it too instead of making my life so much simpler", give me one reason for why you choose to die arguing over this rather than using cogs? is it that horrible to use it?
intents = discord.Intents(guild_messages = True, etc...)
is my way for pycharm to stop screaming
I'm not fighting, I want to know what advantages the way you think it's better have and... I don't see the advantage, I just see that they're practically the same
cogs can be dynamically (re/un)loaded
literally worth it
Now, that is a good reason, and a difference
also now you can brag to your friends you use oop
Are you spying me? The programming friends I have, literally program in C++
.... maybe
isn't c++ somewhat oop?
Yes... I got confused, in fact now that I see the c++ syntax it's not even the same, and I only remembered #include <stdio.h>
probably for usaco
Stupid python question
def ret_tuple():
return 'a', 'b'
a, b = ret_tuple()
# 'a' 'b'
This works. But
if (a, b := ret_tuple()):
print(a, b)
does not..? It stuffs the entire tuple into b
Edit: Apparently a known limitation of unpacking with the "walrus" operator. Womp womp
TypeError: on_ready() missing 1 required positional argument: 'self'
@bot.event
async def on_ready(self):
if not self.persistent_views_added:
self.add_view(TicketCreateView())
self.persistent_views_added = True
setattr(bot, "db", await aiosqlite.connect("infinity.db"))
bot.db = await aiosqlite.connect("infinity.db")
await asyncio.sleep(3)
async with bot.db.cursor() as cursor:
await cursor.execute("CREATE TABLE IF NOT EXISTS warns (user INTEGER, reason TEXT, time INTEGER, guild INTEGER, id TEXT)")
print("Bot is ready!")
in main.py
If you are in the main why do you use self?
for self.persistant_views_added
?
how do i do it without self
self is a parameter used in classes to represent the object itself, if you want to refer to the client use the variable in which you instantiate it (e.g. bot).
oh
ty
does ctx.message return the updated msg if i edited the msg before
or it only sends the original msg
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components.0.components.0: Value of field "type" must be one of (2, 3, 5, 6, 7, 8).
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord/bot.py", line 997, in invoke_application_command
await ctx.command.invoke(ctx)
File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 359, in invoke
await injected(ctx)
File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 135, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components.0.components.0: Value of field "type" must be one of (2, 3, 5, 6, 7, 8).
with
class FeedbackModal(discord.ui.Modal):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
# self.add_item(discord.ui.InputText(label="Short Input"))
self.add_item(discord.ui.InputText(label="Long Input", style=discord.InputTextStyle.long))
async def callback(self, interaction: discord.Interaction):
con = sqlite3.connect('./data/data.db')
cursor = con.cursor()
cursor.execute(f"INSERT INTO suggestions VALUES ({interaction.user.id}, {interaction.message.id}, {interaction.data['values'][0]})")
You want to add errors? You should be using C++
Bruh. No one need use c++ LOL?
r/wooooosh
anyone?
How do you add a description to an argument?
wdym?
As in adding a description to a part of a command like:
/command this:
How do I add callback script to view.add_item(button)?
When someone clicks the button
um
Wut
button = Button(label="Hi")
async def callback(interaction):

but the guide doesn't show how to create dynamically created buttons
only static buttons
what
idk what's the difference in that
huh

I guess I can override the interaction_check function
for example if I want to show different amount of buttons each time the command is run
with different labels, emojis and colors
Oh
u mean random stuff?
yeah something like that
use the random module to pick stuff from a list
have a list of styles, labels, etc
random.choice
styles = [discord.ButtonStyle.danger, discord.ButtonStyle.green, etc]
choice = random.choice(styles)
button = Button(label="Hi", style=choice)
@graceful mason
ah, I know that, but thanks
just wondering about how to add callback function to that next
just add a async def callback(interaction): beneath it
I thiink it only works with @ syntax used for button creation tho
make sure there arent other callbacks called callback, if so name it async def callback1 and so on
no?
okay, I'll try
ok
its called subclass btw, not @ syntax
by doing button.callback = callback?
it's called a decoration btw
ik
do u have message content intent
can i somehow save that without saving 2 times because if i save below it will only write 10 prestiges
what do you mean?
bot = discord.Bot()
almost works, shows the button but no callback
class MyView(discord.ui.View):
pass
@client.command(description="") # this decorator makes a slash command
async def button(ctx): # a slash command will be created with the name "ping"
styles = [discord.ButtonStyle.danger, discord.ButtonStyle.green, discord.ButtonStyle.blurple]
button = discord.ui.Button(label="Hi button", style=random.choice(styles))
async def callback(interaction):
print("button clicked")
v = MyView()
v.add_item(button)
await ctx.respond(f"Pong!", view=v)```
not commands lol
bot = discord.Bot()
do button_callback
thats it?
do ```py
intents = discord.Intents.default()
intents.message_content=True
bot=discord.Bot(intents=intents)
okay. that's it ?
still nothing
I enabled right now message.content intent in the website
maybe add it via @ syntax
ok now try
okay wait
i was abt to tell u that
still the same error
hm
let me give you all the func code
its a function in a command
in a cmd?
let me give u an example:
this def check is for this :
await bot.wait_for('message', check=check(message), timeout=60)
Okay !
wdym?
there is no ctx.message for slash cmds
its only for prefixed cmds?
oh
ctx.command returns the commannd
command*
if the cmd was /help, ctx.command would return help
one sec
ok
gtg sorry, maybe someone will help, just wait
search in the server for ur error via Ctrl+F
hm okay thanks
ah, I did it by
button.callback = v.checkbutton```
and
```py
class MyView(discord.ui.View):
def __init__(self, *items: discord.ui.Item):
super().__init__(*items)
self.user = None
self.clicked_button = None
async def checkbutton(self, interaction : discord.Interaction):
if interaction.user.id == self.user.id:
self.clicked_button = interaction.custom_id
await interaction.response.send_message(self.clicked_button)
btw u couldve just subclassed button in MyView as i told u
is it possible to add selection in paginator
Um @vivid plaza, I saw that msg, and ctx.message will be None in slash commands
That's what I told u
and how Can I fix it
Well just tell me what ur trying to do here
okay. wait
Don't send code, explain to me what u want to do
yes yes
I want to make a command that sends a message, then in the same command I want to wait for someone with a specific id to send a specific message and if he sends, the command continue
What will be in that message
What is that specific msg
.
I don't use paginator
cool
That's for on_message
oh
Wait
and the full message is :
And then do message.content
Let me Check
can i get example please
exactly what I did
is it that hard to run a function
What didn't work in that
the traceback is:
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'ApplicationContext' object has no attribute 'content'
Try def check with msg again
could you send full code/traceback
And send me error
.
full traceback
sure
what’s your current code?
wait
def check(author):
def in_check(message):
if message.author.id != author.id:
return False
else:
if message.content == "content":
#do smth
else:
return False
no need to tell me to wait. just send it, if you will.
await bot.wait_for("message", check=check(ctx.author), etc
Try this
With this
my eyes
@silver moat here's my full code
please use functions
It can? It has worked before for me
not check=check(args)
v2.0 update or smth?
no just check=check
okay wait let me try
it shouldn’t’ve
now the message isn't detected
also please name parameter/variables correctly.
the message is
?tag message-content
As of Pycord Beta 5, Discord API v10 requires message content intent to receive message content. This affects the traditional commands. Not enabling this intent will result in the messages' content, embeds, and components being empty.
You will need to enable the intent on the developer portal, as well as in your code:
intents = discord.Intents.default()
intents.message_content = True
bot = discord.Bot(intents=intents)
Docs: https://docs.pycord.dev/en/master/api.html#discord.Intents.message_content
yup I added intents
Yup told him first
my tag is @vivid plaza
where 123456789 is the user’s ID
whats wrong
you can also iterate through msg.mentions
@vivid plaza or @SIDAL.py#0001
@vivid plaza
what will it change
Try @vivid plaza
with # or without?
It doesn’t matter either way since none of those would work
Maybe try this
message.mentions works too
like I add message.mentions == "@SIDAL.py#0001"
um no
no
then?
message.mentions[0].id == your_id
.
outside of buttons list
so,
and message.mentions[0].id == 994347081294684240
?tag tias
Lol
Hm
ok
on_interaction includes all interactions
also it is better to use callback
@silver moat
return message.content.startswith(f"**:moneybag: | {message.author.display_name}, has transferred ") and "@hot stirrup" in message.content and message.author.id == 282859044593598464 and price[0][0] in message.content
any of these could be the problem
please print their values out
1 question
Nvm
I added ** at the start
It is in bold
the problem can't be the .startswith
hm ?
no colon is needed since that's not an independent clause
Just print it tbh
print everything out ?
Yes!
https://www.digitalocean.com/community/tutorials/understanding-class-and-instance-variables-in-python-3
https://docs.python.org/3/tutorial/classes.html
There's a difference between a class and an instance. Think of it like this:
- A class is like a blueprint, or a concept. It defines what something should have, but it's not the same as actually having it.
- An instance is the 'realized' version of the class, it contains everything that the class defines should be on it, but you can actually access and interact with these features.
Let's consider the Cat. We know a Cat has a name and an age, but Cat.age won't work, because Cat isn't an actual cat, it just represents the concept of a cat. It's like asking "What is the age of a cat?" - it doesn't make sense, because we need to have an actual cat.
mimi on the other hand is an instance of a Cat - it has everything a Cat should have. Maybe mimi was constructed, like mimi = Cat("Mimi", age=4), or maybe mimi was retrieved from somewhere else, like house.cats[0], but in any case, it has everything we need, and mimi.age will rightfully give us 4.
There are many situations in Object Oriented Programming where you will need an instance instead of a class to perform an operation properly (in fact, you almost always need an instance instead of a class), and these cases will usually be documented.
You should learn a good amount about Object Oriented Programming before working extensively with Pycord.
@fervent cradle
So I print these
in this case, Paginator is a class while paginator is the object.
yes
yes
in message.mention[0].id it gives this traceback
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'Message' object has no attribute 'mention'
mentions
Mentions
oh sorry
Not mention
how do you copy and paste code wrong 💀
lol true
I didn't copy paste 💀
Bruh
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: IndexError: list index out of range
Then there's no mentions
still in message.mentions[0].id
In that msg
yeah cuz it has to be the second message
@vivid plaza just add a on_msg event
that i want to check
no
And print every msg from probot
wdym ?
Ur ignoring an exception
wait_for waits for an on_message event that satisfies check so all messages will be ran through check. This can be resolved with a try-except clause
Oh So I use
try:
print(message.content.startswith)
print(message.mentions[0].id)
print(message.author.id)
print(message.content)
except IndexError:
#what do I put here
return False
oh okay thanks let me try
isn't startswith a method, not an attribute?
Um
txt = "Hello, welcome to my world."
x = txt.startswith("Hello")
print(x)
This works
It is a method
print(message.content.startswith) will do nothing for you
the first "<bullit-in method " is for the first probot msg
what is price[0][0]?
the first and the second
its a variable
price is a variable
inside of the variable there is c.fetchall()
(its from sqlite3 db)
I meant to ask for its value
for this one the value of price[0][0] is 1
now could you print the values of the conditional/predicates as well?
@vivid plaza wait, In ur code, it's message.author which returns the name and tag
But in the msg it's only ur name
Is ephemeral message deletion already live in 2.2.2, or is it still upcoming?
Oh
it works
I added .display_name
Nvm
How does one do it?
delete_original_message
Hm, just tried that, and it didn't work
ctx.delete also works in slash cmds
what should I do next ? @cobalt tangle
resp = await ctx.respond("test", ephemeral=True)
await resp.delete_original_response()
Hm
is resp an interaction or message
Maybe make probot send a particular pass code or smth at the end of the msg and check that it mentions u and the passcode is there
Interaction
I'm pretty sure startswith() is the issue but yea
@vivid plaza
then it should work fine
I sent u the full msg of probot
one sec
here again @cobalt tangle
e.g.
print(message.content.startswith(f"**💰 | {message.author.display_name}, has transferred "))
wdym?
like print the conditions that return true or false
D'oh, turned out this venv only had 2.2.0 installed. Updating fixed it. Thanks!
Maybe make probot say smth like
**💰 | {message.author.display_name}, has transferred $1 to @frank cedar [213] **
And we check for that [213] at the end of the msg and for ur mention in the msg
Sorry for the ping rip
damn rip @X
I still don't understand
do u mean I put the return thing in a variable ?
I'm pretty sure that I can't
He's telling u to print whether the check returns true or false
Yeah I know ! but how
If Invite.inviter is supposed to be a User, why is that None when the invite creation event is fired?
print(message.content.startswith(f"**💰 | {message.author.display_name}, has transferred "))
print(message.mentions[0].id == id)
print(message.author.id == 282859044593598464)
print(price[0][0] in message.content)
@vivid plaza
by this
oh okay
intents.member?
They're enabled. Works in my test guild, but production guild (with same code/settings) tells me that invite.inviter is None
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: 'in <string>' requires string as left operand, not int
the error is in print(price[0][0])
nice that's supposed to be a string
yeah ok
still not solved 💀
for me I work on this problem for 1day 🙂
outch 2 false
see the problem was with startswith
yup 💀
but It's written properly
I copy pasted the message of probot
and added things
as message.author.display_name instead of sidal.py
@silver moat
Sooo.. looking at the Audit Log, nobody actually created an invite, yet the event was fired? Is there some other case where Discord would send this over the wire? It's specifically on_invite_create so I wouldn't think it was anyone's invite Expiring or such.
I'm back with another ephemeral message deletion question.
Let's say I have an ephemeral message with a view attached. When the user clicks one of the buttons in the view, I want to delete the ephemeral message. I've tried, in the button callback, to run await interaction.delete_original_response(), but that doesn't seem to do anything. I've also tried await interaction.message.delete(), which also does nothing.
Neither call raises an exception.
Any ideas?
How to fix this?
TypeError: Interaction.edit_original_message() takes 1 positional argument but 2 were given
await interaction_respond.edit_original_message(text[:2000], view=v, embed=embed, delete_after=delete_after_time)```
from discord import Bot
How can i respond with an embed to a slash command?
python -m pip uninstall discord
python -m pip install discord
yeah
ty
hey guys so i was wondering how i can get discord.abc.Snowflake so i can use guil.unban i just dont get it at all
oh it was fetch user not get user
Why is this not working?
@discord.option(required=False, name="attachment", description="test")
async def test(ctx: discord.ApplicationContext, att:discord.Attachment):```
The attachment is required and it shouldn't be
put
async def test(ctx, att:Optional[discord.Attachment]):
You must uninstall the discord library. The only discord library should be PyCord
Can i create slash command without a decorator?
You must provide a default value.
Why would you?
in the prefix put /
but why would you?
okay thanks guys
I feel its quiet hard to give dynamically created values to the decorator. Like translation data from the database.
Then i dont see any other way to create slash commands in runtime.
The doc string for Slash commands says "These are not created manually, instead they are created via the
decorator or functional interface." so i was guessing that a functional interface exists, but i could not find anything for this in the docs.
I already got it to work by manually creating the classes and adding it to the bot on runtime. But this obv was quiet "hacky" and had a lot of bugs.
So thats just why i ask if there is a runtime option to create Slash Commands.
That's pretty much the intended way. that warning has bugged me for a really long time, I'll consider working on a fix soon. You can open an issue for it if you'd like
Sure. It's relatively trivial, but if it helps, I'm open to doing so.
I am sorry, but what prefix do you mean? I do not use any normal commands anymore.
But you want "slash_command without decorator"
Why setting option description doesn't work?
Is it possible to supply a function to generate choices for option dynamically per server?
can Anyone help me in my problem?
I want to create a normal slash command. Without the wrapper/decorator. I am not sure what prefix you mean.
I think that you can't. Maybe someone else can help you.
sure thank you 
Can anyone help me in this problem:
but seriously, what am I doing wrong,
@discord.option(required=False, name="attachment", description="some cool description")
description doesn't show
why discord.option?
Oh okay I get it nvm
can anyone help me in this problem
I want to create a function that waits for a specific person message. I created it and called it in the code that I will show you. But It doesn't want to call the function then I printed every value so I can know where I'm wrong and where I'm not
here's the code
def check(message):
c.execute("SELECT price FROM accounts WHERE type=?", (type,))
price = c.fetchall()
try:
print(message.content.startswith)
print(message.mentions[0].id)
print(message.author.id)
print(message.content)
print(message.content.startswith(f"**💰 | {message.author.display_name}, has transferred "))
print(message.mentions[0] == 994347081294684240)
print(message.author.id == 282859044593598464)
print(str(price[0][0]) in message.content)
except IndexError:
return False
return message.content.startswith(f"**:moneybag: | {message.author.display_name}, has transferred ") and message.mentions[0].id == 994347081294684240 and message.author.id == 282859044593598464 and price[0][0] in message.content
and here is where I call the Function:
await bot.wait_for('message', check=check, timeout=60)
The message is shown in this picture:
And here's what console print
there is Two False values that I think are:
print(message.content.startswith(f"**:moneybag: | {message.author.display_name}, has transferred "))
And the Second one is
print(message.mentions[0] == 994347081294684240)
Hey I need some help: await interaction.delete_original_response() spits out the error "Unknown Webhook". The interaction is triggered when a user selects an element in the dropdown list, as seen in the attached image
(My goal being to delete the ephemeral message. The function delete_original_message doesn't work either, and gives me a deprecated warning telling me to use delete_original_response)
update py-cord
you should get the interaction of the original interaction
the interaction that sent the ephemeral message
I use the interaction that is passed as parameter to the dropdown callback, do I need to use the interaction of the earlier message?
yes
Oh my bad, thank you
how would i make it so that only the original user can interact with a button?
Interaction check
how would i do that?
- read the docs
- search in chat for related topic
- google it
- redo everything cus i know u didn't do the first two steps
oop
Is it possible to restrict commands to only dm's or only in guild?
Traceback (most recent call last):
File "/home/container/bot.py", line 3, in <module>
from backend import client, discord_token, console
File "/home/container/backend.py", line 9, in <module>
from discord.ext import commands
File "/home/container/.local/lib/python3.11/site-packages/discord/ext/commands/__init__.py", line 18, in <module>
from .flags import *
File "/home/container/.local/lib/python3.11/site-packages/discord/ext/commands/flags.py", line 57, in <module>
@dataclass
^^^^^^^^^
File "/usr/local/lib/python3.11/dataclasses.py", line 1221, in dataclass
return wrap(cls)
^^^^^^^^^
File "/usr/local/lib/python3.11/dataclasses.py", line 1211, in wrap
return _process_class(cls, init, repr, eq, order, unsafe_hash,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/dataclasses.py", line 959, in _process_class
cls_fields.append(_get_field(cls, name, type, kw_only))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/dataclasses.py", line 816, in _get_field
raise ValueError(f'mutable default {type(f.default)} for field '
ValueError: mutable default <class 'discord.utils._MissingSentinel'> for field name is not allowed: use default_factory
What's this error?
I'm using python 3.11, never seen it before
same for me
python 3.11 is not yet supported in release version of py-cord
you need to use in-dev version from github or rollback to 3.10
?tag install
- Uninstall discord.py or any other forks of discord.py you might have with the namespace
discord.
python -m pip uninstall discord.py discord -y
2a. Install py-cord
python -m pip install py-cord
2b. Update py-cord
python pip install -U py-cord
Installing other builds:
Note: You need to have git installed. Use ?tag git to find out how to install git.
Updating the module to master branch (unstable):
pip install -U git+https://github.com/Pycord-Development/pycord
There's still no way to respond to an interaction without sending or editing a message, right?
@fervent cradle @wary rover ^^
Alright thanks!
@bot.bridge_command()
@commands.cooldown(3, 10, commands.BucketType.user)
async def ping(ctx):
embed = discord.Embed(title = "Pong! :grinning:", description =f"`Ping is : {round(bot.latency*1000)}ms`", colour= 0xFE6000)
msg=await ctx.respond(embed=embed)
await msg.add_reaction("🏓")
getting error regarding add.reaction when using slash cmd but working when using prefix is there a way to fix ?
Yep okay!
I reinstalled my Windows, I didn't expect this, thanks for the info
Anyone down to be kicked from my server so i can test my bot uwu :3
Create a new Account and invite the Account to your Server
Im in vietnam currently lol, i tried creating an account for 5 days and cant. Even tried a free vpn and no beans
yes he is talking about this
Sure
Is there any way to force the bot to sync commands with Discord so that the bot's available params line up with those shown on Discord for slash commands?
I tried using bot.sync_commands() but that doesn't work
It seems to have no effect at all
And all commands end up being outdated
Nvm, I fixed this ^
I just had to set force=True
Hello, how can i get a member timeout from the audit log?
async for thing in ctx.guild.audit_logs(after=member, action=discord.AuditLogAction.kick):
embed.add_field(name=f"Kick", value=f"Kicked for {thing.target}", inline=False)```
is there a way to prevent delete_after from running in .send()?
basically i want to prevent message from being deleted if some conditions are met
are the conditions known when you sent it?
well, i made a "game" so if somebody guesses the flag - then it shouldn't be deleted, and this thing is working on buttons
if you not you can just use the og message.delete()
and i'm editing this same message from button's callback function
setting delete_after to None didn't help
help pls
Pleaseeeeee
How can I send message in channel in on_member_join?
what's your current code?
I'm get channel (channel = bot.get_channel(channelData)) and try to send message in it with await channel.send(file=file)
what is channelData
ID of channel from database
it is an int, right?
yes
you can use
channel = await bot.fetch_channel(channelData)
instead
If it is a valid channel, it would return it.
oops
what even is that
thanks for help
…
.docslink discord.AuditLogAction
I already read it but with member.update it‘s also lists the nicks, how can i filter it?
I want to uninstall all the libraries related to discord to reinstall pycord. I have already uninstalled discord, discord.py and py-cord, but when I run my bot it still works.
Which of this libraries do I have to uninstall?
HELPPPP
please just say me how to filter it
simple if statement
ik but wich args
which ever ones you need to fliter out
but i don't know them
so:
async for thing in ctx.guild.audit_logs(user=member, action=discord.AuditLogAction.member_update):
if AuditLogAction.member_update == "timeout":
pass```
none, restarting your IDE should update the dependencies
?
how can i remove the used from after using a slash command? its a template bot and i forget from where i got it xd
i think its the wrong code sniped, to remove the "x used from"
You can't remove that
It's a slash command
wasnt there a thing that when u do a slash command its only visable for yourself?
its not pycord, its a normal python dc bot, didnt find a other dc server xd
you cannot.
could you tell my how, i think i need to change then something in the base of the bot? how i said i have 0 clue, and im using a template
Is there an Option type that lets the user input multiple mentions (and only mentions)?
should this be a command or a slash command
cause it automatically turns to a slash command for me
and the slash commands are super buggy
ctx.send for prefixed commands, ctx.respond for slash commands
if it's discord.Bot then it's a slash command. If it's commands.Bot, it's a prefixed command
where do i report a bug in pycord
when using a slash command, any interaction makes any emojis not work
the bot needs external emojis permissions on the @everyone role
doesnt work
pycharm?
vs code
How can I don't show the error in the console?
.tag eh
Docs: https://discordpy.readthedocs.io/en/latest/ext/commands/commands.html#error-handling
Example: https://gist.github.com/EvieePy/7822af90858ef65012ea500bcecf1612
Simple Error Handling for ext.commands - discord.py - error_handler.py
Error handling
Docs: https://discordpy.readthedocs.io/en/latest/ext/commands/commands.html#error-handling
Example: https://gist.github.com/EvieePy/7822af90858ef65012ea500bcecf1612
I mean the error that comes when I stop the bot.
Here's the slash autocomplete example.
@heavy jungle. ^
yw
😊
@silver moat
ah wait, this may not be what im looking for. I would like to change the future arguments based off of the first option.
is this possible?
Here's the slash groups example.
if you need for cogs there's
Here's the slash cog groups example.
this may be what i am looking for.
i will give it a go
was exactly what i was looking for
How can I find out if a modal has been canceled?
you can't
Damn, that sucks
i've looked around and tried googling it but anyone know how to set custom status on the bot?
nvm i just got it
I already do that, but it's strange, look
Here everything is perfectly aligned
I looked at the pixel with photoshop
Here nothing is correctly aligned
the only reason you would re-write something, if it works, is to make it more efficient
The phone display is not perfect, I am stressed now
I just started getting this error randomly while testing.
Ignoring exception in on_connect
Traceback (most recent call last):
File "C:\Users\schne\PycharmProjects\discordSlashBot\venv\lib\site-packages\discord\client.py", line 377, in _run_event
await coro(*args, **kwargs)
File "C:\Users\schne\PycharmProjects\discordSlashBot\venv\lib\site-packages\discord\bot.py", line 1138, in on_connect
await self.sync_commands()
File "C:\Users\schne\PycharmProjects\discordSlashBot\venv\lib\site-packages\discord\bot.py", line 692, in sync_commands
registered_commands = await self.register_commands(
File "C:\Users\schne\PycharmProjects\discordSlashBot\venv\lib\site-packages\discord\bot.py", line 581, in register_commands
registered = await register("bulk", data, _log=False)
File "C:\Users\schne\PycharmProjects\discordSlashBot\venv\lib\site-packages\discord\http.py", line 372, in request
raise DiscordServerError(response, data)
discord.errors.DiscordServerError: 500 Internal Server Error (error code: 0): 500: Internal Server Error
looks like a discord issue
Thats what google
if Internal Server Error wasn't clear enough
is saying
Yeah. Just making sure. Pycord is auto-reconnecting, or at least the bot isn't dropping off the service, but is there any error handling I need to do to deal with it?
if you really wanted to, you could with on_error
In need of a little help in #1038688239596355636
If message.type is reply, then is message.reference guaranteed to be non-None?
Is there a hard ceiling on the number of slash command groups you can have?
How can i check if the member update is a mute?
async for thing in ctx.guild.audit_logs(user=member, action=discord.AuditLogAction.member_update):```
i got the interaction of the message using message.interaction. but not able to get the option values. how to get that?
Hey,
Anyone know how this (in the image) is named in the pycord docs?
message.command
@discord.message_command()
Thank you found it 👍🏻
np
Is it possible to edit a response?
how to i pass in an option in a slash command to a select class
yes
msg = await ctx.respond("Hi")
await msg.edit("Bye")
help
interaction?
yes
use ctx.edit()
ig that works too
I dont understand y this doesnt
the slash_command returns an interaction
a user will input a member to which I need the member's id in the dropdown class's callback
same error again lol
it works perfectly fine for me
ill make a forum post
u have some error, show ur code
also can u help me with smth
I can try
^
i need the slash cmd option's value for user to find result in sqlite
def __init__(self, bot_: commands.Bot, user: discord.Member, ctx):
self.bot = bot_
self.user = user
self.ctx = ctx
``` does this work
you can try it but Im not sure xd
okay
Hey, I have a problem and I get the following error:
If anyone knows how to fix it, feel free to tag me. Thanks for the help
Traceback (most recent call last):
File "C:\Users\imene\PycharmProjects\AzGlobal\src\main.py", line 4, in <module>
from discord.ext.commands import Bot
File "C:\Users\imene\PycharmProjects\AzGlobal\venv\Lib\site-packages\discord\ext\commands\__init__.py", line 18, in <module>
from .flags import *
File "C:\Users\imene\PycharmProjects\AzGlobal\venv\Lib\site-packages\discord\ext\commands\flags.py", line 71, in <module>
@dataclass
^^^^^^^^^
File "C:\Users\imene\AppData\Local\Programs\Python\Python311\Lib\dataclasses.py", line 1221, in dataclass
return wrap(cls)
^^^^^^^^^
File "C:\Users\imene\AppData\Local\Programs\Python\Python311\Lib\dataclasses.py", line 1211, in wrap
return _process_class(cls, init, repr, eq, order, unsafe_hash,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\imene\AppData\Local\Programs\Python\Python311\Lib\dataclasses.py", line 959, in _process_class
cls_fields.append(_get_field(cls, name, type, kw_only))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\imene\AppData\Local\Programs\Python\Python311\Lib\dataclasses.py", line 816, in _get_field
raise ValueError(f'mutable default {type(f.default)} for field '
ValueError: mutable default <class 'discord.utils._MissingSentinel'> for field name is not allowed: use default_factory
Process finished with exit code 1
you need the git version
Thanks
np
Is there a way to make embeds a specific width? I want to return 5 embeds (its like a bot which searches a website), which have a title and a description. But it does not look very consistent if they have (because of the different lengths in title and description) a different width.
send the whole code (the whole cmd)
Try m.edit
TypeError: 'str' object is not callable
@lockdowncmds.command("Kick all members who join")
@commands.has_permissions(administrator=True)
async def member(self, ctx):
async with self.bot.db.cursor() as cursor:
await cursor.execute("SELECT value FROM lockdown WHERE guild = ?", (ctx.guild.id))
data = await cursor.fetchone()
if data:
if data[0] == True:
await cursor.execute("UPDATE lockdown SET value = ? WHERE guild = ?", (False, ctx.guild.id))
owner = ctx.guild.owner
await owner.send(f"{ctx.author} has disabled Lockdown mode in {ctx.guild} which kicks every member who joins!")
await ctx.respond("Turned off Lockdown mode!")
elif data[0] == False:
await cursor.execute("UPDATE lockdown SET value = ? WHERE guild = ?", (True, ctx.guild.id))
await owner.send(f"{ctx.author} has enabled Lockdown mode in {ctx.guild} which kicks every member who joins!")
await ctx.respond("Turned Lockdown mode to TRUE")
else:
await ctx.respond("Error!")
else:
await cursor.execute("INSERT INTO lockdown (guild, value) VALUES (?, ?)", (ctx.guild.id, True))
await owner.send(f"{ctx.author} has enabled Lockdown mode in {ctx.guild} which kicks every member who joins!")
await ctx.respond("Turned Lockdown mode to TRUE")
its raising the error from async def member(self, ctx)
@lockdowncmds.command(description="Kick all members who join")
Btw, couldn’t you just turn off invites (requires Guild edit privs) instead of kicking?
oops
Just do ctx.edit
@fervent cradle hm, if .edit doesn't work, try m.edit_original_message()
You mean a token?
You don’t need a “license key”.
Ohhh I see
Well you’d have to do that yourself, since we don’t know your intentions for it.
Maybe pull it from a database
if the user is downloading your bot's code then any protection that you try and code in will be able to be circumvented surely?
so you want to rely on the lack of technological ability of the end user for your security?
but then again, what else can you do
The only way I could see this working is if you controlled the bot instance, allowing anyone to add it to a server, but not do or watch anything aside from “license key” commands.
If you allow users to download and execute the source, there’s no point.
How would i use ipc in pycord?
/home/container/syst.py:11: RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
client.load_extension((f"{path[2:]}/{filename[:-3]}").replace("/", "."))
RuntimeWarning: Enable tracemalloc to get the object allocation traceback```
I'm getting this error for no reason on a different Discord host VPS.
I just switched and it wasn't happening before.
def load(client, path, filename):
import os
if os.path.isdir(f"{path}/{filename}"):
for file in os.listdir(f"{path}/{filename}"): load(client, f"{path}/{filename}", file)
else:
if filename.endswith(".py"):
try:
client.load_extension((f"{path[2:]}/{filename[:-3]}").replace("/", "."))
print(f"{w}{brt}Loaded {filename} from {path}{rst}")
except Exception as e:
print(f"{w}{brt}Failed to load {filename} from {path}{rst}:\n{e}\n")```
Line 11 is client.load_extension((f"{path[2:]}/{filename[:-3]}").replace("/", "."))
There should be no reason this is happening
pip list and send output
unless you are using Pycharm where there's a button called Python Packages and take a screenshot of that.
No I'm not using pycharm.
so this.
py-cord==2.0.0b5
psutil
colorama
asyncio
wrap
textblob
discord.gui
randfacts
dadjokes
music-cord```
that's your requirements.txt
I'm unable to do an actualy pip list since it's like a host.
but each could have extra dependencies
discord.gui requires discord.py
It works in my other host without an issue.
My bot is loading but nothing in the cogs is working
It says / not found. None of my commands in the cogs work.
It's only on this new host.
use py-cord 2.2.2
How can i limit slash commands to certain users (developers, checking from a list of IDs would be fine)
But it can't be version if it works on my old host
What does this even mean
You can limit them to just a guild.
yea
wth
requirements.txt line 1
discord.py```
Fork what
fork discord.gui
Nah it's the host
My other host works fine
It should be able to use it without d.py
you can always run os.system("pip uninstall discord discord.py")
probably wouldn't work
I need some help on ctx.author.add_roles()
got discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'NoneType' object has no attribute 'id' error
async def redeem(ctx,license:discord.Option(str)=None):
if license==None:
await ctx.respond('You didnt provide a license to claim', ephemeral=True)
else:
if license in licenses :
users[str(ctx.author.id)]=licenses[license]
saveusers()
role = ctx.guild.get_role(config["roleid"])
await ctx.author.add_roles(role)
licenses.pop(license)
_save()
await ctx.respond('Success!', ephemeral=True)
else:
await ctx.respond('Unkown license', ephemeral=True)
``` is my cde
nvm solved i just putted wrong role id
1st issue: why do you have 5.7k lines
Is not using cogs
first use an IDE
and then you will see a missing parentheses.
Is there a way to get the number of unread pings I have? Would be for a personal project so doesn’t need to work for anyone else
against discord tos unless it isn't a discord client modification
Nah, it’s a hardware notification thing that I thought would be cool
how do i catch @commands.has_permissions (in a cog) instead of it just throwing an error?
https://docs.pycord.dev/en/master/api/events.html#discord.on_application_command_error
or https://docs.pycord.dev/en/master/api/cogs.html#discord.Cog.cog_command_error
This section outlines the different types of events listened by Client. There are two ways to register an event, the first way is through the use of Client.event(). The second way is through subcla...
@commands.Cog.listener()
async def cog_command_error(self, ctx, error):
print(f"[x] error: {error}")
TypeError: Commands or listeners must not start with cog_ or bot_
@commands.Cog.listener(name = "cog_command_error")
oh lol
and rename actual function name
one sec
does this also apply if the command is in a command group?
because it aint catching it
@commands.Cog.listener(name="kick")
async def on_command_error(self, ctx, err):
print(f"[x] error: {err}")
mod = discord.SlashCommandGroup("mod", "List of moderation commands for Admin")
@mod.command(description = "Kicks a member. Permission required.")
@discord.option("member", description = "Member wanting to kick")
@discord.commands.option("reason", description = "Required: Describe the reason")
@commands.has_permissions(kick_members=True)
async def kick(self, ctx: discord.ApplicationContext, member: discord.Member, *, reason = None):
got it, no need for a listener.
async def cog_command_error(self, ctx: commands.Context, error: commands.CommandError):
await ctx.send(error, reference=ctx.message)
how do i use get_application_command to get a subcommand? currently im doing get_application_command('group subgroup subcommand') but it's returning None
update: only happens with conda envs
When passing a timedelta to timeout_for i get TypeError: Member.timeout_for() takes 2 positional arguments but 3 were given, how can i fix this?
send code
currenttime = datetime.datetime.now()
currenttime = time.mktime(currenttime.timetuple())
time1 = int(convert(length))
endtime = datetime.timedelta(seconds=time1)
timestamp1 = datetime.datetime.fromtimestamp(currenttime + time1)
delta = datetime.timedelta(seconds=time1)
print(delta)
await member.timeout_for(delta, reason)```
convert returns a value of seconds
what about reason
reason is a string
i think the problem is with my delta
docs say it takes a delta but the delta returns 1 day, 0:00:00 which i assume is read as 3 args
I don't think so
reason is a kwarg
that would be an issue, thank you
Never had this issue but its saying module discord has no attribute bot
File "C:\Users\layne\Downloads\Discord-Generator-Bot-1.0\LinkGen.py", line 12, in <module>
client = discord.Bot()
AttributeError: module 'discord' has no attribute 'Bot'
:C
pip list and show output
ok
?tag notpycord
The library name is py-cord not pycord
?tag install
- Uninstall discord.py or any other forks of discord.py you might have with the namespace
discord.
python -m pip uninstall discord.py discord -y
2a. Install py-cord
python -m pip install py-cord
2b. Update py-cord
python pip install -U py-cord
Installing other builds:
Note: You need to have git installed. Use ?tag git to find out how to install git.
Updating the module to master branch (unstable):
pip install -U git+https://github.com/Pycord-Development/pycord
does banning a user via user.ban() automatically delete all their messages?
Hey, it’s not anything really important but what I’m making is a discord account bot that sends you like user ids to your dms , but what’s a way I can limit the amount of uses that command can be run yall got any ideas on how I can do this
like limit it forever?
or for some time?
How the generator works is they have to have a role for them to gen
^
do u restart ur bot often
u can use @commands.cooldown(amount of times the cmd can be used before cooldown, cooldown in seconds, commands.BucketType.user)
but it will reset after u restart the bot
@mortal junco
Well how the bot works is it’s like a subscription
Not really but kinda
They boost they server get access to it
is this what you are looking for?
whats ur timeout?
No, super.__init__() should be in def __init__()
as a matter of fact, where is your def __init__()?
Channel name changes are heavily ratelimited
maybe add their name to a db temporarily and check if their name is there via interaction_check()?
I dont think there's a method for cooldown in interaction
brutha you should start reading your code
anyways
is there a way to restart the bot without disconnecting?
it is kind of an issue if you have a view without a timeout and you have to restart the bot
'cause then all the views will be broken
add persistant views
Here's the persistent example.
@hazy vault
.
thank you so much
but this is just a view without a timeout
I don't need that lol
you can reload cogs maybe
yes? thats where persistent-views come in
seems like u do but okay
I already have it
I know how to remove a timeout lmao
yeah I figured but it won't reload internal stuff
How do I access the selected users from ComponentType.user_select?
is it still Select.values
Can I add field without value?
Not sure. But I know you can't add a value without a field.
I feel like it's a no though
Probably?
@verbal dawn
add the code for the buttons after all the bot's code in Interface and give button 1 row 0 and button 2 row 1
Why does this remove 1 child per intereaction
because u remove the item...
I mean i want remove 2 at once not 1
and what is option
send the code then
Basically 3 interactions:
- selection
- enable
- disable
when you switch to another selection only enable removes
ok send the code
ok one sec
view is discord.ui.View right?
ok
also it has duplicated ids (i didn't see it before)
what
buttons with duplicated id
oh yeah
wait
so the option cb removes all children (enable, disable buttons)
but three of the options add new Enable and Disable buttons
maybe ur getting confused with the new enable and disable buttons?
yeah probably
bruh
is it confirmed that thats whats happening?
I can use clear_items() but option will clear too
yes
cant u use clear_items() and do add_item()
so i am migrating from discord.py 1.7 to 2.0 and i confused now in this:
i was using discord_components to get the label of the button on click but on 2.0 i cannot seem to find anything that can help me get the label of the specific button on click

This isn't discord.py
ahh so where do i go for discord.py
Maybe the support server?
ok
why r you adding it to the view, its already added cuz its in a discord.ui.View
u dont have to add it...
its automatically added
just send the class
ill update and send u
...
its been 3 minutes
Are you on the latest pycord version?
[CRITICAL: 15:59:27 | EXT] @discord.ui.button(label="Support Server!", style=discord.ButtonStyle.link, link="https://discord.gg/")
[CRITICAL: 15:59:27 | EXT] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
[CRITICAL: 15:59:27 | EXT] TypeError: button() got an unexpected keyword argument 'link'```
not sure why this is giving an error if it says I need a link there
The kwarg is url not link
I tried that too but it was saying the same thing
[CRITICAL: 16:12:00 | EXT] @discord.ui.button(label="Support Server!", style=discord.ButtonStyle.link, url="https://discord.gg/")
[CRITICAL: 16:12:00 | EXT] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
[CRITICAL: 16:12:00 | EXT] TypeError: button() got an unexpected keyword argument 'url'```
@slash_command(name="support", description="Get a link to our support server.",)
async def support(self, ctx: AppContext):
embed = Embed(title="Support Server", description="🔗 Click the button below to join the Support Server to get help and have access to some cool features!")
await ctx.respond(embed=embed, view=SupportButton)
class SupportButton(discord.ui.View):
@discord.ui.button(label="Support Server!", style=discord.ButtonStyle.link, url="https://discord.gg/")
async def button_callback(self, button, interaction):
await interaction.response.send_message("You clicked the button!")```
you didn't initialize the view btw
oh, what do I need to add 👀
the constructor and calling its parent's constructor
💀
can you explain a bit more, I dont see this anywhere on the example docs
So, TextChannel.permissions_for is considered the most accurate way of checking permissions, but sometimes I get a PartialMessageable instead. What do people do in this situation?
how would I go about making a message with multiple buttons?
did you get 1 button working?
yes

how did you do it
class ReactionRoles(discord.ui.View):
@discord.ui.button(label="Announcements", style=discord.ButtonStyle.secondary, emoji="📢")
async def button_callback(self, button, interaction):
user = interaction.user
guild = bot.get_guild(924979519977320459)
role = guild.get_role(944940789375565935)
if role in user.roles:
await user.remove_roles(role)
await interaction.response.send_message("Removed <@&944940789375565935> from you!", ephemeral=True)
else:
await user.add_roles(role)
await interaction.response.send_message("Gave you <@&944940789375565935> role!", ephemeral=True)
@bot.event
async def on_message(message):
if message.author == bot.user:
return
if message.content.startswith("?roles") and message.author.id == 675316333780533268:
embed = discord.Embed(title="Roles", description="""
Lets get you some roles!
""", color=0x0d6dea)
await message.channel.send(embed=embed, view=ReactionRoles())
Nov 07 16:44:16 raspberrypi python3[104647]: Traceback (most recent call last):
Nov 07 16:44:16 raspberrypi python3[104647]: File "/home/pi/the-hi5-group/venv/lib/python3.10/site-packages/discord/ui/view.py", line 416, in _scheduled_task
Nov 07 16:44:16 raspberrypi python3[104647]: return await self.on_error(e, item, interaction)
Nov 07 16:44:16 raspberrypi python3[104647]: File "/home/pi/the-hi5-group/venv/lib/python3.10/site-packages/discord/ui/view.py", line 400, in on_error
Nov 07 16:44:16 raspberrypi python3[104647]: print(f"Ignoring exception in view {self} for item {item}:", file=sys.stderr)
Nov 07 16:44:16 raspberrypi python3[104647]: File "/home/pi/the-hi5-group/venv/lib/python3.10/site-packages/discord/ui/item.py", line 93, in __repr__
Nov 07 16:44:16 raspberrypi python3[104647]: attrs = " ".join(
Nov 07 16:44:16 raspberrypi python3[104647]: File "/home/pi/the-hi5-group/venv/lib/python3.10/site-packages/discord/ui/item.py", line 94, in <genexpr>
Nov 07 16:44:16 raspberrypi python3[104647]: f"{key}={getattr(self, key)!r}" for key in self.__item_repr_attributes__
I updated to the latest commit on git so I could get the mentionable select options, is this an issue in my code?
nevermind it didn't update properly
wtf does this meannnn
Check the guides
