#Basic Pycord Help (Quick Questions Only)
1 messages · Page 30 of 1
Ok that's awesome. Thank you.
Install pycord:
pip uninstall discord.py
pip install py-cord
Install pycord from git repository: (alpha)
pip uninstall discord.py
pip install git+https://github.com/Pycord-Development/pycord
thanks sexy

so cute
is there a problem with install master branch on python 3.11? I seem to be getting the error that C++ 14.0 is required, but I'm not using VS
Microsoft C++ Build Tools is not directly linked to VS. you still need it to function, no matter the IDE
oh I see ty
is it bc of python using C++ to compile into bytes? If I'm using the correct terminology?
python does not specifically use C++ as a compiler, libraries for python does
I got a quick question: If i work with files, does it make a signifcant improvement if i open them with a library like aiofiles? Or could i just read files normally without asynchronous execution.
The issue only arises when you have concurrent users or loading a big file. However, it is recommended to use aiofiles regardless
Yeah my file is neither big nor should it happen, that several users need to open it. But i try, thanks!
will displaying if the variable is int, string or list help in performance since during compiling, python itself will decide the variable type?
anyone knows how to fix this error?
One message removed from a suspended account.
Here's the slash cog example.
One message removed from a suspended account.
embed.set_author(name=ctx.author.display_name, icon_url=ctx.author.display_avatar)
AttributeError: 'NoneType' object has no attribute 'id'```
how has this happened
typehinting in python is never enforced, it's mainly for typecheckers/IDEs
you won't see any performance gains unless you seek out a compiler that specifically takes advantage of them
I see, so is it best practice to go into enforcing typehinting where possible?
typehinting is nice for code readability/making your ide happy and is part of the many PEP guidelines so people do encourage its use
thus you could consider it good practice, but it's not going to impact the code itself
:( Was hoping it'd help in performance a tiny bit
ultimately i guess try it out and see if you like it, i pretty much never bothered typehinting but i tried it on a recent cog i worked on and it did look pretty nice in the end
if you're working in an IDE/using stuff like copilot there's also a chance it can complete the typehints for you so it's not much extra work
It'd be very good practice especially when learning languages that requires typehinting
Thank you!
allgood
bruh i asked this question like 5 times today
probably because there's like zero context there
you should be getting a full traceback
Hi, im having problems with timeouts, self.disable_all_items() does nothing to the view so i tried this:
async def on_timeout(self):
for child in self.children:
child.disabled = True
await self.message.edit(content="You took too long! You have to send another command to continue :(.",
view=self)
This works when the view is called in the slash command, but not in interaction or followup, there it just says that NoneType obj has no attribute edit:
Task exception was never retrieved
future: <Task finished name='discord-ui-view-timeout-17f7431f32310f4a8587cda87b378011' coro=<view.answer_mode.on_timeout() done, defined at /opt/bot/cogs/test.py:179> exception=AttributeError("'NoneType' object has no attribute 'edit'")>
Traceback (most recent call last):
File "/opt/opt/bot/cogs/test.py", line 183, in on_timeout
await self.message.edit(content="You took too long! You have to send another command to continue :(.",
AttributeError: 'NoneType' object has no attribute 'edit'
pycord version?
thats the thing
i have no idea whats causing the error
instead of just that error in the red box, run the code and paste the full traceback that appears in the console
VersionInfo(major=2, minor=2, micro=2, releaselevel='final', serial=0)
if im not mistaken the view.message implementation is still incomplete
hmm
there are a few ways around it i guess
i tried the simple self.diable_all_items(), but same results, only works when in slash command
if it's the first ctx.respond or interaction.response.send_message, you can do view.interaction = await ctx.respond(...), then view.interaction.edit_original_response
if it's a subsequent ctx.respond or interaction.followup.send, you can do view.message = await ctx.respond(...) then view.message.edit
I dont understand what you mean
i'm saying that you can assign the view.message attribute itself, to make sure it always exists
but depending on when you send the view, you might get an interaction object; if that happens then you change the edit method
i am sending the view on interaction (clicking button or select something in the select menu)
so in your button's callback you're doing something like await interaction.response.send_message i presume?
i am sending a follow up message, but thats similar
i need the interaction to edit the first message
first i use response to disable the view in the first message,
then i use follow up to send another message with another view
and the view used with the follow has the problem with timeouts not working well
i dont know what defer means in this context
Hey y’all, probably a dumb question: I’m attempting to use the change_presence method to assign a rich presence to my bot based on what it’s currently doing (aware this is global, but it’s a private bot) and as far as I’m aware everything is done per the docs, but for whatever reason all it ever does is update the name of the Activity, all other fields (assets, timestamps, etc) appear to be ignored. Are rich presences including images and time elapsed supported by (a) bots and (b) pycord?
I can throw in the code if needed.
rich presences aren't possible on bots
Okay, was getting to that conclusion, so they seem to be limited to just name and description, right?
ignore me, if it's followup then all you have to do is view.message = await interaction.followup.send etc. etc.
yeah just the standard statuses
you can do stuff like watching/listening/streaming but that's it
Okay sweet, thank you! Was wasting a lot of time on it and figured it probably works for normal users.
this doesnt work, what it does is when the first view times out, it edits the secod-followup view
convert into int first and then add 1
number2 = int(number + 1)
you are adding 1 to number and then converting to int
but number is a string and + is acting as the concatenation operator
see the brackets
int(number) + 1 should convert number to an integer and then add 1 to it
yeah
??
just use +=
every time i open this channel
i always see someone
asking for the most basic help
Is there a way to add options to a select menu based on who executed the command?
I made a thread for this, but if there is some kind of quick documentation available or something I figured I could ask here
something similar is what i did
class Dropdown(discord.ui.Select):
def __init__(self):
options = []
for i in range(1, 17):
options.append(
discord.SelectOption(label=f"Team {i}", value=str(i), description=f"Your preferred team is {i}"))
super().__init__(
placeholder="Choose your preferred team",
min_values=1,
max_values=1,
options=options,
)```
I've figured it out since I posted, and its pretty similar!
costumeView = discord.ui.View()
if len(user_closet['paints']) != 0:
paintSelect = discord.ui.Select(placeholder="Pick your Lackey's color", min_values=1, max_values=1, disabled=False)
paintSelect.add_option(label="Black", value="black")
for item in user_closet['paints']:
paintSelect.add_option(label=item.capitalize(), value=item)
costumeView.add_item(paintSelect)
hey guys i was wondering what react messages permission name is i cant spell it good enuph to find it in docs 
wait i found in source code lol
Anyone can help me so I can use on_interaction and slash commands created with @bot.slash_command()
use await bot.process_application_commands(interaction) in on_interaction
So I just have to put this single line in on_interaction and everything after this Code line works and my slash commands too? And thank you
My desired flow for this command is this: >User executes command --> They are presented with an ephemeral menu to select certain things, which is deleted upon completion --> based on those selections, the bot responds to the original message with a result non-ephemerally.
My issue right now is that when I use ctx.respond and the selection menu is deleted, the response message says "The message was deleted", as it is responding to the previous message and not the original command
Any way I can fix this?
Without relevant code, can't help.
async def doneCallback(interaction):
with BytesIO() as image_binary:
generateLackey(ctx.author.id, lackeyChoices).save(image_binary, 'PNG')
image_binary.seek(0)
await interaction.response.defer()
await ctx.respond(file=discord.File(fp=image_binary, filename=f'{ctx.author.id}s_lackey.png'))
doneButton = discord.ui.Button(style=discord.ButtonStyle.primary, label="Done!")
doneButton.callback = doneCallback
costumeView.add_item(doneButton)
await ctx.respond(content="Enter details", view=costumeView, ephemeral=True)
This is about as much as I can minimize without sending the entire thing
Why are you using ctx.respond inside a View callback
Because when the final message is sent, I want it to show the command like
Libra used /COMMAND
[final image]
Which this obviously doesnt do, what SHOULD I be using in the view callback?
Im confused cause you have no ctx in a view callback
You only receive interaction
So you be responding to interactions with interaction.response.send_message
What you want to do is edit the original message
It's the ctx from the original command, available from the scope the function is declared in, the same one the "enter details" is using
So it should be interaction.response.edit_message
The message is ephemeral though, can I edit an ephemeral message to be non-ephemeral?
OK, that's awful.
How is it supposed to be done
No.
You must send a second respond or just don't make it ephemeral at all n
There's no other option
What is the proper way to send a second response?
I dont want to reply to the ephemeral menu, because other users cannot see that
.
If you don't want the reply thingy
You'd just send a normal message. But you must pong the interaction
Or it'll "fail"
To other users though it will say "This message is unavailable" instead of "Libra used /command" because that first response was ephemeral
So just to confirm: Having a second interaction respond to the original command once the first response was deleted is not possible
You can send a second response. It just doesn't fit your needs or having it display "Libra used /command"
Just don't make the first response ephemeral
The first response is a menu I dont want others that did not use the command interacting with while the user that issued the command is doing so
This seems like it would be a common usecase, that or I am thinking about this completely wrong, which is probably the case. lol
You can run internal checks to prevent that
Ah I see
You just run a quick check before doing all the callback
shouldn't there be select as a param too?
or is it only for classes
Or override on_interaction and run the check there to prevent the callback from being called
I'm having to do this a little fucky because the options inside the select menu are generated on a per-user basis, so each one of them is it's own interaction that assigns to a dict on callback (lackeyChoices)
which is another reason that menu is ephemeral
Users with more access will have more options
I see right
Im just going to edit the original menu and leave it ephemeral
unfortunate though, wouldve been neat
Yep thats the "submit" button
Takes all the data from several submits and sends them to the generation function to send
can you send in the costumeView as well pls
I know this likely isnt the best way to do this, but I was having trouble using selections generated per-user like this
open to suggestions
I presume you don't know much about classes?
I thought I did, but if there’s a better solution using them i missed it hard
I read these docs, but in every every example of selection options being generated they are hardcoded in the class definition, which is why i started declaring them outright like i did in the snippet
it's a bit difficult to like follow the code especially without classes, but if you want all ur messages sent to be ephemeral, you can do that easily with classes
you can use the
interaction.response # once and then it is
interaction.followup.send # same like the above and can be used ephemerally
The reason I didn’t use classes is because i coudlnt figure out how to dynamically declare selection options using them based on what user called the context
you can compare it in the __init__ and create the object using self
def __init__(....)
if self.user == "":
self.add_view(Select(...)
else:
....
What’s slipping me up the most is how the options are declared inside the decorator on the documentation
lil bro needs to learn what a decorator actually does
great commentary norman
thanks for the help @loud holly i’ll figure out how to write this the right way
Can bots go live/share screen?
nope
ok
I feel dumb but I want to save an attachment to a specific file:
this doesnt work cause I need an "os.pathlike" object?
how would I convert the string I currently have to os.path?
How do I record audio in a voice channel?
https://github.com/Pycord-Development/pycord/blob/master/examples/audio_recording.py
I'm aware this exists, but I'm getting errors like:
OpusNotLoaded
So then I add py import discord discord.opus._load_default() #or discord.opus.load_opus() to the code, and get one of two results: py Required Positional Argument: name OpusNotLoaded
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/audio_recording.py at master · Pycord-Development/pycord
Use sinks
The code example above does use sinks of the user's choice
hey guys, how i can make a command that returns the replied message if exists?
@client.event
async def on_message(message):
if message.content == "I did it":
await ctx.send(":white_check_mark:")```
i mean getting the message instance
not replying
when i reply to a message with a command, get that message instance
message has a reference attribute
^
thanks
@round rivet, any thoughts on this? The example listed on github seems to be running into an error
Yes i do
opus is supposed to come bundled with the library
we never figured out why that error occurred
I see. I noticed that there are some differences comparing to discord.py, though I have not touched with discord.py in a while, that I don't know if that still works
So does this mean discord packages still can't really record audio from Discord?
view=discord.ui.View
options=[]
for i in range(10):
options.append(discord.SelectOption(
label=i[0],
value=i[1]
))
view.add_item(discord.ui.Select(
placeholder = "Select",
options = options
))
await ctx.respond(view=view)
how do I add a callback for this?
I looked at the Select Menus guide, but that needed a custom class
make a callback function and assign it to select
which I'd be fine with, but I need to add the options dynamically
how do I "assign" it?
.docslink discord.ui.Select.callback
so I have to subclass discord.ui.Select?
ok I'll give it a try
subclassing discord.ui.Select was a bad idea
but I managed to subclass discord.ui.View in a way that works
thank you!
Read the error
Reading the error will help you solve the problem.
then learn basic python
"List indices must be integers not strings"
learn python
And learn how to read errors, because your "solution" doesn't even solve the error
It's on my VPS, what's the best way to solve it?
anyone knows how can i fix this?
ive also been getting these kinda of errors but it doesnt seem to affect how my code runs
well mine doesnt .. it runs but the command doesnt work
deal with it :(
not rly sure then
how to make second dropdown wait for first dropdown?
Traceback (most recent call last):
File "c:\Users\Baban\Desktop\Folders\code playground\olympus-dev\Olympus-Private\main.py", line 2, in <module>
from discord.ext import commands
ImportError: cannot import name 'commands' from 'discord.ext' (unknown location)
can you show the pip list
also do you use pycharm?
Add a custom_id to the first select menu and use bot.wait_for("interaction",check=check) and include something about the interaction.custom_id in the chec
no
ago 0.0.95 aiohttp 3.7.4.post0 aiosignal 1.2.0 akinator 1.0.3 animec 0.4.2 astunparse 1.6.3 async-timeout 3.0.1 attrs 21.4.0 beautifulsoup4 4.11.1 braceexpand 0.1.7 bs4 0.0.1 certifi 2022.6.15 chardet 4.0.0 charset-normalizer 2.0.12 click 8.1.3 colorama 0.4.5 discord 2.0.0 discord-together 1.2.6 discord-ui 5.1.6 disputils 0.2.0 frozenlist 1.3.0 humanfriendly 10.0 humor-langs 1.0.1 idna 3.3 import-expression 1.1.4 jishaku 2.5.0 mojang 0.2.0 multidict 6.0.2 mysql 0.0.3 mysql-connector 2.2.9 mysql-connector-python 8.0.31 mysqlclient 2.1.1 pet-pet-gif 1.0.2 Pillow 9.1.1 pip 22.0.4 py-cord 2.2.0 pyreadline3 3.4.1 python-dateutil 2.8.2 qrcode 7.3.1 requests 2.26.0 setuptools 58.1.0 six 1.16.0 soupsieve 2.3.2.post1 typing_extensions 4.4.0 urllib3 1.26.9 wheel 0.37.1 yarl 1.7.2
discord-together 1.2.6
discord-ui
py-cord```
uninstall all 4 and reinstall py-cord
.
i am using discord-togeather
cool its working now thanks!
i dont really get it but can i ask for an example?
Dropdown selected value is just disappearing after editing the message. How could I fix it?
discord.errors.HTTPException: 413 Payload Too Large (error code: 40005): Request entity too large
when sending an image (23MB) in on_message() and send them again 
Here's the code (It's also inside of command not class)
https://cdn.discordapp.com/attachments/979392900993519646/1035570578628812891/unknown.png
view=self
# select menu decorator
@discord.ui.select(..., custom_id = "select1")
# 2nd select menu
@discord.ui.select(...)
async def second_select_menu_callback(self, select, interaction):
def check(interaction):
return interaction.custom_id == "select1"
await bot.wait_for("interaction", check=check)
Don't edit the view then
Then submit can't be enabled
i have updated the code 💀
I believe this is a discord limitation since there is no way to preset selected values for a Select Menu
Yeah, but if a user selects the dropdown value and it edits it should stay and not clear it
instead of editing the message you can send another message
which wouldn't update the select menu
Expected & Reality
nvm you actually can
you should get the values and edit the select menu so that those are selected
@verbal dawn
select = discord.Select(..., options = [discord.SelectOption(..., value = "option1")])
async def callback(interaction):
for value in select.values:
if value = "option1":
select.options[0].default = True
and don't forget the edit the actual view
it's always setting it on "discord"
maybe try a if statement, whereas if the first dropdown input is empty, dont execute
Update: It was fixed but very complicated
Isnt a for loop easier
I am dumb alr?
not shure but i guess it's pip uninstall py-cord
pip uninstall py-cord?
lol
y
enable it
^
use discord.Intents.all()
do you have enabled all what i did?
ok
don't you what i did but your welcome ::)))
How can read the Audit Log and filter it?
guys ı install library
then ı write import discord
but ı cant
do you know what can ı do
send code
Show the pip list
just this
do pip list in the terminal
then?
send the output
there are too many things
So how do I create a help menu using embeds?
The help command itself should be callable using /help
Very important I am creating the help menu in a cog called help.py
dm me
good
so that's good, you have installed it correctly
can you hower over the error and send a screenshot of the message that the idea sends
there is no error
and why you need help?
you use vs code?
yes
try saving the file and reopening it in vsc
vsc doesn't directly show the imports as imports on the first time.
ı tried it
You using windows?
then open cmd
try to ignore the error
and type pip list
and show me the entire list it gives you
here its @solemn idol
if ı cant import it how can ı write codes lol
sometimes the idea is just stupid, that hapens sometimes
it's only an real error if you get a console error
first try it by your self
huh
strange...
try installing python as an extension for vsc if you havent already
maintained by microsoft
ı have already
here is the result
well that seems rather odd...
and this doesnt work in your terminal either?
perhaps its just vsc messing it up
for some reason
ok idk if that helps but create a venv:
python -m venv <project_path>
and reinstall pycord
ı do it many times
but not working
ı cant understand anything
firs install the venv
try pip installing discord
@valid ibex could you create a thread in #969574202413838426 and ping me after you created, this is a deeper problem
ı cant
it should be py-cord
I have em both
not pycord or anything that could cause conflict like having py-cord and discord at same time
try removing pycord
oh yeah
i would try using the venv
ı cant create button inactive
Some of my users have noticed that Pings from my bot have been slow, or occasionally not going through at all. Is this a bot issue or a discord issue.
The pings are part of a message in a @<###> format.
Is there a way to add a hyperlink to an embed footer?
Using fields is for squares! :( lol
nope, embed footers do not support clickable links at all, only text
Darn.
But
I dont know if theres a limit to fields, so you could always add another field
which could contain your hyperlink
True but the hyperlink is for a copyright page I'm required to add to this particular content so I was hoping to make it not so profound
Well you could add it in the author section
since that part does support links, not directly via the usual way of creating hyperlinks in an embed, but they do support it.
how can you understand why cog doesn't work?
and then it starts, and then after the changes it does not want and it is not clear why
For a command option decorator type as int is there a way to limit the int given from 1-10 for example? Aside from handling it inside the command itself
max/min_value
if commands.Bot is only for prefix commands then why is it so much used in cogs and also contains slash commands and stuff
?tag discord.Client
No tag discord.Client found.
?tag client
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
whats the event for updated channel overwrites
oh thanks
well depends on your error message ig.
What page do you recommend for learning Python?
Pycord Guide is a complete guide for Pycord. Learn how to create Discord Bots today!
Is it possible to create a restart command for my bot?
how can we format one liner for loops, like in the code below:
llist_embed.add_field(name='Activated Licenses', value='\n'.join([n for n in alic]))
i want to bold each element in the list but idk how to, i dont want to use it in the value directly coz then the format will apply to all items in the list except for the last one
how i can check if member has timeout?
Member.communication_disabled_until
and
one liner for loops are similar to normal loops
#Normal loop
b_list = []
for x in a_list:
y = some_func(x)
b_list.append(y)
#The same can be achieved using list comprehension and for loops
b_list = [some_func(x) for x in a_list]
#This is usually faster and more efficient
thanks
actually Member.timed_out would be better lol
Anyone know how to get the audit log of a member and how to filter it?
you can specify a member there
in the examples is a user=guild.me this is the ctx.author wright?
guild.me is the bot as a member
ctx.author will be the one who ran the cmd
use the one according to your objective
ok
is there any module to make paginators with buttons?
discord.ext.pages
How does Member.is_on_mobile() work? Because currently, it always shows me false, if i completely quit discord on pc and just use my mobile device.
You may need to fetch member to get the updated status
No get the guild, then fetch the member from the guild
i tried, but the status of the member is still 'offline'
ah maybe i need an intent...
Are you fetching from the guild?
Oh well that will do it
You should be enabling all intents
if you have them
nope, still offline
Do i need to activate any special scope before inviting the bot?
and this is my code
guild = await self.bot.fetch_guild(ctx.guild.id) # type: ignore
member = await guild.fetch_member(ctx.author.id) # type: ignore
print(member.name)
print(member.status)
bot and application.commands if you use slash commands
i use them already
well its a cog and the files are really long
could you specify what you need? Most of the stuff has nothing to do with this command
@faq.command()
async def list(self, ctx: discord.ApplicationContext, page: int):
'''Get a list of all FAQ-Tags'''
amount = 20
tags = self.data.get_all_tags(amount, amount * (page - 1))
# tabulate data
lines = tabulate(tags, 1, 100)
formatted = "\n".join(lines)
guild = await self.bot.fetch_guild(ctx.guild.id) # type: ignore
member = await guild.fetch_member(ctx.author.id) # type: ignore
print(member.name)
print(member._client_status)
print(member.is_on_mobile())
await ctx.send_response(f'\`\`\`{formatted}\`\`\`')
This is the command. (I want to know the status for the tabulate function, to make a table look better on mobile)
and main.py basically is this:
intents = discord.Intents.all()
bot = commands.Bot(intents=intents)
...
# run bot
loader.load(bot, 'cogs', ['test'])
bot.run(os.getenv('TOKEN'))
Do i need to activate any special permissions in the guild?
Duh. Fetching the member from the guild does not work. it will always return offline. If i get the member from the context directly, it does work. My problem in the beginning was just that i havent had any intents, but i needed them.
Anyways, thanks for your help @rare ice !
well i know that, but i dont understand how do you format every element in a list, like i want to bold all the items in the list, but i am unable to do that
uhh pretty simple, but depends on where you wanna do it
" ".join([f"**{word}**" for word in this_list])
oh alr, tysm
yeah
wait no
i think its drop table
brb
no?
DROP TABLE test will delete the entire table
if you only want to delete certain rows then use delete statement
https://www.w3schools.com/sql/sql_delete.asp
https://www.w3schools.com/sql/sql_ref_drop_column.asp to drop only certain columns
is there an event for category create i tried searching for on_category and catagory but i dont see anything about it
on_channel_create
oh its considered a channel
you would be looking for CategoryChannel
on_guild_channel_create right?
yea
alr
Anyone know why I might be getting this error:
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components.1.components.0.options: Must be 10 or more in length.
read the error
do you have a button with more than 10 in a label?
numbers or letters
I've had buttons with less than 10 characters in the label before, so i'm confused why that would be an issue
Like if I want a button that says "Done" that's 4 characters but completely relevant, right?
please send code
def createSelectMenu(self, itemType):
selectOptions = []
async def selectCallback(self, select, interaction):
await interaction.response.defer()
self.lackeyChoices[itemType] = select.data['values'][0]
selectMenu = discord.ui.Select(
placeholder = typeConfig[itemType]['placeholder'],
min_values = typeConfig[itemType]['min'], max_values = typeConfig[itemType]['max']
)
for itemName in self.user_closet[itemType]:
itemData = closetDict[itemName]
selectMenu.add_option(
value=itemName,
label=itemData['name'],
emoji=itemData["emoji"]
)
selectMenu.callback = selectCallback
self.add_item(selectMenu)
Function inside of a discord.ui.View class
I wasnt using .add_option before but I was trying to cover all my bases to track the error down
Here's the button
@discord.ui.button(style=discord.ButtonStyle.primary, label="Done")
async def submitLackey(self, button, interaction):
with BytesIO() as image_binary:
generateLackey(interaction.author.id, self.lackeyParams).save(image_binary, 'PNG')
image_binary.seek(0)
await interaction.response.defer()
await interaction.edit_original_message(content="", file=discord.File(fp=image_binary, filename=f'{ctx.author.id}s_lackey.png'), view=None)
- content="" it cannot be emtpy
- why do you use ctx.author.id in a button?
It wasnt empty, i removed that when I pasted
could you show full traceback?
for sure one moment
I think the issue is in where I am generating my option labels, itemdata['name'] might be throwing an undefined/none or somthing, but the "more than 10" error is confusing me on that
Ignoring exception in on_application_command_error
Traceback (most recent call last):
File "/home/turbo/bots/HalloweenBoy/venv/lib/python3.8/site-packages/discord/commands/core.py", line 127, in wrapped
ret = await coro(arg)
File "/home/turbo/bots/HalloweenBoy/venv/lib/python3.8/site-packages/discord/commands/core.py", line 911, in _invoke
await self.callback(ctx, **kwargs)
File "main.py", line 617, in costume
await ctx.respond(content="Pick your Lackey's costume!", view=userCostumeView, ephemeral=True)
File "/home/turbo/bots/HalloweenBoy/venv/lib/python3.8/site-packages/discord/commands/context.py", line 275, in respond
return await self.interaction.response.send_message(*args, **kwargs) # self.response
File "/home/turbo/bots/HalloweenBoy/venv/lib/python3.8/site-packages/discord/interactions.py", line 727, in send_message
await self._locked_response( File "/home/turbo/bots/HalloweenBoy/venv/lib/python3.8/site-packages/discord/interactions.py", line 975, in _locked_response
await coro
File "/home/turbo/bots/HalloweenBoy/venv/lib/python3.8/site-packages/discord/webhook/async_.py", line 213, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components.1.components.0.options: Must be 10 or more in length.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/turbo/bots/HalloweenBoy/venv/lib/python3.8/site-packages/discord/client.py", line 382, in _run_event
await coro(*args, **kwargs)
File "main.py", line 209, in on_application_command_error
raise error
File "/home/turbo/bots/HalloweenBoy/venv/lib/python3.8/site-packages/discord/bot.py", line 1009, in invoke_application_command
await ctx.command.invoke(ctx)
File "/home/turbo/bots/HalloweenBoy/venv/lib/python3.8/site-packages/discord/commands/core.py", line 359, in invoke
await injected(ctx)
File "/home/turbo/bots/HalloweenBoy/venv/lib/python3.8/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.1.components.0.options: Must be 10 or more in length.
Line 617 is where the message with the view is sent
can you print the view
sorry could you elaborate?
print(view)
yeah sure
sorry for the delay,
<class '__main__.costumeView'>
good catch lol
your select menu options don’t have a label
I've hardcoded it to be label="label" and this error still occurs
hmm
I think it has something to do with my value, because I didnt hardcode that, I just did and its working, ill look into the function that it gets that data from, thank you
In data.components.1.components.0.options: Must be 10 or more in length.
what’s in the view’s __init__
the fuck
I agree
im pretty confused lol
ill send the whole thing in a bit, im gonna go crazy if I dont go take a walk or something, glad its as confusing to you as it is to me tho
is there a way of having a slash command's option be either one type of input or another? for example, having input be either a str or a discord.Attachment
it has to be a string xor discord.Attachment
Yes
you can kiiinda get the same effect with having a string option and discord.Attachment option with both not being required
but that also allows both as inputs and neither as inputs
some_var: str | discord.Attachment?
Or a union?
Extension 'countrybot.cogs.utility' raised an error: TypeError: Invalid usage of typing.Union
Nope
@silver moat here's the entire class, I'm at a loss as to why this is happening
class costumeView(discord.ui.View):
lackeyParams = {}
def __init__(self, user_closet):
super().__init__(timeout=30)
self.user_closet = {
"accessories": ["knife", "wings", "cat", "witch"],
"backgrounds": ["candy", "night", "slime"],
"paints": ["paint_green", "paint_purple"],
"masks": ["trick", "treat", "zombie"]
}
for index, itemType in enumerate(user_closet.keys()):
if index == 4:
break
self.createSelectMenu(itemType)
def createSelectMenu(self, itemType):
async def selectCallback(self, select, interaction):
await interaction.response.defer()
self.lackeyChoices[itemType] = select.data['values'][0]
selectMenu = discord.ui.Select(
placeholder = typeConfig[itemType]['placeholder'],
min_values = typeConfig[itemType]['min'], max_values = typeConfig[itemType]['max']
)
for itemName in self.user_closet[itemType]:
itemData = closetDict[itemName]
print(f"name: "+itemData["name"])
print(f"value: {itemName}")
selectMenu.add_option(
value=itemName,
label=itemData["name"]
)
selectMenu.callback = selectCallback
self.add_item(selectMenu)
@discord.ui.button(style=discord.ButtonStyle.primary, label="Done")
async def submitLackey(self, button, interaction):
with BytesIO() as image_binary:
generateLackey(interaction.author.id, self.lackeyParams).save(image_binary, 'PNG')
image_binary.seek(0)
await interaction.response.defer()
await interaction.edit_original_message(content="Your newly dressed Lackey!", file=discord.File(fp=image_binary, filename=f'{interaction.author.id}s_lackey.png'), view=None)
is it possible to see who created a channel using on_guild_channel_create i also looked at channel_create audit log action but i didnt see anything there either
You would use discord.AuditLogActions
Alr never used audit log actions yet so that'll be fun
its pretty easy
Yall what am i doing wrong here, its claiming its getting unexpected key args
do you need privileged intents for User.display_avatar?
why do u have a callback inside another function
I think it has something to do with the view initiating before the select menu is added.
#1036089034197446667 message
i’ve made a post for it
simpler code
how am i supposed to do what i’m doing here?
The Guide for Views seem to focus on a single dropdown when using the decorator https://guide.pycord.dev/interactions/ui-components/dropdowns#usage-syntax
Is there a way to define multiple in this fashion (even though I don't really like them), or would I have to create separate classes? If I intend to have five dropdowns, do I really need five separate classes?
Or is 'select_callback' tied to that specific dropdown and I can just make multiple methods?
you can have 5 dropdowns in one view
^
Okay, the method name wasn't clear that it was custom and not an override of a specific callback class. Thank you
So, dumb question, will the callback be run when each dropdown is touched, or can I have a submit that processes it all then? (Although I am guessing I can't have five dropdowns with any other UI input, so maybe that's moot anyway)
they work just like buttons
Trying to create a UI that approximates a cron so people can schedule recurring reminders, but might have to get a little more creative/less complicated
Damn. Limited to 25 in a dropdown, so a Day selector is out.
Conflicting libraries.
I have some code in a loop. Anything that is an io method is accessing a sqlite3 database stored locally. Will having a loop like this with many iterations and many database reads and writes slow down my program?
@tasks.loop(minutes=30) # make this lower if it doesnt affect performance
async def advance_date(self):
for guild_id in io.get_guilds():
try:
rpdate = io.load_rpdate(guild_id)
channel_id = io.load_rpdate_channel(guild_id)
guild_channel = await self.bot.fetch_channel(channel_id)
last_posting = io.load_last_rpdate_posting(guild_id)
if dt.datetime.now() - last_posting > dt.timedelta(days=1):
await guild_channel.send(embed=discord.Embed(title=f"The RP date is {rpdate}.", color=discord.Color.blurple()))
io.save_last_rpdate_posting(dt.datetime.now(), guild_id)
except Exception as e:
if isinstance(e, RPDateNotPostedError):
await guild_channel.send(embed=discord.Embed(title=f"The RP date is {rpdate}.", color=discord.Color.blurple()))
io.save_last_rpdate_posting(dt.datetime.now(), guild_id)
Also, I do plan on upgrading the database reads/writes to aiosqlite. Assume this code is the same but with asyncio database reading and writing
on each iteration of the loop, it reads through the database containing the ids of all the guilds the bot is in, and then iterates through that list, where it loads data from a few entries. It then compares if one of the timestamp values is greater than 24 hours, and if it is, it will send a message and save the timestamp of when it sent that message
any idea how to fix this?
aiohttp==3.7.4.post0
disputils==0.2.0
pillow==9.1.1
py-cord==2.2.0
requests==2.26.0
discord-together==1.2.6
humor-langs==1.0.1
qrcode==7.3.1
akinator==1.0.3
pet-pet-gif==1.0.2```
my libs
It is easier than I thaught it would be lol
You must remove conflicting libraries.
sorry I should have probably just posted in here instead of making a new thread: https://discord.com/channels/881207955029110855/1036095812893147136
using version 2.2.2
already did thanks for advicing :)
oh actually I can replicate with just a simple example:
class Example(commands.Cog):
def __init__(self, bot_: discord.Bot):
self.bot = bot_
greetings = SlashCommandGroup("greetings", "cog greetings")
@greetings.command()
@option("test", "enter text")
async def hello(self, ctx: discord.ApplicationContext, test: str):
await ctx.respond("some response")
AttributeError: 'str' object has no attribute '__name__'. Did you mean: '__ne__'?
removing @option allows the type to be inferred correctly, but I'd expect @option to work here?
I guess as a workaround using type annotation seems to work here using discord.Option
why its not useable bruh
(i am not using class)
how do i block out token output from eval cmd
like if someone uses the eval cmd to get bot token, they get some other stuff instead
don't make a public eval command please
no i still want the protection if one of the devs run it
or if the eval gets hacked or something wrong happens
there's no foolproof way to do it
as an example, jishaku tries to filter it but fails when the send method is called directly
anyone?
oh
rip
where do i put on_timeout?
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\shan's python work\PycharmProjects\da_pycord_botto\venv\lib\site-packages\discord\bot.py", line 992, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\shan's python work\PycharmProjects\da_pycord_botto\venv\lib\site-packages\discord\commands\core.py", line 358, in invoke
await injected(ctx)
File "C:\Users\shan's python work\PycharmProjects\da_pycord_botto\venv\lib\site-packages\discord\commands\core.py", line 135, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: KeyError: 't'
how do i fixx
@client.slash_command(description="Get a sassy sticker to add to your convo.")
async def sticker(ctx, query: Option(str, "Enter the search query for your sticker")):
url = "http://api.giphy.com/v1/gifs/search"
params = parse.urlencode({
"q": query,
"api_key": giphy_key,
"limit": "5"
})
with request.urlopen("".join((url, "?", params))) as response:
data = json.loads(response.read())
print(data['data'[2]])
code
print(data['data'[2]]) this line you are getting the 'data'[2] of data. So you just need to more your ]
does pycord work on python 3.11?
not yet in a stable release
is there a beta release that does?
the master branch would work
ok, thanks a lot
I've been using it for a few days and it's worked fine
How can I use mentions as prefix when I use bridge commands?
Call commands.when_mentioned in ur bot's subclass
Can I use commands.when_mentioned_or('a!')?
Yes
U get mentions and prefix a!
and I can use slash commands?
ok, thanks
Np
Can I use MissingRequiredArgument, MissingPermissions from discord.ext.commands with bridge?
yes
In cog file I change @commands.command for @commands.bridge_command and have the error. Why?
bridge.bridge_command()
also you need a bridge bot
What does it mean "bridge bot"?
Concept
Oh, thanks
How can I use has_permissions with bridge? (for example: @commands.has_permissions(administrator = True))
just like normal
But when I used as default command, it work
what's not working?
does it always fail?
on_application_command_error is the slash command error handler
did you put the permission decorator below the bridge command decorator?
why is commands underlined?
because I import from py file
?
I import from discord.ext import commands from global_sets.py, not in file, where my code
In my code from global_sets import *
ah, it's actually bridge.has_permissions
could you update?
How can I update?
?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
Updated. The error is gone, but command don't work 😦
how would I send a message on an exception (for example: I want the bot to send "You are not the owner" when the "NotOwner" exception is raised
you can use the on_command_error for text-based commands and on_application_command_error for slash commands
which one(s) don't work: slash command, text-based, xor both
Other commands work, but in one slash command don't work
Maybe problem in await ctx.send()?
yeah, it should be ctx.respond
How can I send a message to a member?
DM them?
yes
await member.send()
And slash command will work?
yes
well, my understanding of that question is "will it work for slash commands?"
my bot is responding to commands properly but "discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction" is being raised
send code
nvm i fixed it, forgot to delete a line
is there any jishaku fork for pycord (with slash command support)?
you can just use jishaku
nah
?
do u expect there to be a fork of a fork for pycord that itself is a fork of what jishaku is forked from?
unlucky
i already sent a intent request its not approved yet
so i need slash command support
so is there any fork with slash command support?
If you want, you can use bridge commands (slash, text-based, etc)
i cant
i have no message intents
why?
no?
Is there an argument I can pass to view.disable_all_items() to only disable the view items for a single user?
wdym
https://docs.pycord.dev/en/stable/intents.html
@young bone read this
thanks
np
?
i think ill just port it myself xd
you can just use message contents without a bot verification
try it...
no, it's global
jishaku
its not working with py cord i think
no bob made one
no
but thats what i am asking for
how would I edit a channel's name
currently im getting "AttributeError: 'NoneType' object has no attribute 'edit'"
@tasks.loop(seconds=60)
async def my_loop():
channel = bot.get_channel("1036353629382254713")
await channel.edit(name=f"Players Online - {onlineUser}")
How do i access the response to a slash command? I want to add a reaction and later delete the response, but if i try
msg = await ctx.send_response(...)
the message gets send, but msg.message is Null
get_channel takes an int, not a string
ah ok
How can I get guild id in slash command? I try ctx.message.guild.id , but error discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'NoneType' object has no attribute 'guild'
restart your IDE
If you are using Pycharm, click Python Packages on the bottom left and add py-cord to dependencies
edited it to an int, now i'm getting discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
also make sure it's py-cord, not pycord
full traceback, thanks
Ignoring exception in command updateplayers:
Traceback (most recent call last):
File "C:\Users\Austin\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 127, in wrapped
ret = await coro(arg)
File "C:\Users\Austin\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 881, in _invoke
await self.callback(ctx, **kwargs)
File "D:\Coding Stuff\Python\Growtopia\Website Checker\websiteChecker.py", line 76, in updateplayers
await ctx.respond("Begun updating!")
File "C:\Users\Austin\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\context.py", line 258, in respond
return await self.interaction.response.send_message(*args, **kwargs) # self.response
File "C:\Users\Austin\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\interactions.py", line 712, in send_message
await self._locked_response(
File "C:\Users\Austin\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\interactions.py", line 959, in _locked_response
await coro
File "C:\Users\Austin\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\webhook\async_.py", line 211, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Austin\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 992, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\Austin\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 358, in invoke
await injected(ctx)
File "C:\Users\Austin\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 135, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
you can use ctx.message
show code for updateplayers
async def updateplayers(ctx, boolval: discord.Option(bool)):
channel = ctx.guild.get_channel(1036353629382254713)
updatetxt = onlineUser
if boolval == True:
my_loop.start()
await ctx.respond("Begun updating!")
if boolval == False:
my_loop.end()
await ctx.respond("Ended updating!")
Thanks for the answer, but do not need the original message, but rather the response from the bot. But i found out that
msg = await ctx.interaction.original_response()
does work.
try adding an await ctx.defer() at the beginning of that method
the original message is indeed the response.
oh well than that would be even more convenient. Thanks!
class ErrorHandler(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_application_command_error(self, ctx: discord.ApplicationContext, error: commands.CommandError) -> None:
r"""The event triggered when an error is raised while invoking a command.
Parameters
------------
ctx: :class:`commands.Context`
The context used for command invocation.
error: :class:`commands.CommandError`
The Exception raised.
"""
if hasattr(ctx.command, 'on_error') or not isinstance(error.original, Exception):
return
match error:
case commands.MissingPermissions():
embed = error_embed("Invalid permissions!")
case _:
match error.original:
case e.ChannelNotSetError():
embed = error_embed("Channel not set!")
...
case _:
print(error)
embed = error_embed("Unknown error!")
await ctx.respond(embed=embed, ephemeral=True)
This is a shortened version of my error handler. For some reason, when it responds with the "Unknown error!" embed, the message is not ephemeral, despite ephemeral being true. Furthermore, every other error message is ephemeral. Does anyone know what might be happening here?
Here is an example of this happening:
Should I be retrieving a message ID in on_raw_reaction_add(payload) from a DB that was created from a command? I feel like its unecessary and there's another way I should be doing it. The message that will be reacted to is created in a command and I need that message ID inside of on_raw_reaction_add(payload)
Is flagify deffered?
are the chances good? or i am doing something wrong
common has to be 60 or 100
(literally no idea if thats relateable to pycord)
seems reasonable
Yes
can i get message id of someone using a slash command with ephermal
i want report message link to go where they reported but not show there message
ephemeral messages are stored on Discord's server for 15 minutes.
so if the 15 minutes have elapsed, then the message would be deleted
Ephemeral messages are designed so that only your bot and the author can see the message.
but i should still be able to get message id and it will link to around that
it will link to nothing
let me show
gonna make link to this
#998272089343668364 message
it scrolls to where it took place
ok?
so is there a way i can get message id of slash command message
or msg = await ctx.original_message(); msg.id
so 100 common and other ones are just 40 25 15 etc it will be rare to get the mythic
You should add "Morbiulistic" and make that 1/1e8
How weights work is it is like tickets in a hat
So a, b, c with the weights 4, 2, 1 means
A is 4 times more likely to be selected than C, and twice as likely as B but only a 4/7 chance overall.
B is twice as likely as C but half as likely as A but overall has a 2/7
Hope that makes sense
did they ask for this explanation or
let's draw a tree
Is there any way to get a slash command in a subgroup without having to walk through all the commands in the SlashCommandGroup? I tried using bot.get_application_command("parent child") but it just returns None
How do I fix that AttributeError: 'Interaction' object has no attribute 'author'
interaction.user
oh, thanks!
why this doesn't work?
@option(required=True, name="name", description="asd")```
the @real compasstion doesn't display the name and the description
Use discord.Option
.docs discord.Option
If I want to store the usernames and userIDs of people who leave the server, would you guys recommend a MySQL/MariaDB/PostgreSQL server or should I go with a NoSQL implementation for the future stuff? Basically I'm trying to figure out which type of database has the most expandability for future projects
While of course having a decent async driver
any should be fine
Isn't there a method that extracts Mentionables (users/roles) from a string (not necessarily a Message), or did I make that up in my head?
Answer: raw_mentions and raw_role_mentions in discord.utils, it appears.
is it possible to use commands.cooldown decorator for events
its up to you
Ohhh now i get it how it works
how can i get arguments/options from my slash command using ctx?
Can I go above 25 choices inside of 1 choice?
Is there a way to disable a slash_command without making a check?
Is it possible to create a discord.ui.Select menu with a working callback without having to subclass it?
yes py select = discord.ui.Select(...) async def some_func(interaction): ... select.callback - some_func
Why I can't use ctx.message.created_at.timestamp() with slash commands?
ohh yeah i hadn't thought of that thanks!
because when a user runs a slash command it does not create a message.
Hey all! Is it possible to detect if a user is currently 'Priority speaker' while in a voice channel? VoiceState has a suppressed boolean but it's for stage channels only, trying to capture when a bot should start recording audio.
you would want to look at autocomplete
Here's the slash autocomplete example.
thanks!
class NitroView(View):
async def on_timeout(self):
expire_button = Button(label='Claim', style=discord.ButtonStyle.gray, disabled=True)
view.add_item(expire_button)
view.remove_item(accept_button)
nitroexpire_embed = discord.Embed(title="You've been gifted a subscription!", description='Hmm, it seems someone already claimed this gift.')
nitroexpire_embed.set_thumbnail(url='https://i.imgur.com/wI9q2Md.png')
await self.message.edit(view=self, embed=nitroexpire_embed)
this is my view, and i get an error on timeout, that 'NoneType' object has no attribute edit
I am currently getting these errors while trying to host on a VPS:
Traceback (most recent call last):
File "/home/ubuntu/.local/lib/python3.10/site-packages/discord/cog.py", line 757, in _load_from_module_spec
spec.loader.exec_module(lib) # type: ignore
File "<frozen importlib._bootstrap_external>", line 883, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "/home/ubuntu/YCCUtilities/cogs/commands_2.py", line 18, in <module>
from normalize import normalize
ImportError: cannot import name 'normalize' from 'normalize' (/home/ubuntu/.local/lib/python3.10/site-packages/normalize/__init__.py)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/ubuntu/.local/lib/python3.10/site-packages/discord/cog.py", line 757, in _load_from_module_spec
spec.loader.exec_module(lib) # type: ignore
File "<frozen importlib._bootstrap_external>", line 883, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "/home/ubuntu/YCCUtilities/cogs/commands_2.py", line 10, in <module>
from main import Duration, Punishment, PunishmentFromMessage
File "/home/ubuntu/YCCUtilities/main.py", line 240, in <module>
load_cogs()
File "/home/ubuntu/YCCUtilities/main.py", line 118, in load_cogs
bot.load_extension(f'cogs.{file[:-3]}') # loads every python file
File "/home/ubuntu/.local/lib/python3.10/site-packages/discord/cog.py", line 893, in load_extension
self._load_from_module_spec(spec, name)
File "/home/ubuntu/.local/lib/python3.10/site-packages/discord/cog.py", line 760, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.errors.ExtensionFailed: Extension 'cogs.commands_2' raised an error: ImportError: cannot import name 'normalize' from 'normalize' (/home/ubuntu/.local/lib/python3.10/site-packages/normalize/__init__.py)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/ubuntu/YCCUtilities/main.py", line 240, in <module>
load_cogs()
File "/home/ubuntu/YCCUtilities/main.py", line 118, in load_cogs
bot.load_extension(f'cogs.{file[:-3]}') # loads every python file
File "/home/ubuntu/.local/lib/python3.10/site-packages/discord/cog.py", line 893, in load_extension
self._load_from_module_spec(spec, name)
File "/home/ubuntu/.local/lib/python3.10/site-packages/discord/cog.py", line 759, in _load_from_module_spec
del sys.modules[key]
KeyError: 'cogs.commands_2'
What could potentially cause this issue
nvm, resolved.
can someone help
learn python
bruh
there's so many errors
like what
im not gonna hold a lecture for you
it worked before
atleast can you tell some major point outs
How can i get a member timeout?
async for thing in ctx.guild.audit_logs(user=member, action=discord.AuditLogAction.member_update.mute):
embed.add_field(name=f"Muted for {thing.target}", value="h")```
Help pls
anyone knows whats wrong with my code?
(its supposed to print something in the terminal when someone joins/leaves a server)
you need intents
you also have to do it at the website
learn what self does before you try to use it
Anyone ever had problems with commands permissions resetting in the Integrations Tab in Server settings on command sync?
Perms don't reset for commands loaded before bot.run(), but they are reset for commands loaded after the bot.run()
Are multi-line string input Options a thing yet?
this isn't supported by discord yet, Modals are a great alternative however
Gotcha, thanks. I just remembered them demoing them and wasn't sure if they were out yet. Unfortunately, modals have a couple of issues, but if they're the only option, they're the only option!
Is it possible to have a button (sent with an embed) callback in the same function where it was sent from? So that I can edit an embed using an existing variable within a function?
you can create an instance of the button in the command. example next
async def command(ctx):
button = discord.ui.Button(label=“Hello”)
async def callback(interaction);
pass
view = discord.ui.View()
button.callback = callback
view.add_item(button)
await ctx.respond(“Hi!”,view=view)
Ah interesting! Thanks, I'll give this a shot once I'm home from work
just looking to confirm you can only have 1 interaction response, from an interaction component? Couldn't have a button edit a message and launch a modal?
- yes
- yes
.docslink discord.Interaction.edit_original_response
... isn't a response
ty
ahh so that could be used to edit the view, to disable the button, and the response interaction could launch the modal?
yes
I couldn't get edit_original_response to work(kept getting webhook error), but this did, does that seem right? to be clear its editing an ephemeral message send by another interaction response.
@discord.ui.button(label='Change Bid', style=discord.ButtonStyle.primary)
async def change_bid_callback(self, button, interaction):
await self.message.edit(content="Changing your bid", delete_after=3)
await interaction.response.send_modal(BidModal(self.item, self.ctx))
it should work
ValueError: could not find open space for item
modal can have only 5 inputs?
hi, is it possible to make dynamically generated buttons (view) to be persistent?
4?
Discord limit
Hello, Why this command does not work? I don't get any error, but it doesnt work + it terminates the bot
@bot.command()
async def checkcode(ctx: discord.ApplicationContext, codigo: str):
try:
check = licencias.find_one({'licencia': codigo})
if check == None:
await ctx.respond('Ese codigo NO es valido!')
ae = False
else:
ae = False
if check['type'] == 'mon':
monedas = check['monedas']
elif check['type'] == 'rol':
roleid = check['rol']
dias = check['dias']
embed = discord.Embed(
title='Propiedades de este codigo',
color=discord.Colour.blurple()
)
embed.add_field(name='tipo', value=check['type'])
if check['type'] == 'mon':
embed.add_field(name='monedas', value=monedas)
elif check['type'] == 'rol':
embed.add_field(name='id del rol', value=roleid)
embed.add_field(name='dias', value=dias)
await ctx.respond(embed=embed)
except Exception as e:
await ctx.channel.send(str(e))
Try debugging the code to see if it's running or if it get stock in some place
The code does not get stock
how can i use on_interaction’s interaction.data
I want to know ctx.author in on_interaction
so…
any one can help me

interaction.user?
no
in on_interaction
but i want to know ctx.author
isn’t interaction.user
@unborn veldtIt's the same
i think is interaction.data
but
i don’t know how to use this
you want to get the user that triggered the interaction right?
user in interaction it's the same as author in context
def on_interaction(interaction):
interaction.user
What I want is to know the user of slash_command in on_interaction
can i do this?
🤔
Owo(?
user id? user name? user # number? you can get all of that with interaction.user
if this make it easier for you, just do this:
author = interaction.user```
I'm trying to get what you mean...
ok
What I did is defining author as interaction.user, because interaction.user has the same clases of ctx.author
i cant seem to make the bot prefix work, the mention works but not the prefix, even if i just put the prefix. I had this exact same code on another bot with another version of the pycord from github and it was working
bot = commands.Bot(
command_prefix=commands.when_mentioned_or('d!'), activity=activity, status=status, help_command=None, intents=intents, case_insensitive=True)
Let me see if I understand the problem.
So I member use a slash command, and on_interaction is not triggered by that, but on_interaction is triggered when a user pressed the button and you want to on_interaction be triggered with the slash command, right?
almost
try putting```py
command_prefix='d!'
but slash_command.author can’t use button
Mean ‘a’ use slash_command but ‘a’ can’t use button.
with command_prefix='d!'
with the mention
beside "a" any other member can use the button?
The on_guild_[un]available events refer to Enabling/Disabling Invites?
Or does pausing the server not throw any event? I guess it's a guild edit event
How do I get the emoji id from a reaction
For example this, how can I get the emoji ID
If I right click -> Copy ID, it just copies the message id
Hm. That might be a regression; I don't remember if it ever copied the ID
Two ways:
You can right-click and "Copy Link" or "Open Link". The filename is the snowflake ID
Escape your emoji by putting a backslash in front of it
escaping 
would be \:troll~1: which will print
<🧌945379443508150363>
lol stupid discord, but I think you get the idea
Programmatically from a reaction is a little easier. on_reaction_add is passed a Reaction object.
reaction.emoji is an Emoji object, so reaction.emoji.id is the ID.
Only works for custom emoji, not built-ins; emoji will simply be the str emoji character
Thanks, right click open link works 👍
Back on Enabling/Disabling server invites. It seems that this action is not passed into the Activity Log. Is there any way of determining who changed the setting?
I have a bot that posts an embed and some buttons.
The left and right -most buttons cycle through each page of the leaderboard by getting the next page's data and editing the original message with an updated embed.
Whenever I press one of the next page buttons, it seems to work for the first couple of pages, and then I get an error saying "This interaction failed." with error code 10062.
I have no idea what's causing this error and the weirdest part is that it breaks at seemingly random intervals. Sometimes I can press the button all the way until page 6, sometimes it breaks on page 3.
Is it something to do with like...discord rate limits stopping the bot from editing the message? Or maybe something to do with the interaction timer for the button?
very likely you're getting ratelimited on how quickly you can edit the embed, and then by the time pycord is finished waiting for the limit the interaction has expired
you could solve this by deferring the interaction before attempting to edit the embed, that way the interaction won't expire so quickly
I'm also getting webhook error when using it
From docs
Raises
HTTPException – Editing the message failed.
you can't spam buttons no
im not trying to spam the button, im just trying to click it all the way from page 1 to page 9 but it always breaks somewhere in the middle
ill give this a shot, ty
I fixed it by using
interaction.response.edit_message()
the problem there is, you can only have one interaction.response so in my case I was wanting to disable a button, or edit an embed, while also launching a modal
I used self.message.edit() to get it to work
So I am having a problem with my bit, occasionally when a slash command that loops through data is run, the bot will go offline. Is this because of the interface with the heartbeat? The function is async, so shouldn't this not interfere with the heartbeat? Shouldn't pycord automatically attempt a reconnect?
depends on what kind of data you're getting. is it api calls?
It's a SQL database call, and then loopinf through the data, but it's using async Sqlalchemy
dunno then, open a post and provide relevant code
A few different loops have done it, here is one of them, probably the simplest loop that's caused it, so easiest to post the code
can’t use
hey so whats the function to get message history in channel
Make sure that when you declare a button disabled is false
i found the name for some reason i thaught it was channel.messageable history but ig its just history
?
Doesn't this work for everyone?
All buttons are disabled False by default
only slash_command user can’t use
Because while loops block the code
Anyone know how I can pass in an async function result as a parameter in another async function?
Basically I have an async function that outputs a list and want to use that list as my optionchoice for a slash command
Here's the slash autocomplete example.
@severe comet
keep in mind that you still have to validate the inputs after they are inputted.
gonna need to see more code to tell you anything
there's nothing obviously wrong in what you've shown us so far
tyty \o/
It works perfectly in my server, but in other servers, what the bot is supposed to do after the user reacts, doesnt work
Thanks, that was xd
why is this thing here
[mp3 @ 00000176b18cfa00] Estimating duration from bitrate, this may be inaccurate
[mp3float @ 00000176b18f8340] Header missing
Error while decoding stream #0:0: Invalid data found when processing input
everything works well?
If the command is executed for a long time, then discord sends - "The application did not respond". How can I increase the waiting time for command execution
defer the interaction
Hello, i have a big problem
I've made some buttons and i want that the on_timeout doesnt trigger if the user used a button
There's a way to make this ?
Traceback (most recent call last):
File "C:\Users\shan's python work\PycharmProjects\da_pycord_botto\bot.py", line 581, in <module>
member: Option(discord.member, 'Enter the member you would like to ask the question',
File "C:\Users\shan's python work\PycharmProjects\da_pycord_botto\venv\lib\site-packages\discord\commands\options.py", line 156, in __init__
raise exc
File "C:\Users\shan's python work\PycharmProjects\da_pycord_botto\venv\lib\site-packages\discord\commands\options.py", line 151, in __init__
_type = SlashCommandOptionType.from_datatype(input_type)
File "C:\Users\shan's python work\PycharmProjects\da_pycord_botto\venv\lib\site-packages\discord\enums.py", line 693, in from_datatype
if issubclass(datatype, str):
TypeError: issubclass() arg 1 must be a class
Process finished with exit code 1
Im getting this error for the following code
@client.slash_command(description='Play the classic backbench truth or dare game with your friend')
async def truthordare(ctx, truthordare: Option(str, 'Ask someone whether truth or dare, then enter the query here',
choices=['Truth', 'Dare']),
member: Option(discord.member, 'Enter the member you would like to ask the question',
required=False)):
global url
if truthordare == 'Truth':
url = 'https://api.truthordarebot.xyz/v1/truth'
elif truthordare == 'Dare':
url = 'https://api.truthordarebot.xyz/v1/dare'
resp = requests.get(url)
e = discord.Embed(title=truthordare, url="https://play-lh.googleusercontent.com/"
"slAvsPRR2-TSV1P96Ob6e8JyvaTrRHnNVG6-kQN3XDHKWhGNufdqcUSGjAetpmFHBVQ",
description=resp['question'])
await ctx.respond(f'{member}', embed=e)
@commands.slash_command(guild_ids=[GUILD_ID], description="test")
async def testh(self, inter: discord.Interaction):
await inter.response.defer()
await asyncio.sleep(2)
await inter.response.edit_message(content="test")
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: InteractionResponded: This interaction has already been responded to before```
how is it correct?
You don't receive discord.Interaction, you receive discord.ApplicationContext
So you just do ApplicationContext.defer and then ApplicationContext.respond and the library will manage what to do.
Do you use discord.py?
thanks
discord.Member i believe
anyone know why my variable wont update through the button callback? i've tried some random things and not sure why it wont update
because that is not actually the callback
can someone point me in the right direction on which branch i need to get for python 3.11 support?
wdym it’s not the callback?
everything else works
ok and u've printed in the supposed callback?
You'll need to install the master branch
?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
ik python 
this is really basic python, u should know
show your button setup
yeah ik it’s basic i’m just rusty and never rly got familiar with async functions
async is basic
10 its
20 this
30 basic
yeah ig so
calling async functions is basically the same as normal functions. provide code or nobody will help you as it is not possible
here is my code, i had to cut out random parts since it wouldn't let me send it
would it be better to put the stopp variable in the command and not the __init__?
why do you have one variable as a self var and one as not? remove the variable that is not in the instance of the class
btw use interaction: discord.Interaction instead of ctx in your callback for better typehinting
oh ok thank you
Typehinting is magic. It should be forced.
yeah it really is magic
Pylance has some setting somewhere
I use pycharm
It possible to disable buttons in a view for only certain people? For example just allow buttons to be pressed by the original response author?
nope
async def booster_update(ctx):
booster_role = discord.Guild.get_role(1037515948283936900)
embed = discord.Embed(title="Boosters",description="",color=discord.Color.blue())
names = ""
for member in booster_role.members: names+=f"{member}\n"
channel = bot.get_channel(1023695423061372949)
embed.add_field(names="",value=names,inline=False)
await channel.send(embed=embed)
bot.run(TOKEN)
I keep getting this error
Application Command raised an exception: TypeError: Guild.get_role() missing 1 required positional argument: 'role_id'
but I do have the role id in there
I am looking for something we can use for power rankings. I like using tiermaker or tierlists. does anyone know of any similiar sites that have an api?
i like the ease of drag and drop for the user. ideally they would just submit a link with like /rankings link_to_yours: and i have it parse it + math
Hi, I want to run my bot with loguru instead of logging...
For the code I write myself and the code in my main file this works fine.
I use a custom handler for logging, but the things in cogs and other files, this does not work, even if i set the custom handler there....
Any Ideas on what to do?
Is this supposed to work?
.tag tias
._.xd
Lol wow
It’s not that hard to run your code and see if it works.
So did it work?
No xd, thats why I asked
is it possible to edit the content of a message from another message's view? In my example I'm trying to have a slash command send an ephemeral message to the author, that controls an embed in a followup message that everyone else can see
Quick question because I've never specified only two intents, but does discord.Intents.all() attempt to load all intents Discord has, or all intents that the bot is enabled for?
all intents that exist
Thank you
@round rivet is it possible to get old webhook data to be reused?
If i have the webhook id?
yeah
Probably a question for the Developers: Is it possible to convert the async def received_message(self, msg) inside class DiscordVoiceWebSocket to a bot.event?
Inside received_message contains the below code:
elif op == self.SPEAKING:
ssrc = data["ssrc"]
user = int(data["user_id"])
speaking = data["speaking"]
What I need is the speaking var as this contains the op code (1) for normal speaking, (5) a user who is a priority speaker inside a voice channel. I'm thinking if i use it as an event i'll be able to action what i need in there, any help/ ideas would be appreciated, thanks!
So, I have a aiosqlite instance in main.py, how do I use that in cogs?
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("level.db"))
await asyncio.sleep(3)
async with bot.db.cursor() as cursor:
await cursor.execute("CREATE TABLE IF NOT EXISTS levels (level INTEGER, xp INTEGER, user INTEGER, guild INTEGER)")
print("Bot is ready!")
``` (my on_ready function)
assign that instance as a bot var/function (e.g. bot.db = ...) then you can access it from self.bot
Here's what sucks about this channel sometimes. Its only active during the time when I'm asleep.
:(
hm
so bot.db = Bot()?
bot() is my bot class
No
then how?
bot.db = whatever
whatever=?
and then call the variable through self.bot
ok
bot.db = await aiosqlite.connect("level.db")?
sure that works
alr
discord.errors.Forbidden: 403 Forbidden (error code: 50021): Cannot execute action on a system message
Is there a way to filter out the system messages?
if i'm want to add error how i can to do this?
bc when i did this not work work
NVM MB
lil bro censor guild id as if we could use it for something
I am trying to import a class function from my other python file which scrapes instant gaming website trending games and returns 20 games each in a list. I want my bot to respond in a message with all those scraped games when /keys command has been given. But ctx.respond(<passed class function>) does not work. Any ideas on how to properly pass my own class functions?
by adding a __str__ method* to the class that is called, create an instance of the class and then just do str(class) or class.__str__() (wherever u want to call it)
much appreciated!
Hi I know members in voice channel are ordered by alphabetical name, but how about symbols. It seems like symbols are ordered higher than the letter 'a'. Is there any way I can find the order of all the symbols
How can u use custom emojis inside of an embed?
nvm i got it
I am trying to make a bridge command that reacts on both, prefix and slash command. But there is a problem with the second args = ctx.message.content.split(' ')
@bridge.bridge_command(description="xxx")
async def xxx(self, ctx):
if isinstance(ctx, commands.Context):
args = ctx.message.content.split(' ')
if len(args) >= 2:
frage = ' '.join(args[1:])
mess = await ctx.send('xxx'.format(frage))
await asyncio.sleep(2)
await mess.edit(content='xxx')
#some other stuff
await ctx.message.delete()
else:
args = ctx.message.content.split(' ')
if len(args) >= 2:
frage = ' '.join(args[1:])
await ctx.respond(ctx.author.mention + ' xxx `{0}` xxx: `{1}`'.format(frage, random.choice(discordVariable.antworten)))
args = ctx.message.content.split(' ')
AttributeError: 'NoneType' object has no attribute 'content'
it's likely just their unicode character order
you can use ord to get any character's unicode value, and chr to do the opposite
do you have the message content intent


