#Basic Pycord Help (Quick Questions Only)
1 messages · Page 64 of 1
seems to be fixed
never mind, rate came back after 12 reactions
after that reacts once every 400 so messages (should be doing every 100)
i dont understand why it ratelimits and doesnt send reactions even though its like 1 reaction every 2 minutes
How do I allow the user to select multiple roles within a command parameter?
You can't. That's a Discord limitation. Use role selects.
Ok thanks!
You could use a role select menu after the command is run (If that works for you)
Do you have multiple bots running? Try to get logging to see how many times the reaction request is sent
https://docs.pycord.dev/en/stable/logging.html
Yea I'm probably going to do that
what is the difference between pycord and discord.py?
Like, do they work differently?
yes. Most notably, Pycord and discord.py have different application command systems.
If I'm working with a command that displays a select menu and then resumes the command after the user has made their selection, what's the easiest way to resume the command after a selection has been made?
Currently i'm using await view.wait, which seems to just be waiting for it to time out
self.stop()?
But that can't be run in the command itself, right? Only in the callback?
Basically players create a treaty with a command, are presented with a select menu to select the people involved, and then the command resumes and adds the data to a JSON file
self.stop() also triggers await view.wait()
Good afternoon Yesterday I made endless buttons, but in the end nothing works.
As a result, all buttons are valid for 5 minutes, after which they do not work.
Here's the persistent example.
and you spelled timeout as timeoiut
Thank you very much 😁
IDEs like Pycharm would mark that as a warning.
😥 Still doesn't work...
Please look at the example
I think it can put 3600 in a timeout. Is it counted by seconds?
@silver moat
Buttons are disabled every 5 minutes
@bot.event
async def on_ready():
bot.add_view(TlB()) # Registers a View for persistent listening
Now I wrote endless buttons and ran into a problem
@commands.Cog.listener()
async def on_ready(self):
self.add_view(TlB())
I need a similar function to work in COG
self is the cog. self.bot will be the bot
add_view is a method on the bot and not the cog
nope
Ok
I made a 'self.bot' but now it gives me an error. And I don’t even know how to change it.
class TlB(discord.ui.View):
def _init_(self):
super()._init_(timeout=None)
@discord.ui.button( label...)...
class NS(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
self.bot.add_view(TlB())
This is roughly what is happening now.
looks right
whats the error?
you need to set custom id on all the items in the view
class TlB(discord.ui.View):
def _init_(self):
super()._init_(timeout=None)
@discord.ui.button( label="Confirm participation",custom_id="button-1",emoji="✅",style=discord.ButtonStyle.success)
async def button_callback(self, button, interaction):
await interaction.response.send_message(f"You confirm participation.",ephemeral = True)
@discord.ui.button( label="Admin button",custom_id="button-2",emoji="🔄",style=discord.ButtonStyle.primary)
async def second_button_callback(self, button, interaction):
await interaction.response.edit_message(view=self)
guild = interaction.guild_id
msg = interaction.message
cursor.execute(f"SELECT rowid,* FROM vipteamlist WHERE server_id = {guild}")
item2 = cursor.fetchmany(4)
db.commit()
b = ""
i = 0
for el in item2:
i+=1
b += f"**{i}**.:coin: __{el[1]}__ | {el[2]} | <@{el[3]}>\n"
cursor.execute(f"SELECT rowid,* FROM teamlist WHERE server_id = {guild}")
item = cursor.fetchmany(16)
db.commit()
a = ""
f=4
for el in item:
f+=1
if 4<f<17:
a += f"**{f}**. __{el[1]}__ | {el[2]} | <@{el[3]}>\n"
if f>16:
a += f"Reserve🔴**{f}**. __{el[1]}__ | {el[2]} | <@{el[3]}>\n"
embed2 = discord.Embed(title =f":scroll: TEAM LIST :scroll:",description=f"**🕐Time: 21:00 Moscow **\n \n{b}{a}", colour = discord.Colour.embed_background())
embed2.set_footer( text =f'To confirm participation, click on ✅')
await msg.edit(embed=embed2)
I think the problem is that I write the event after the class🤔
that doesnt matter
Then what doesn't he like?
def _init_(self):
super()._init_(timeout=None)
@proud mason What's wrong?
you need double underscores here
not just one
aah lmao
ahahahaha
@soft girder do you have the Python one installed for Visual Studio?
@young bone yes
Is there any problem with it?
hey i am using mongodb for my bot, should i make connections in every cog?
or is there any way to make connection in one place and access it in every cog
Realistically you should only need to make a connection when you actually need to access the database. Your best option is probably to set up a connection pool and use those connections on-demand. Unless you have something that is very frequently accessing the database, in that case having a persistent connection would be better.
Uh ok
and i am having a problem here
TypeError: duplicate base class TimeoutError```
I am trying to use aioredis
@bot.event
async def on_ready():
bot.pool = await aioredis.create_redis_pool('redis://localhost')```
What are you using redis for?
for storing stuff
You know that redis doesn't persist any data right? As soon as you restart your redis instance all data is going to be cleared.
Redis is a cache, not a database. It's literally the same as storing things in a variable.
i am trying to avoid mongo db cuz its only 512 mb
what is redis?
So it's useless unless you have multiple applications needing to access the cache
storage
ye thanks for the help
Redis is an in-memory database / cache
It's mostly used when you need to cache things that are accessed by multiple applications
my bot is going to store alot of data that is why i am trying to avoid mongodb... are their any other nosql alternatives?
Wdym only 512mb? It's as big as your storage space is?
my bot is going to store alot of data tho
And?
is it enough?
Wtf do you mean by Mongodb only being 512mb? That makes no sense
wait a sec
atlas's free plan is 512 mb
If your host only has 512mb then it doesn't matter what database you use? It's still going to b 512mb
Host your mongodb instance yourself, don't use atlas

Sqlite files are very small. You would need hundreds and thousands of lines to hit 10MBs ngl
alr
hmmmm so should i stick to sqlite?
the free atlas tier isn't even meant to store things, it's just a testing space to play around with
its just that nosql is easier to manage
Yea sqlite is pretty good and powerful. Asqlite library and WAL mode will help you achieve best performance out of it
True that 
That's what I am asking keeping in mind there are 20,000 members and each of them is storing bunch of data.
Inventories, money, and others
Storage is cheap, use whatever database you prefer
it's not like you're going to have 1TB of data just because you're storing a few thousand members
you'll need literally millions of rows in your database tables before you need to worry about disk space
i should use json then 
no
lmao
||You can even estimate your db size to a very large extent||
One way for SQL- each datatype has a specified size. find the size of 1 row based on its columns. You can get the size for sqlite data types from google. Multiply this row size by the estimated number of rows. Do this for all the tables and add it
Add some overheads to this and you will get a fairly accurate db size estimate
To put into perspective, I have a database table here with ~10k members. 8 columns with various types of data, and it's not even 1MB using Postgres
In case you want to look into some additional features, asqlite (not aiosqlite) offers connection pools. This can offer slightly better async performance during high activity times
But aiosqlite is pretty good too
Just thought of letting you know
@proud mason
py -m pip install asqlite
ERROR: Could not find a version that satisfies the requirement asqlite (from versions: none)
ERROR: No matching distribution found for asqlite```
- i found nothing on the web regarding asqlite
https://github.com/Rapptz/asqlite
First link 💀
What python version?
Wait, danny made that.
I found a solution to edit slash command response on stackoverflow: ctx.edit("new content") but it returns an error:
TypeError: Interaction.edit_original_response() takes 1 positional argument but 2 were given
I didn't find any other solutions to this. How do I fix?
Yea
Google thought you made a typo
Pass content="..."
sorry if i ask alot of questions but
@bot.event
async def on_ready():
bot.db = await aiosqlite.connect()```
should i establish connection once or do it in each and every command
As a kwarg
can I pass extra arguments to a Loop object?
Ah, I forgot that edit uses the complete JSON table of the message. Thanks
or do it like this
@bot.command()
async def test(ctx):
db = await aiosqlite.connect()
#stuff here
await db.close()
and what about closing the databse? should i worry about it
If you are using aiosqlite then per-command should be better. Use async context manager
How often is the command being run? I would say if it is greator than 5-10m per time it is run than you should close it otherwise you could keep it open.
I dont think it makes sense to ever disconnect from the database all together.
I think this will be a dumb question. But how to make a button that can be used by a person who has certain permissions .For example : administrators.
There is not built in way in discord. In the callback you would have to check interaction.user.guild_permissions with the required permissions.
Yea
If you are using ephermeral then probably check if the user has permission if doesnt just disable it
Anyone familiar with bot computing/data requirements? We’re running an online game on March 25th with 36 people on discord, with the bot performing a few key tasks, so will be processing a lot of commands. I currently have it running on a Heroku basic dyno with 512mb RAM. Should I move it to a VPS? It only needs to be used for a few hours so I don’t care about persistency but it will be heavily used
Look at Vultr, they charge per hour instead of per month. So if you only use your bot for a few hours it'll be very cheap.
And the hardware requirements depends a lot on what your bot is actually going to do. But if it really will be "heavily" used, then at least 2G RAM and 2vCPUs.
hey all, I want to make a sound dispatch command somewhat similar to Airhorn Solutions... This is what I made but I am having an error
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'VoiceChannel' object has no attribute 'play'
Code:
@discord.slash_command(name='quack', description = 'Quack, Quack, Quack!')
async def quack(self, ctx):
vc = ctx.author.voice.channel
if vc == None:
ctx.respond("You must be connected to a voice channel!")
else:
vc.connect()
vc.play(discord.File('duck-quacking-37392.mp3'))
where am I going wrong?
Could give serverless a look. It’s very cheap for many uses. Just be sure to have good indices.
But also, 512MB will probably go further than you think
Pycord and Wavelink try to keep the playing of audio as simple and easy as possible, to keep making Discord
.idw
Saying it doesn't work or asking what's wrong with this code is not helpful for yourself or others.
Describe what you expect and/or tried (with your code), and what isn't going right.
Please provide any errors you get for optimal assistance.
How would i make a slash command option user selection only? I mean to get the parameter to list all members without a specific role?
Use autocomplete and generate your own list
Here's the slash autocomplete example.
Yeah, I'm trying to figure out how to get the users of the currect guild that doesn't have a specific role.
https://docs.pycord.dev/en/master/api/models.html#discord.Role.members
https://docs.pycord.dev/en/master/api/models.html#discord.Guild.fetch_members or https://docs.pycord.dev/en/master/api/models.html#discord.Guild.members
Models are classes that are received from Discord and are not meant to be created by the user of the library. Attributes key, url. Methods def is_animated, async read, def replace, async save, def ...
what?
Why do you want to create an instance of the Role class?
So, I'm trying to make a slash command that has two required parameters, where the first one lists all members without a specific role. The second consists of 3 roles.
I somewhat understood the autocomplete feature
That doesn't answer why you're trying to manually initialize a new instance of the role class?
I don't know how to do it?
I'm asking you why you're trying to do it in the first place
Because I assumed I could use discord.Role.members
You can, but why do you need to manually create an instance?
I wasn't sure know what that does. I'm new to pycord and python
Read rule 1 in #help-rules
I assume I can't even ask for help to HELP me LEARN it
?tag learnpython
To be clear:
When we tell you to learn Python before asking questions here, it is not meant in a derogatory way, we are not calling your dumb or incompetent. We are simply stating the fact that usage of PyCord requires a fair bit of knowledge with using OOP, Async/Await etc. in Python. If you are not comfortable with these concepts, chances are you will not understand the answers given to you in this channel.
We understand that everyone learns at a different pace, and your current knowledge with Python may have been enough so far. When we say "you need to learn Python", it is most likely a sign that we have given you an explanation that you could not understand and there is no way for us continue to help you without spoonfeeding.
The point is that you won't understand the help we give you, meaning the only option we have is to just give you finished code, which we do not do here. You need to know the basics before making a bot.
We're here to help you with issues regarding pycord, not teach you basic Python concepts so that you'll understand our solutions.
@discord.ui.button( label="Admin button",custom_id="button-2",emoji=":arrows_counterclockwise:",style=discord.ButtonStyle.primary)
async def second_button_callback(self, button, interaction):
await interaction.response.edit_message(view=self)
guild = interaction.guild_id
msg = interaction.message
interaction.user.guild_permissions(administrator)
Hello everyone. Now I wrote the code. You need to know how to organize the button so that only administrators can click on it.
Either implement a check on the callback or override interaction_check
How do I do a persistent view, if the view has parameters that changes the custom_ids of the buttons?
bot.add_view(reaction_roles.ReactionRoles.ReactionView([])) # Just leaving an empty list doesn't make the view work
How do I set the status of my bot? I can't figure it out for some reason
async def on_ready():
await client.change_presence(status=Status.online, activity=Activity(type=ActivityType.custom, name=status))
print(f"{client.user} is connected.")```
note that the status variable is just a string
Does anyone have a recommended open-source bot made with pycord that I could review the code of to learn the library?
you learn how to use pycord by reading the docs
Why does it change the custom_id's?
Bots don't support custom activities.
Posted in #1084642192456417360 message
It's for reaction roles
But a select menu is a LOT easier
is there a common way people remove button's when a view times out? I have a sorta of solution but it has some weird kinks
Edit the message and pass view None?..
that's kinda what I'm doing but it only seems to work for the most recent message and also doesn't like it when it has attachments.
What and what
if you run 1 command that sends a message with buttons, then another before the first times out the first keeps the buttons.
All you need to do is override on_timeout of the view and edit the message with view=None.
It sounds like you're making it way more complicated than it has to be
I could have sworn I tried that, thought when I did it had a issue with self.message but it worked fine now so 🤷
this makes things so much easier
One message removed from a suspended account.
in modals, if a non-required field is blank, what is the default value? None?
You could set "None" to be default
through?
i see this
i would prefer if it was None already tho
Empty string I believe.
alright
is there a way to send a modal after sending a select menu?
interaction.followup has no option for sending a modal
send_modal()?
use interaction.respond
One message removed from a suspended account.
okay thank you
last question, im subclassing a MyView(View) inside of a Cog class, how do I access the Cog class's attrbutes?
You can set the value of the select menu to none and than edit the message passing the view again.
Its not recommended to subclass views within a cog. What attributes do you need?
ah alright, i'll move everything about then
Just wondering what cog attributes do you need? Bot?
One message removed from a suspended account.
Send the modal first. Than edit the message with followup.edit()
oh no i need the attributes from the class that inherits Bot
but i separated everything
One message removed from a suspended account.
One message removed from a suspended account.
One message removed from a suspended account.
i have two server (oracle vm) is there any way i can use both to host one bot?
i mean use computational power of both?
This is a support channel for pycord/python related issues. Your question has nothing to do with any of those
okay 👍
try interaction.edit_original_response or interaction.message.edit
one of them should work
Hi, How would i add muliple buttons too a command. Right now my command is:
class Rock(discord.ui.View):
@discord.ui.button(label="Rock!", style=discord.ButtonStyle.primary, emoji="🧱")
async def button_callback(self, button, interaction):
await interaction.response.send_message("You Chose Rock! I choose:")
class Paper(discord.ui.View):
@discord.ui.button(label="Paper!", style=discord.ButtonStyle.primary, emoji="📰")
async def button_callback(self, button, interaction):
await interaction.response.send_message("You Chose Paper! I choose:")
class Scissors(discord.ui.View):
@discord.ui.button(label="Scissors!", style=discord.ButtonStyle.primary, emoji="✂")
async def button_callback(self, button, interaction):
await interaction.response.send_message("You Chose Scissors! I choose:")
@bot.slash_command()
async def button(ctx):
await ctx.send('Rock, Paper, scissors', view=Rock(), view=Paper(), view=Scissors())
When its just the rock alone, It works.
@commands.guild_only()
@bot.slash_command(name='registration', description='Write down command data.',guild_ids=[944934277777326090,769823680695107594])
async def reg(ctx):
cursor.execute(f"SELECT rowid,* FROM counter1 WHERE server_id = {ctx.guild.id}")
item = cursor.fetchmany(16)
db.commit()
for el in item:
nom=el[2]
author= ctx.author
if nom<12:
if ctx.guild.id == 9-0:
guild = bot.get_guild(9-0)
role=guild.get_role(1-0)
await author.add_roles(role,reason=None, atomic=True)
if ctx.guild.id == 7-4:
guild = bot.get_guild(7-4)
role=guild.get_role(7-5)
await author.add_roles(role,reason=None, atomic=True)
cursor.execute(f"UPDATE counter1 SET count= count + 1 WHERE server_id = {ctx.guild.id}")
db.commit()
else:
await ctx.respond("TEST")
ctx.respond and the buttons has the same callback
They cant have the same callback?
What a problem
no
What else would i put for the callback then?
that is basic python?
Im still learning python, right now i dont know much with it but im just trying to make random commands until they work. Now ive decided to attempt it with buttons.
Im trying to learn as i go a lont
along*
Read rule 1 #help-rules
I know.
I try all methods
We will not help if you dont even know the basic´s of Python
Alright.
Any tips to learn though? Youtube has not helped me even a little bit. Ive learned most of my python by just doing it.
can you help?
what is nom?
Mhm, True. Ive done a few small projects like calculators etc, I just like to challenge myself a littlebit lol.
small question: what could cause a repeating task to reset itself mid execution? I have a task set to repeat every 120 seconds, but for some reason it stops executing at a specific line, and start all over again
You already open a tread for that
i know, i meant as in what could be a potential cause, like as of right now, if there's no answer in the thread yet, then probably some pointer would be useful to see where thing went wrong
I explain what I'm trying to do. I need 12 people who first wrote the team to get a role.
Pycord Guide is a complete guide for Pycord. Learn how to create Discord Bots today!
So is it the button_callback i would need to change? Or would it be something in (self, button, interaction)?
I tried all the ways. He constantly doesn’t like it ...
button cannot have the same callback name
Oh ok, So if i do buttonrock_callback etc that would work?
ye
Alr
I still dont really know what nom is
💀 Still saying theres a problem with this line:
await ctx.respond('Rock, Paper, scissors', view=Rock(), view=Paper(), view=Scissors())
@young bone watch here
create a view and add the buttons
Oh, Just 1 view then?
uhhh
that's.. setting 1 thing.. to 3 different thing
I'm trying to get where his logic was at
so nom is a number?
Mmm.. Yes...
But it's didn't WORK 😦
for el in item:
nom=el[2]
what are you trying to do?
you are just reassigning a variable
I have tried all the ways
?tag xy
An XY problem is when you're trying to ask about your attempted solution, rather than your actual problem.
You are trying to solve problem X, using solution Y. Instead of asking for help with X, you ask about Y. This only results in frustration as whoever is trying to help you needs to ask several questions before even beginning to help you with your actual issue, wasting both their own, and your time. Always include as much information as you can about your problem, including attempted solutions. If there are solutions you've ruled out, include them along with an explanation as to why you've ruled them out.
This is the dumbest
see this
what is your goal?
Look. I am making a command for registration. For the first 12 people, a role should be issued. And for the rest, it should be written "You in reserve"...
I tried all the ways, but it does not give me an opportunity.
Every time he writes...
alr
so
what i would do is, set nom to the length of item
because that would represent the number of people in the db
you can do this using len(item)
@proud mason
class TlB(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button( label="Confirm participation",custom_id="button-1",emoji="✅",style=discord.ButtonStyle.success)
async def button_callback(self, button, interaction):
await interaction.response.send_message(f"You confirm participation.",ephemeral = True)
@discord.ui.button( label="Admin button",custom_id="button-2",emoji="🔄",style=discord.ButtonStyle.primary)
async def second_button_callback(self, button, interaction):
await interaction.response.edit_message(view=self)
guild = interaction.guild_id
msg = interaction.message
data1=f"SELECT rowid,* FROM vipteamlist WHERE server_id = {guild}"
cursor.execute(data1)
item2 = cursor.fetchmany(4)
db.commit()
b = ""
i = 0
for el in item2:
i+=1
b += f"**{i}**.__{el[1]}__ | {el[2]} | <@{el[3]}>\n"
data2=f"SELECT rowid,* FROM teamlist WHERE server_id = {guild}"
cursor.execute(data2)
item = cursor.fetchmany(16)
db.commit()
a = ""
f=4
for el in item:
f+=1
if 4<f<17:
a += f"**{f}**. __{el[1]}__ | {el[2]} | <@{el[3]}>\n"
if f>16:
a += f"Reserve🔴**{f}**. __{el[1]}__ | {el[2]} | <@{el[3]}>\n"
embed2 = discord.Embed(title =f":scroll: TEAM LIST :scroll:",description=f"**🕐Time: 21:00 Moscow **\n \n{b}{a}", colour = discord.Colour.embed_background())
embed2.set_footer( text =f'To confirm participation, click on ✅')
await msg.edit(embed=embed2)
How to make it so that only the admin can click the second button?
interaction.user.guild_permissions maybe
but i don't know ?how to use this right
Can teach me pls 🙂
Hey, i think pillow library won't be good with discord.py
so is there any asynchronous library for it
thats right
for some reason, the docs dont mention the return type...
anyways
check if perms.administrator is True
where perms is that above thing
not that i remember. you can always call sync functions using asyncio.to_thread and they wont block the event loop
||there is a low probability that is is as frequently maintained. and a high probability that it just uses asyncio.to_thread. not sure tho||
@discord.ui.button( label="Admin button",custom_id="button-2",emoji="🔄",style=discord.ButtonStyle.primary)
async def second_button_callback(self, button, interaction):
await interaction.response.edit_message(view=self)
if interaction.user.guild_permissions.administrator=True:
guild = interaction.guild_id
msg = ...
await msg.edit(embed=embed2)
else:
await interaction.response.send_message(f"You aren`t admin.",ephemeral = True)
why do you send the whole code again?
.idw
Saying it doesn't work or asking what's wrong with this code is not helpful for yourself or others.
Describe what you expect and/or tried (with your code), and what isn't going right.
Please provide any errors you get for optimal assistance.
Extension 'cogs.NS' raised an error: SyntaxError: cannot assign to attribute here. Maybe you meant '==' instead of '='? (NS.py, line 34)
@proud mason^
which line is that?
you use ==
if interaction.user.guild_permissions.administrator=True:
Maybe you meant '==' instead of '='?
it even says that 😭
this line ^^^
why are you commiting after selecting 😭
aaaaa...
member = discord.utils.get(ctx.guild.roles, name="Member")
catergoryOverwrite = {
guild.default_role: discord.PermissionOverwrite(read_messages=False, view_channel=False),
guild.me: discord.PermissionOverwrite(read_messages=True, view_channel=True),
guild.get_role(member): discord.PermissionOverwrite(read_messages=False, view_channel=False)
}
category = await guild.create_category(name="RECORDS", overwrites=catergoryOverwrite, position=0)
is throwing me an error
Traceback (most recent call last):
File "path\to\project\venv\lib\site-packages\discord\commands\core.py", line 124, in wrapped
ret = await coro(arg)
File "path\to\project\venv\lib\site-packages\discord\commands\core.py", line 978, in _invoke
await self.callback(self.cog, ctx, **kwargs)
File "path\to\project\cogs\test.py", line 43, in setuporder
category = await guild.create_category(name="RECORDS", overwrites=catergoryOverwrite, position=0)
File "path\to\project\venv\lib\site-packages\discord\guild.py", line 1586, in create_category
data = await self._create_channel(
File "path\to\project\venv\lib\site-packages\discord\guild.py", line 1142, in _create_channel
"id": target.id,
AttributeError: 'NoneType' object has no attribute 'id'
create channel works properly but create category causes an error
The role might not be in cache.
hmmm let me try without the permission for the role
yep it worked without it hahaha
thanks
So you will need to check if the role is none than fetch it instead 👍
ohhh thanks
An HTTP exception has occured: 400 HTTPException: Invalid Form Body
In data.components.0.components.0.url: Not a well formed URL.
found the problem, i forgot to get the role id
what i did was passing the role object to the get_role
What is a difference between discord.Bot and discord.Client?
?tag client
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
bridge.Bot # above + bridge commands (application commands and text commands in one)
(each class has all features of the class above it)
size is determined by label
Oh ... 😦
Is there any way to control any Uncaught exception?
I would like to be able to do something before the bot crashes.
depends on where the exceptions are made.
If they are made
in application commands, on_application_command_error
in text-based commands, on_command_error
in events, on_error
in a task, @task_name.error
Ok!
Thank you.
is there an easy a way to make all views persistent?
maybe by using custom_id
Not exactly sure what you mean. Persistent views are just views with no timeout and all items have a custom_id
i mean watching all the views you create and making sure they are all persistent is hard
ex is the ticket bot
each close button ticket needs their own persistence
it doesn't need to have a different persistent id for each button
i mean yeah but the thing i am having a hard time understanding is does custom_id need to be unique for every instance you call the view or can be in the code only?
It depends on what info you would need. I gtg now be back later
well the thing is, sometimes i try to pass some arguments to views so i can reuse the values from one to another causing problems when doing bot.add_view() since they ask for those params unless i make the optional
sure thanks
best idea I got right now is saving the loaction of the view (msg.id) and the data in a SQLite db or any similar db
yeah that's what i think too but i want to know if there's a way to do it without using a database
I think a db is the best way.
But if the arguments you pass to the button are under 100 characters you can have
close_button:10-6-hello
How would i cancel a command after a set of time? Just using this?:
import time
-discord command bla bla bla-
time.sleep(10)
return
```?
youll need to explain more than "cancel a command after a set time"
what does the user need to do for it not to cancel
how does the command work
and no, you dont use the time lib in async enviroments
So i have a rock paper scissors button thing, But it works all the time until bot resets. How would i cancel that time after like 10 seconds?
give it the view a timeout?..
?
if you have buttons, you have a view, if you have a view you can give it a timeout and disable the buttons on timeout
Oh ok.
@bot.slash_command()
async def button(ctx):
await ctx.respond('Rock, Paper, scissors', view=RPS(timeout=10))
So like that then?
try it and see
Nah, didnt work
Ok, i think i got it now. Changed it to the parent class with the timeout=10
Epic. Works 👍
I have a printer function that displays a refreshing 'dashboard' that has quite a few calls to a local db to pull data. Some consequences of this are that when attempting to stop the bot (using keyboard interrupt) it seems to have to wait for the printer function to 'finish' as it takes a good 15-30s to stop the bot.
wondering if I'm doing something wrong or if this is expected using loop tasks
nevermind, had the brilliant idea of turning logging from info to debug, looks like i'm making a lot of suspicious calls somewhere >_>
Why would a button work in one server but not work in another server? Well, more specifically it works but doesn't send the response and rather gets the Unknown Interaction error?
Nvm on that ^ just needed to defer the response while bot queried the google sheet
how is a bot's guild member cache determined (without members intent)? just people who have interacted with the bot? or does the bot get an initial package of 'active' members?
I'm trying to reduce my fetches of members, and opting to use get instead of members intent, but wondering if that's going to cause a lot of misses on cache and confusion on the users when they see "missed cache" heh
Why not just get from the cache and if that returns None, use fetch?
that's pretty true, I was just hoping to pre-fetch I guess, or rather try not to bombard the api with 50 some requests at one time, but even that I could limit in other ways
I get pretty stubborn when I choose a course of action heh but you're right
Well if you have a specific use case you can always just work on caching the members yourself in some way
nah i'm just being lazy and dumb and expecting there to be an api to solve my problem instead of changing a database query to limit the number of returns, I really only need <20 get/fetches but right now my database is returning everying and i'm sorting and querying everything -.-
basically a timekeeping system that refreshes once a minute and shows leaderboard for who's highest
nah private, 1 server, 1 test. I think discord would hire hitmen on me if it was public heh
yeah just turn on members
aight, I'll think about it, just wanted to try out 'best practices' heh
but if it was a >100 server bot, would you suggest not turning it on?
ok thanks heh
ok, kinda hard determining new discord features/systems if the intent of it is to move away from it or not, like application commands, i imagine discord's idea is to transition fully to that in the future, but cant be sure
guess I could read all the blogs
We're glad you asked! As with most things, it is up to the details of the implementation. Rather than list out every possible idea, or have you extrapolate on examples, here are some principles tha...
thanks 🙂
yeah that doc makes sense, it's something (somewhat) in the back of my head and want to do a good job, but this is just a small fun project for me all the same
all the same I got some paths forward, thanks!
Is there a way to make a select menu reselectable? As in, the same values can be inputted if the menu is selected again?
Nvm, that's probably a discord limitation
hi all, I use slash_command load some cogs, but the commands in cogs are not sync to my server, do I need to do something additional? I've restarted discord app.
Which py-cord Version do you use?
py-cord==2.4.0
You can find something at the docs to sync a command
What's the difference between Bot.sync_commands & Bot.register_commands? I'm confused by the document
one of them doesn't exist
The following section outlines the API of Pycord’s prefixed command extension module. Bots: Bot: Attributes activity, allowed_mentions, application_flags, application_id, cached_messages, case_inse...
Is there a way I can get an announcement channel message using the invite link without joining the server by discord api?
Models are classes that are received from Discord and are not meant to be created by the user of the library. Attributes key, url. Methods def is_animated, async read, def replace, async save, def ...
who can help me?
@discord.ui.button( label="Confirm participation",custom_id="button-1",emoji="✅",style=discord.ButtonStyle.success)
async def button_callback(self, button: discord.ui.Button, interaction):
#await interaction.response.send_message(f"You confirm participation.",ephemeral = True)
guild = interaction.guild_id
msg = interaction.message
user = interaction.user
data4=f"SELECT id FROM teamlist WHERE server_id = {guild} AND id={user.id}"
cursor.execute(data4)
item3 = cursor.fetchone()
db.commit()
if user.id == item3:
cursor.execute(f"UPDATE teamlist SET status = '✅' WHERE server_id = {guild} AND id={user.id}")
db.commit()
cursor.execute(f"SELECT rowid,* FROM vipteamlist WHERE server_id = {guild}")
item2 = cursor.fetchmany(4)
db.commit()
b = ""
....
this code didn't work
but didn't have error
@proud mason
Use a debugger. Or add lots of print statements to see till where the code is being executed
is there a api for bot to get the guilds with a member together?
Models are classes that are received from Discord and are not meant to be created by the user of the library. Attributes key, url. Methods def is_animated, async read, def replace, async save, def ...
quick question, how do i embed a video (mainly youtube video) into a embed?
do i just add_image() it on?
yes
is it an image/gif?
No, it's a youtube video
that will not work
Then.. why did you answer yes?
and well, how can i do that?
Or is it just not possible yet
url=imageurl
Some classes are just there to be data containers, this lists them. Unlike models you are allowed to create most of these yourself, even if they can also be used to hold attributes. Nearly all clas...
Can't. Discord only allows you to embed images
You could send a video link in the msg content part of the message
And discord will embed it in a standard way for you
got it then..
how can i send a paginator using select menu?
the same like a message or button message?
paginator.send need message invocation context
Question: what's the biggest file size a bot can send?
8MB like normal user or a higher limit?
i dont have that (have only interaction)
paginator.respond
👍
also, extending on the questino. what about when the server is boosted? Do bots get the extra benefit like increased upload size?
no
they have the limits like a normal user
but when the server is boosted, when users get the higher upload limit (50MB/100MB), do bots in the same server get the same benefit too?
when they send message in the server, of course
yes i believe
I feel like there's a way to pop a modal based on a dropdown selection, but didn't see any examples anywhere. Am I correct that this is possible?
Pop a modal?? 💀
What does that even mean
If you mean send a modal, then yes you can
You can do it just like you would do with a button
...? Display the text input modal when selecting a particular value from a dropdown, similar to "popping one" from a button press
Cool. Would I have to evaluate the Option value in the Dropdown callback?

Okay, use case for clarity:
Five options in the dropdown; four presets and a fifth one that when you select it, displays a modal for custom input
So would the fifth one just need some value that is used in the callback to then display the Modal?
Cool, thanks. That helps me select a rabbit hole to go down.

I have a webserver listening for requests and I want to somehow couple it with a discord bot. Is there a way to invoke a method declared in a cog just by passing around the bot instance to the webserver? (similar to ctx.invoke but starting from a "higher level"). I know this is a weird question but bear with me.
Look into IPC
There is a library called better-ipc on GitHub
It works with pycord the last time i checked
Thanks! I'll do that.
@proud mason to the SelectMenu module can be changed presistent for permanent functioning as in buttons?
What's wrong in this? It's telling that the "option" keyword is not valid
@bot.command()
async def select_menu(interaction):
the_options = [
discord.SelectOption(label="Option 1", value="1"),
discord.SelectOption(label="Option 2", value="2"),
discord.SelectOption(label="Option 3", value="3")
]
await interaction.response.send_message(
"Please select an option:",
components=[
discord.SelectMenu(options=the_options, placeholder="Select an option", max_values=1, min_values=1, id="my_select_menu")
]
)```
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: SelectMenu.init() got an unexpected keyword argument 'options'
i made an discord bot, in python, but whats the code for making channels, ive tried many things but mb you guys now something? you can dm me
Yes select menu can be persistent
And see #help-rules
Dont ping for help...
.rtfm create_text_channel
Create object of discord.ui.Select and not discord.SelectMenu
discord.SelectMenu is a library internal thing for select menus. Don't use that
Thanks
bruh who pinged
Is there any alternative to cog_load? This is what I'm trying to achieve (this is discordpy code and I want to find a pycord equivalent)
Would on_ready achieve the same result?
try asyncio.create_task in there
almost. except ready can fire multiple times. you would need to store if ready was fired before on a cog object attribute
Ok that's not too bad, thanks
Hey guys!
How can i get the reaction user (like i did in this example, but it doesn't work)
for reaction in msg.reactions:
if reaction.user == self.bot:
if reaction.emoji == "✅":
last_counting_msg = msg
break```
.rtfm Message.reactions
discord.Reaction
discord.Reaction.clear
discord.Reaction.count
discord.Reaction.emoji
discord.Reaction.is_custom_emoji
discord.Reaction.me
discord.Reaction.message
discord.Reaction.remove
discord.Reaction.users
discord.on_reaction_add
discord.on_reaction_clear
discord.on_reaction_remove
discord.InteractionMessage.add_reaction
discord.InteractionMessage.clear_reaction
discord.InteractionMessage.clear_reactions
discord.InteractionMessage.reactions
discord.InteractionMessage.remove_reaction
discord.on_raw_reaction_add
discord.on_raw_reaction_clear
discord.RawReactionClearEvent
Read the docs.
I literally provided you the doc links?..
if self.bot in reaction.users?
Bro
Read the docs
A discord.Reaction object doesn't have a users attribute
It has a method
*async iterator to be precise
*use async for to read it
I told you last time itself to not ping for help
That is called autocomplete
Here's the slash autocomplete example.
Ok thanks
is anyone able to tell me why this
async def con_nodes(self):
with open("lavalinks.json", "r") as f:
data: dict = json.load(f)
rand_idents = statics.random_node_idents()
print(rand_idents) # <---- the list is actually here
await self.wait_until_ready()
for node, values in data.items():
identifier: str = random.choice(rand_idents)
rand_idents = rand_idents.remove(identifier)
identifier = f"'{identifier.upper()}'"
code gives me this
Ignoring exception in on_ready
Traceback (most recent call last):
File "E:\DragonBot\venv\Lib\site-packages\discord\client.py", line 378, in _run_event
await coro(*args, **kwargs)
File "E:\DragonBot\DragonBot.py", line 100, in on_ready
await self.con_nodes()
File "E:\DragonBot\DragonBot.py", line 49, in con_nodes
identifier: str = random.choice(rand_idents)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\pauln\AppData\Local\Programs\Python\Python311\Lib\random.py", line 370, in choice
raise IndexError('Cannot choose from an empty sequence')
IndexError: Cannot choose from an empty sequence
error?
I expect it to choose me a random name from this rand_idents = statics.random_node_idents() function which returns a list of str
Does the print statement show that list?
yea it does
that is what confuses me too
ohh and btw it already chooses one name [ WARNING ] [14-03-23 21:44:23] [DragonLog] [DragonBot:75] : Node didn't respond: Lavalink 'ONION' didn't connect on http://127.0.0.1:2333
but after that it throws this error
even if I replace the function directly with the list it throws this error
btw I'm using python 3.11.1
I guess I found a workaround it's not nice, but it works i guess
async def con_nodes(self):
with open("lavalinks.json", "r") as f:
data: dict = json.load(f)
rand_idents = ['apple', ...]
await self.wait_until_ready()
for node, values in data.items():
rand_num = random.randint(0, len(rand_idents))
identifier = rand_idents[rand_num]
rand_idents.pop(rand_num)
identifier = identifier.upper()
If anyone knows offhand - when choosing to delete messages with a ban action, is bulk_message_delete called, or just message_delete for each?
(Answer: message_delete. However, my plan was to show the message that got someone banned, and there's no real way to correlate. Could prob report the last message, though)
I'd say it's an internal function from discord https://discord.com/developers/docs/resources/guild#create-guild-ban
nothing that the libary does for you except passing your value to the api
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
Perhaps I'm missing something, but I gave details to a slash command where there is only one option that should be set 'required'. I gave the option the required=True property, but it displays as a "optional".
Code?
It works fine, I only need the option to be displayed as a required option
I'm guessing I'm missing something
You don't provide a default value if the value is required
That makes it automatically non required
How would I go about creating a slash command group within a cog?
I use the slash_command decorator and I'm assuming I need to call bot.create_group(), but I'm not sure how to call bot correctly within the cog.
you can use discord.SlashCommandGroup
Here's the slash cog groups example.
Tyvm. I see add_application_command(groupVar) is not called in the example, but I thought it had to be when using SlashCommandGroup?
Not in cogs.
Oh... Interesting. Is there documentation for this?
Side question: If I wanted to set default_permissions, would I do that with the groupVar decorator or the discord decorator?
I don't understand your question. The @discord.slash_command decorator is for each individual command, not groups.
Mind if I post a code snippet to give context, or should I open a thread?
Trying to do something like this (will move to thread if requested):
# Within Cog class
# <__init__ code here>
praise = discord.SlashCommandGroup("praise", "Praise people")
@praise.command(name = "set", description="Set number of praises for user")
@discord.default_permissions(
administrator=True,
) # Only members with admin can use this command.
async def set(self, ctx, member: discord.Option(Member), praises: discord.Option(int)):
# does stuff```
I think @discord.default_permissions is correct, but I'm not sure...
I'm now getting NameError: name 'Member' is not defined, but I thought Member was a valid option for discord.Option?
should be discord.Member
Just figured that out 😅 Thanks ❤️
If it applies to the whole group, then use it in the SlashCommandGroup, otherwise, apply it to each command that requires it.
Uhh... Not sure yet if it will apply to the whole group, but that is great to have in mind 🙂
However, I noticed guild_ids can be defined in SlashCommandGroup, but I instead have it defined in the cog class. Is that okay? Should I move it down to SlashCommandGroup?
As long as it applies to the whole cog, it is fine
If I wanted the permissions to apply to the whole cog, is there a permissions kwarg for the cog class?
afaik no
Ahh, because permissions are a decorator, and the command attributes of the class get directly passed to the kwargs of the command (which guild_id is one of the many).
This has been a journey to learn 😅 Appreciate your help. I'm used to Java and this is wildly different...
I don't think the Java Discord API even has cogs
Cogs just seem like helpful code organization by splitting up code into external classes, so I thought it would be a good investment to learn early. It's more so decorators and kwargs that are throwing me for a loop... Like, the documentation states to just pass whatever kwargs you want to the function, but never states what kwargs are supported by each function.
I'm pretty sure you can make a https://docs.pycord.dev/en/stable/api/cogs.html#discord.Cog.cog_check and write your own permission check, if you want a cog-wide permission check.
Sadly that doesn't support the default_permissions factor.
Right
Is there a way to run a function before all commands in a Cog (like a before_command() or something like that)
Attributes description, qualified_name. Methods cls Cog.listener, def bot_check, def bot_check_once, async cog_after_invoke, async cog_before_invoke, def cog_check, async cog_command_error, def cog...
I want to code slash command and normal command separately using pycord I don't want to use bridge any other alternative ways?
Can you cancel calling the command if you to verification in cog_before_invoke
no. You would be looking for https://docs.pycord.dev/en/master/api/cogs.html#discord.Cog.cog_check
Attributes description, qualified_name. Methods cls Cog.listener, def bot_check, def bot_check_once, async cog_after_invoke, async cog_before_invoke, def cog_check, async cog_command_error, def cog...
commands.Bot handles that for you
I see and can you call the before function with custom arguments? For exemple I know all the commands in my cog take a role as parameter

Yess but sometimes their is workaround to do it, or the doc is just outdated
So we never know
If the docs say that a method takes one parameter, there is never a workaround to magically add another parameter.
Command Permission Decorators: Commands: Shortcut Decorators: Objects: Attributes full_parent_name, qualified_id, qualified_name. Methods@ after_invoke,@ before_invoke,@ error, def get_cooldown_ret...
See would never have found if I did not ask
That's not a "workaround", that's literally in the docs
which you would have found if you read them
you both should just chillax
huh?
Is it possible to have a default command for a SlashCommandGroup? What would that look like?
It is not, Discord removed that feature
aww sadge
Follow up: If I define a slash command with the same name as a group, I'm assuming it will get mad?
Yeah, I think so
Welp, I tried, lol 
yes
tyvm
I'm assuming it would look like this?
# Cog file
from discord.ext import commands
@commands.Cog.listener()
async def on_message(self, message):
# Do stuff...```
assuming it will be indented properly, you are missing the self parameter
Good now?
.tag tias
I was wondering how to make an on_message event where the bot detects embeds it has sent itself and only change the color of the embed leaving the content the same?
Why would you change the color of the embed using an on_message event instead of just setting it when you send it?
It’s for mee6; I have a custom bot and istg I hate their branding on my bot /nay
.rtfm message.embeds
.rtfm message.edit
Ahh thanks a lot!!
not sure if this is a good channel to ask this, but I don't know that much javascript so what does this do? or what is it for? (docs/_static/js/custom.js)
This is a Python Discord API Wrapper Support Server.
well yeah, but it's in the library, maybe not like the actual library but it's in the github repo, where else am I supposed to ask this? I thought it might be specific to this use case since google didn't provide any help
probably some formatting/UX thing
Why not ask in a server that actually helps with JavaScript? You couldn't be further from the right place to ask
did you even read my reply to the first person that said that
why are you guys so aggressive
this is why people are afraid to ask questions
If that's "aggressive" then you're in for a treat by being on the internet
well imo a better way a helper in a programming discord server's help channel could have said that would be smth like "I'm not sure what this does but this isn't a good place to ask, you could try asking in a javascript discord server, they might be able to help you better"
but that's just a suggestion
sorry if I offended anyone
Well sometimes you assume that people read #how-to-get-help and #help-rules before asking a question. And by reading those it should be pretty obvious that this is not the right place to ask a JavaScript question.
But I'm sorry if that was too aggressive
I'll admit I didn't read those before posting, I don't see anywhere where it says it should be python only, but I guess that should just be inferred, and this is a help channel for the pycord api, not help for understanding internal code
Where did you even find that code anyways?
here
I noticed it was something added after forking and the commit comment was "improve toctrees" but removing it didn't seem to change anything
but it doesn't really matter I was just curious
ah looks like it's part of a scrollspy script library in js, weird that it didn't come up on google, I need to get better at searching for things
Well that's part of docs
I know
I hope you meant it didn't change docs. Because that won't change the library 💀
Ah my bad lol
no worries
Would be a cool idea to ask what it does to the person who committed it
Because most helpers here don't deal with docs
gets mad at friendly person for asking a question related to the package in the server that maintains the package
I don't think they recognized it was a part of the package at first which is understandable
I like your definition of "mad" 
yeah true, I figured it out tho pretty sure so it's ok
i like your way of cherrypicking a word and refusing to address the main point brought up in my message
anyway whatever who cares you're hte helpers anyway
That's right, I am an all-knowing god and I rule this world

fr
What do you want me to address then, sir? I promise I won't be mad at you
@coral charm @limber urchin could you maybe take this to DMs?
eh i just wanted to point out that like 2 different helpers saw javascript and instantly told them to screw of before even attempting to figure out where the code came from and if it was relavent
i'm done here i dont really care about pycord i dont wnat to continue this conversation anyway
👋
I don't like DMs tbh
This is a channel to get help on how to use the library, not how the library was made
is it possible to edit a message and send paginator?
I used the example for the on_message_edit() event in the pycord git and the before.content and after.contect show as an empty string for some reason.
I tried to send the message with the tables themselves and it showed correctly with the message, channel and author info
?tag intents
https://docs.pycord.dev/en/master/intents.html
https://discord.com/developers/docs/topics/gateway#gateway-intents
import discord
from discord.ext import commands
# Get specific intents for fine control
intents = discord.Intents()
intents.emojis = True
intents.guilds = True
intents.messages = True # Required for prefix commands!
...
# Get all non-priveliged intents; this excludes presences, members and message_content
intents = discord.Intents.default()
# Set priveliged intents: these must be enabled on dev portal
intents.members = True
intents.presences = True
intents.message_content = True # Required for prefix commands >= 2.0.0b5
# Get all intents; all intents must be enabled on dev portal.
intents = discord.Intents.all()
# Apply intents when creating your bot
bot = commands.bot(prefix="?", intents=intents)
In version 1.5 comes the introduction of Intents. This is a radical change in how bots are written. An intent basically allows a bot to subscribe to specific buckets of events. The events that corr...
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
1st one
I do have message content intents enabled
You need to enable it on the bot too
^
Now I am writing a bot and I would like to clarify ... If I make 3 buttons in this code, then by clicking on the second one, the first two should turn off and the third one will turn on. Is this possible?
Just check if child.label = third button label. Than dont disable it.
Ок thanks
so I got a small problem with a raspberry pi cronjob and I am sure someone here knows what I have to change to fix it.
I got these three lines for cronjobs
00 04 * * * sudo shutdown -r now
@reboot sleep 30; cd "/home/pi/Desktop/Bot V4.0" ; python3 main.py &
@reboot sleep 60; cd "/home/pi/Desktop/MusicDragon"; source venv/bin/activate ; python3 DragonBot.py &
so this night the first bot started but the second didn't start, I'd like to start both, how is this possible?
btw its the sudo crontab
||or use enumerate and check the index||
No crossposting
so applications commands such as slash commands, cant use it own error handler per command? it needs a global? ```py
@CLIENT.event
async def on_application_command_error(ctx, error):```
what?
like for example, trying to send an error message stating a user is on cooldown, doesn't work if is like commandname.error
but on ly for on_application_command_error
One of the most appealing aspects of the command extension is how easy it is to define commands and how you can arbitrarily nest groups and commands to have a rich sub-command system. Commands are ...
async def button_callback(interaction:discord.Interaction):
ticket_category = discord.utils.get(interaction.guild.categories, name='Tickets')
channel = await ctx.guild.create_text_channel(f"ticket-{format(ticketNum, '04d')}", category=ticket_category)
await channel.set_permissions(interaction.user, overwrite=overwrite)
await interaction.response.send_message(f"Created Ticket at {channel.mention}", ephemeral=True)
embed = discord.Embed(title="Support Ticket Opened!", description="Thank you for contacting support.\nPlease describe your intent for the ticket and wait for a response.", color=BLUE_COLOR)
embed.set_footer(icon_url=interaction.guild.icon, text="Powered by dragsim.org")
await channel.send(embed=embed)
button.callback = button_callback
Error:
In embeds.0.footer.icon_url: Scheme "none" is not supported. Scheme must be one of ('http', 'https').```
on the await channel.send()
Squid can You help me?
You can try just adding .url after icon
Is it possible to initially make the button unavailable.
I'm using using the @Option, the problem is that my idea is to make it so that if you select the discord.Member you can't choose the discord.TextChannel. I don't know if I've made myself clear.
how can you convert a channel variable to the same as ctx.channel which has the (property) instead of (variable)?
Yes. Just set the button to disabled before sending.
You have to do this manually. Or use auto complete but I think it is easier to just send a message when they are both selected.
A property is just a variable inside a class (or function?)
Why does it matter?
Accessing it should work the same
made a transcript module but when i originally made it it just sent the file to the channel the transcript command was sent to, but i want staff to be able to grab a seperate channels by id and send it to them,
the only different i could figure out was if ctx.channel and Channelt = bot.get_channle(id) are not exactly equal
am i missing something? this is being done inside a cog if it matters
Mt guess is you are using the wrong id for getting the channel.
What is wrong?
?tag idw
Saying it doesn't work or asking what's wrong with this code? is not helpful for yourself or others.
Describe what you expect and/or tried (with your code), and what isn't going right.
Please provide any errors you get for optimal assistance.
i want the option to be required and it is not dispite required being True
i have waited for 20 minutes for it to update
I don’t see anyone pinging you. No messages where deleted in the last hours
Ghost ping?
discord.Option
(O capital)
Wow. That happened for the 2nd time today. Maybe reply with ping and deleted?
Nothing was deleted here. That’s the thing
Imma add a ping logger when I’m home
Does someone know how i use slash commands in an cog? Is it just @commands.slash_command or something different because the command isn’t showing up for me
Read the docs
I think its because of me but i don’t find it there
We have various examples and guides
Cool
Hey guys quick question:
I'm using git to keep track of all my development, and I'll soon launch my bot on a public server (it'll be a server specific bot, so only used on this one (and my test server))
So I'm making a development branch (which will be used to try my future features etc. so obviously it'll have a different token)
I have a bash script to launch my bot:
start.sh
#! /usr/bin/bash
day=$(date +"%F")
timestamp=$(date +"%H_%M_%S")
# Creating a day log folder if not already created
mkdir -p logs/$day
# To keep track of the current branch
current_branch=$(git branch --show-current)
# To launch from the stable version of the bot
git checkout master
nohup python3 -u NameOfBot/main.py &> "logs/$day/nohup_$timestamp.out" &
echo $! > pid # Used in stop.sh to kill the process
echo Starting bot...
# Coming back on our working branch after launching the bot
git checkout $current_branch
My question is: When doing this (i.e switching branch to launch the bot then coming back to the working branch once the bot is launched), will the writes / read to the database be on the good version of the database ? My database is in the git directory but is ignored (in .gitignore)
Or should I put it elsewhere to be sure ? Same question as I have logs and resources folder (both untracked as well)
Thanks if someone can help 😄
since your db is ignored, git will ignore it. meaning the file will remain the same across branches
you could have the db files in a folder, and the file name could be the current branch name. then set the current branch in an env var in your bash. use this var to connect to your db
Yes I was thinking to do this, having a env variable with the current branch and using the variable to determine which database to use, I juste wasn’t sure it would properly ignore it, but now I am ^^
Thanks a lot for your answer 😃
np 
how do you dynamically set whitelisted guilds for slash command group's guild_ids using data from database?
mmm like is there a question about doing anything specific? it seems pretty cut and dry:
-have whitelisted guilds in the db
-when using a slashcommand:
--grab whitelisted guilds from db
--check ctx.guild.id is in the whitelist
i tried using beanie and it throws me a collection not initialized
i fetched the data from the database using async client and asyncio.run and throws me that error
seems like a beanie issue, something that i've never used /shrug
my init database is in on_connect event of the main
hmmm then i'll try using sync approach for fetching the guild ids
mmm maybe didnt await somewhere? dunno would need a bit of debugging
now my problem is the commands are still showing on both servers 🤣
is there a way to check rate limits on a interaction call? trying to determine how often i can safely update channel names, apparently that's pretty restricted
channel names are twice per 10 minutes
okey, was a weird request from a 'client' but at least i got something to tell them heh
generally you can only get the ratelimit from discord if you make the request directly to get the headers, don't think the library stores them elsewhere
is there any reference for rate limits? or you just kinda know that
yeah that's fine just need helpful people like y'all to answer that heh
some people just found out through testing, discord doesn't have a list of ratelimits because most are dynamic and per-route
yeah i respect that kinda security by obscurity
hey my commands aren't registering any help?
import discord
from discord.ext import commands, bridge
class Verify(commands.cog):
def __init__(self, bot):
self.bot = bot
@bridge.bridge_command()
async def verify(self, ctx, msgid:int):
await ctx.fetch_message(msgid)
embed = discord.Embed(title = f"sent verification to {msgid}")
embed.add_field(f"[messagelink]({msgid.jump_url})")
msgid.add_reaction("✅")
await ctx.respond(embed = embed)
def setup(bot):
bot.add_cog(Verify(bot))```
discord.ext.commands.errors.CommandNotFound: Command "verify" is not found```
havent used bridge commands but maybe try
@bridge.bridge_command(name="verify")
?
they dont take names as parameters
not a purple name though, so I could be stupid
did the error come from using it as slash command or custom prefix command?
i checked the docs and i cant find anything that suggest name as a parameter infact the guide makes it seems like the opposite
also slash commands dont show
and prefix commands show the error seen above
im following this btw https://guide.pycord.dev/extensions/bridge
Concept
hmph, yeah looking at that and looks like everything should be fine
oh uh is class Verify(commands.cog): supposed to be capital Cog?
yes
OH
discord.ext.commands.Cog
discord.ext.commands.Cog.bot_check
discord.ext.commands.Cog.bot_check_once
discord.ext.commands.Cog.cog_after_invoke
discord.ext.commands.Cog.cog_before_invoke
discord.ext.commands.Cog.cog_check
discord.ext.commands.Cog.cog_command_error
discord.ext.commands.Cog.cog_unload
discord.ext.commands.Cog.description
discord.ext.commands.Cog.get_commands
discord.ext.commands.Cog.get_listeners
discord.ext.commands.Cog.has_error_handler
discord.ext.commands.Cog.listener
discord.ext.commands.Cog.qualified_name
discord.ext.commands.Cog.walk_commands
one would think that would throw an error heh, maybe lower case is a base class?
no
its the commands.cog
cant help it
nah thats def the error thank you
nope
not the issue
even with py commands.Cog i still get the error
might take a few seconds to register the update?
I like to put a description on commands like '1' or '2' to see if the client hasnt updated the cache of commands, works for slash commands
yea, i think it should show as a slash command if everything is right though
can try and do ctrl-R to see if refreshing discord client helps
that didnt work
hmm :T
this is annoyig
and you saved the doc and restarted the bot script and everything?
multiple times
yea that's frustrating
it loads the files so i know its not the command handler
oh well, i see another bug
import discord
from discord.ext import commands, bridge
class Verify(commands.Cog):
def __init__(self, bot):
self.bot = bot
@bridge.bridge_command()
async def verify(self, ctx, msgid:int):
await ctx.fetch_message(msgid) # <- this doesnt get stored as a result
embed = discord.Embed(title = f"sent verification to {msgid}")
embed.add_field(f"[messagelink]({msgid.jump_url})") #<- this is still an int, and doesnt have a jump_url property
msgid.add_reaction("✅")
await ctx.respond(embed = embed)
def setup(bot):
bot.add_cog(Verify(bot))
it doesnt solve not being able to do the command tho :T
yeah i noticed the jump url thing
can try pasting what you got now i guess
can you try not having the msgid parameter? it might need to be a discord.Option
maybe it's just not finding it because it expects self.verify(ctx)
this is what I mean
async def verify(self, ctx, msgid: discord.Option(int, name="msgid", required=True)):
it likely wont 'work' because id's are too big to pass to the javascript client
i've always had to take id's as strings then parse them into ints
i dont think a parameter would keep a whole command from registering tho
yeah not 100% sure about the internals but it's worth a shot
unless you get a purple name or that staff guy back here
.slashnoshow
Checklist for Application Commands Not Showing Up:
• Does your bot have the application.commands scope?
• Are you loading cogs before on_ready and on_connect?
• Is on_connect not overridden?
• Did you update to the newest version of py-cord (tag: install)?
• Is User Settings > Accessibility > Chat Input > Use legacy chat input turned off?
• Did you share your code and errors?
• Do you still have libraries that conflict with the discord namespace (e.g. discord.py)?
So I have a command that looks up emojis via some API. It takes the name as the input. I'm defining an autocomplete method that does the API call and the filtering to return similar emotes. The API is returning a complex object and I eventually also want to get the emote URL from it. Is there a way to pass more data to the caller (command method) without breaking the autocomplete (since it probably wants a list of strings to be returned)?
@void abyss could we move this to a thread?
sure
Right now I'm caching the response and redoing it in the caller but it isn't efficient.
Code looks something like this
async def trending_autocomplete(self, ctx: discord.commands.AutocompleteContext):
# API call
emotes = await self.get_trending_emotes(ctx.options["category"])
return [emote['name'] for emote in emotes if emote['name'].lower().startswith(ctx.value.lower())]
@emote.command()
@option("category", description="What's the emote category?", autocomplete=category_autocomplete)
@option("name", description="What's the emote name?", autocomplete=trending_autocomplete)
async def find(self, ctx: discord.ApplicationContext, category: str, name: str):
# Returns cached response
emotes = await self.get_trending_emotes(category)
# This is the emote object, not just the name
selected_emote = [emote for emote in emotes if emote['name'].lower() == name.lower()]
# Get the url
...
The autocomplete handler for the option. Accepts an iterable of
str, a callable (sync or async) that takes a single argument ofAutocompleteContext, or a coroutine. Must resolve to an iterable ofstr.
iirc, a dictionary withstras keys is an iterable ofstr
Oh, so I just have to put the keys as the name and the rest of the emoji object as the value
I'll try that, thanks!
It could also look like this if you want more than just the url:
{
"sad_face_emoji_name": {
"url": "https://",
"foo": "bar",
"spam": "eggs"
},
"second emoji idk": {
...
}
}
Yea, that would be perfect
async def search_options(options: List, ctx: discord.AutocompleteContext):
return options
@bot.slash_command()
async def choose_food(
ctx,
food_type: discord.Option(str, "select your desired delacasy", autocomplete=search_options(["apple", "banana"]))
):
await ctx.respond(food_type)
how would i go about including an additional parameter in the autocomplete function?
sry i dont entirely get function annotations
do you intend to have static choices?
Autocomplete should only be used for dynamic choices that update during runtime or more than 25 choices.
is there a limit on how many commands a bot can have
can you remove the buttons on a pagegroup used In a paginator If It only has one embed? nevermind I got It 
the choices are intended to be immutable
what would be better optimized for static choices
You can set the choices kwarg to a list of strings/OptionChoices as well, as long as it's fewer than 25
.rtfm discord.Option.choices
Target not found, try again and make sure to check your spelling.
tysm <3
Well that was a good idea in theory, in practice it seems that the autocomplete takes the dictionary and only returns back the key back to find as an the name option/input.
so so sry but what is the difference between the OptionChoice object and a raw string?
Well, an OptionChoice lets you set a name, value and a localization. A raw string will just use the name as the value as well.
Can you print the traceback of a ApplicationCommandInvokeError ? When I try to do it it does:
Ignoring exception in on_application_command_error
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\rapha\AppData\Local\Programs\Python\Python311\Lib\traceback.py", line 187, in format_exc
return "".join(format_exception(*sys.exc_info(), limit=limit, chain=chain))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\rapha\AppData\Local\Programs\Python\Python311\Lib\traceback.py", line 139, in format_exception
te = TracebackException(type(value), value, tb, limit=limit, compact=True)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\rapha\AppData\Local\Programs\Python\Python311\Lib\traceback.py", line 690, in __init__
self.stack = StackSummary._extract_from_extended_frame_gen(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\rapha\AppData\Local\Programs\Python\Python311\Lib\traceback.py", line 409, in _extract_from_extended_frame_gen
if limit >= 0:
^^^^^^^^^^
TypeError: '>=' not supported between instances of 'ApplicationCommandInvokeError' and 'int'
when running: traceback.format_exc(self.discord_exception)
I solved it by doing : ```python
"".join(traceback.format_tb(self.discord_exception.traceback))
Does anyone know how to properly process discord.User.public_flags
You get a discord.User object and access its attribute.
.rtfm userflags
discord.UserFlags
discord.UserFlags.staff
discord.UserFlags.partner
discord.UserFlags.hypesquad
discord.UserFlags.bug_hunter
discord.UserFlags.mfa_sms
discord.UserFlags.premium_promo_dismissed
discord.UserFlags.hypesquad_bravery
discord.UserFlags.hypesquad_brilliance
discord.UserFlags.hypesquad_balance
discord.UserFlags.early_supporter
discord.UserFlags.team_user
discord.UserFlags.partner_or_verification_application
discord.UserFlags.system
discord.UserFlags.has_unread_urgent_messages
discord.UserFlags.bug_hunter_level_2
discord.UserFlags.underage_deleted
discord.UserFlags.verified_bot
discord.UserFlags.verified_bot_developer
discord.UserFlags.discord_certified_moderator
oh
Thanks Squid :D
yes but how do I know if a user has a certain tag the value returned is additive of all the tags
for example, in my case, I have the active developer badge and the hype squad balence
so 4194304 + 256 = 4194560
it isn't the addition, it is the bitshift. You would just have to check for every one
ok thanks
does Command Groups work with Slash Commands?
.tias
I am more curious about how you'd implement it though.
Here's the slash groups example.
Ah okay ty.
Actually I am confused about how decorators work
o wait no i think i get it.
It's a good idea to understand what a decorator is before making a bot with pycord
I mainly write C so Decorators are not sometihng I am familiar wit
is there anyway to simplify this by returning the name of the variable or option?
yeah but I dont tihnk it would save space.
That's the most basic way you can do it, doing it in any other way would just overcomplicate things
You're just changing the name and value in each of them, you could probably add each field to a list like ['rank', 'gamemode', 'time', 'players'] and then iterate over it and add_field for i I guess.
But yeah that's basic without overcomplicating.
is there any way to return the name of a variable that's referenced in a for loop?
for f in [rank, gamemode, time, players]:
embed.add_field(name=return_name_of_orignal_var(f), value=f, inline=True)
without using f"{a=}".split("=")[0]
oh dam'
does name apply to basic types as well
In theory you could do something like:
fields = [rank, gamemode, time, players]
for i in fields:
embed.add_field(name=i.__name__.capitalize(), value=i, inline=True)
Not sure I get what you mean
is name a valid method for strings as well
yeah it returns the name of a varialbe I think
it works for functions and methods tho
so
theoretically
def a():
return "a but the letter"
print(a())
print(a.__name__)
:)
also what does this erorr entail? 'dict' object has no attribute 'cog'
should i make some sort of cache for gettings prefix from mongodb?
reading data directly from mongo would consume alot
if you're going to cache it would it just be JSON? if so why not just have it all in a local json...
I have this, but it will only print to console if the bot is mentioned. What stupid little thing am I missing? 😅
@commands.Cog.listener()
async def on_message(self, message):
print(message.content)```
Oh, does it need Message Content Intent?
im dumb...
Yes
@torpid wraith you should add both message intents
Is it possible to make the discord bot leave the link to the message written earlier.
I need the bot to insert a link into the gray button to the previous message where the green and red buttons are
yes
How...🤔 Some specific system? Or an event?
When sending the green/red button save the message ID (you might need channel id to depending on if you can get that later.) Than reconstruct the link. In a link the IDs go guild/Channel/message.
It should be not that hard if you know python ;3
@strong crypt
This the pycord the help server for making discord bots.
I suggest you join the python help server instead for general python questions the server at the bottom of the next message.
its is very difficult to help you if you don't understand python first.
As it stands, you do not or cannot show that you understand the basic fundamentals of Python. Please continue to learn Python first, as pycord is a Python framework and as such requires that you have a confident grasp on these fundamentals . For now, pause your current project and when you have learned enough Python you can then pick it back up and continue where you left off (if at all possible).** You cannot drive a truck if you do not know how to drive at all.**
cool free resources are
w3school
freecodecamp.org
there are also a lot of python programming tutorials out there a youtube search will give a lot awesome content. If you need help with python there is a python server for that where they will be more that happy to help you with these thing, you can also ask for python help in #881309540639997952.
python server: https://discord.gg/python
is there any method to create an invite in a particular channel given its id
mega small brain question but i cant seem to find it in the documentation
await channel.create_invite()
Is it possible to write a button so that when the administrator clicks on it,then the author of the command is given a certain role.
having some issues integrate the invite into the embed
details = {
"Rank":rank,
"Gamemode":gamemode,
"Time":time,
"Players":players,
}
if voice_channel:
details["Voice Channel"] = str(voice_channel.create_invite())
embed = discord.Embed(
title="The Finals - NA LFG",
description=f"{ctx.author.name} is looking for a group!",
color=discord.Color.from_rgb(210, 31, 60)
)
embed.set_thumbnail(url=str(ctx.author.display_avatar.url))
for k, v in details.items():
embed.add_field(name=k, value=v, inline=True)
await ctx.respond(embed=embed)
do i have to specify await in this instance where im creating an invite?
it's a coroutine object, so you probably have to use await
Is it possible to write a button so that when the administrator clicks on it,then the author of the command is given a certain role.
Yes
And then how do I get the sender's ID in the button.
Store it on the button or view when creating the view
Can You write example?

Sorry im bigginet
#help-rules
@young bone I already have code
Just pass the value to the view's init
class StartRegistrationButton(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button( label="Start registration",custom_id="button-13",emoji="▶",style=discord.ButtonStyle.primary,row=3)
async def startreg_button_callback(self, button: discord.ui.Button, interaction):
await interaction.response.edit_message(view=self)
if interaction.user.guild_permissions.administrator==True:
if ctx.guild.id == 944934277777326090:
guild = bot.get_guild(944934277777326090)
role=guild.get_role(1064856142259425350)
await author.add_roles(role,reason=None, atomic=True)
if ctx.guild.id == 769823680695107594:
guild = bot.get_guild(769823680695107594)
role=guild.get_role(776528911269363775)
await author.add_roles(role,reason=None, atomic=True)
else:
pass
@commands.guild_only()
@bot.slash_command(name='registration', description='Write down command data.',guild_ids=[944934277777326090,769823680695107594])
async def reg(ctx):
await ctx.send("Smth",view=StartRegistrationButton())
Thats a modal, not a button?
I know!!!
I thought to put the class in the command
No
ctx.send_modal?
You asked how to do it in a button. Not in a modal
also that ^
And literally
if ctx.guild.id == idhere:
bot.get_guild(the same id)```
Is just useless
Ohh no...
chek
All I need is some way to save ID author outside command.
So that later if the admin clicks on this button, the author will be given a role.
code here
Store it as an object attribute
self.auth_id = ...
Accept a parameter for the id in the view init
And set this there
While creating the view object in the command, pass the author id to it
interaction.client is this not the right way?
What?
what wrong i do
class RoleButton(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button( label="Registration ended or suspended",custom_id="button-101",emoji="📝",style=discord.ButtonStyle.success,row=1)
async def reg2_button_callback(self, button: discord.ui.Button, interaction):
await interaction.response.edit_message(view=self)
user = self.auth_id
await interaction.response.send_message(f"{user}")
class Reg(discord.ui.Modal):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.add_item(discord.ui.InputText(label="Team name:",min_length=1,max_length=25,placeholder="Enter team name." ,style=discord.InputTextStyle.long))
self.add_item(discord.ui.InputText(label="Tag:",max_length=8,placeholder="Enter command tag.", style=discord.InputTextStyle.multiline))
self.add_item(discord.ui.InputText(label="Players(1-6):",max_length=200,placeholder="P1.Player1\nP2.Player2\nP3.Player3\nP4.Player4\n ", style=discord.InputTextStyle.paragraph))
self.add_item(discord.ui.InputText(label="Troi spot:",max_length=70,placeholder="Enter TROI spot.", style=discord.InputTextStyle.multiline))
self.add_item(discord.ui.InputText(label="Erangel spot:",max_length=70,placeholder="Enter ERANGEL spot.", style=discord.InputTextStyle.multiline))
async def callback(self, interaction: discord.Interaction):
guild = interaction.guild_id
author = interaction.user
self.auth_id=interaction.user
if self.children[0].value == 'MARIARH':
await interaction.response.send_message(f"Team banned")
else:
team_n = self.children[0].value.replace("'", "`", 1)
tag_n = self.children[1].value.replace("'", "`", 1)
cursor.execute(f"INSERT INTO teamlist VALUES ('{team_n }','{tag_n}','{author.id}','{guild}',' ')")
db.commit()
await interaction.response.send_message(f"{self.children[0].value} | {self.children[1].value} |{author.mention} \nPlayers:\n{self.children[2].value}\nTroi spot:{self.children[3].value}\nErangel spot:{self.children[4].value}",view=RoleButton())
```
?\
Do you know what you are doing?
Something that, in fact, should not work. And I understand this.
But I do not really understand how to transform the idea into reality
You are asking so much stuff here?
I don't understand this
Please provide a link to an example.
I can explain again what I need.
Eh, Im not sure if you really know basic python
This is the problem that I know. But it is difficult for me to explain myself because I am from Ukraine.
It's hard for me to understand you.
Okay you can't help me:(
They might not understand because google translate messes things up
Yes...😕
That's why I'm asking for examples.
May small,but ex.
This is an object (class) attribute
dog = Dog()
dog.some_attribute = "hello"```
Ok ..
You've been told before to learn Python before asking questions here




