#Basic Pycord Help (Quick Questions Only)
1 messages · Page 25 of 1
or either make ephemeral= True to make it so that only one user sees it and that is the original author of the command
rather I'm stupid
https://docs.pycord.dev/en/master/api.html#discord.ui.View.on_timeout
rtfm
isn't there a way by which I can specify that I only need 2 fields in one line? because when ever I do it I get 3 in one line
Try using inline = False for the last one and the opposite for the others.
does anyone know how to load/unload cog extensions? because I cannot get the slash commands to go on and off... xd
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'Interaction' object has no attribute 'edit'
msg = await ctx.respond("...")
await asyncio.sleep(2)
await msg.edit(content = f"...")```
is this issue fixed in v2.2.0
https://github.com/Pycord-Development/pycord/issues/1630
Yes.
Hey!
@commands.Cog.listener()
async def on_message(self, ctx):
if ctx.author.bot:
return
# Check if message author is self
if ctx.author == self.bot.user:
return
# Check if message is in DMs
if ctx.guild is None:
await ctx.channel.send('Message author: ' + ctx.author.name)
await ctx.channel.send(
"**Tere!** Mina olen jumal. **Palun vastake `jah`, kui soovite saada kodanikuks.**")
reply = await self.bot.wait_for('message', check=lambda message: message.author == ctx.author)
if reply.content == "jah":
await ctx.channel.send(
"**Palun saatke pilt oma Tallinna Reaalkooli õpilaspiletist. Võite oma isikukoodi ära blurrida, kui soovite.**")
else: # If reply is not "jah"
await ctx.channel.send(
"**Okei, kahju. Kas te teadsite, et 98% lahedatest inimestest on juba kodanikud? Ja sina kindlasti seal 2% seas ei ole.**")```
This would retrigger the wait_for every time a message is sent.
What should I do?
I want basically any message in the dms to be a trigger for the wait_for
how do you delete a response sent by the bot
I do it by using this trick, after saving the message_id while sending the response.
message = [discord.Object(id = message_id)]
await channel.delete_messages(message)
If you have the Message object already, you don't need the first line.
nice
Actually, I need this. How do I get the Cog object to pass there? 
for those who have the same issue I suggest using this way:
await ctx.respond("smthing", delete_after = {time})
...```
That's perfect if you know the time. My bot has to wait for an unknown amount of time, so I went for that solution.
How am I supposed to reset cooldown in a slash command group?
This is my current code for resetting slash commands cooldown
for command in self.bot.walk_application_commands():
command.reset_cooldown(ctx)
But it raises the following error
'SlashCommandGroup' object has no attribute '_buckets'
Try with that. I don't know if there is a better way.
Is there any documentation for migrating from discord.py? more specificly 1.7.3
I don't think so. I've used the guide and occasionally the docs.
Link: https://guide.pycord.dev/
This was very brief and just mentioned uninstalling the old lib, I'm more interested if I have to rewrite stuff and how much
Thanks
Oh, right! I forgot about that page. 
having issues using defer/followup
Very recently (last couple weeks), functions that used to work properly are now throwing
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
when it gets to the await ctx.send_followup part of the code.
Everything else works normally, but it can't send messages/respond to users even with defer
The time between defer and the intended followup is under 10 seconds. Too long to do it without defer, but not even remotely long enough for the defer to expire
send code. thanks
@slash_command(description="Whose address is this?")
async def whose_address(self, ctx, address):
await ctx.defer(ephemeral=True)
addressee = ""
address_ver = db['address_registry']
for userid, user_info in address_ver.items():
if address in user_info['address']:
addressee = await self.client.fetch_user(int(userid))
print(f"{ctx.author.display_name} queried {address} and found {addressee.display_name}, {addressee.id}")
break
if addressee != "":
await ctx.send_followup(f"The resident of this address is {addressee}")
else:
await ctx.send_followup(f"Address not found")
what does it show from the user side
what do you mean?
they get an Application Failed
but I still get the print in the console
so the defer doesn’t trigger.
doesn't trigger?
like it doesn’t say “Bot is thinking”
I suppose not. I'm only getting screenshots from users with the Application Failed message. When I use it, it often/always works as expected
what might cause the defer to fail to trigger?
maybe their discord isn’t up-to-date
hi uh need emergency help idk what to put in await ctx.invoke()'s first parameter which is the command but what do i put in, do i pass in the coroutine? or what
ok nvm solved.
Hi! are the messages saved in cache by the bot removed after a while? is there a way to remove them to limit the memory?
When I use: python3 -m pip install -U py-cord==2.2.0 I get an error: metadata-generation-failed
Does anyone know how to fix this, I’m using Python 3.10.7
Did you try adding ephemeral=True to the send_followup()? I'm not sure if needed.
I guess do this
pip install py-cord--2.2.0
though I won't be upgrading yet, since I'll have to make the necessary changes 😭
hey, how can i add a button to a static message of the bot?
and keep them working even when the bot is restarted
Hey I'd like to fetch a guild category by Category ID, is that possible?
Channel = await guild.create_text_channel(f':green_circle:︱hello')```
Unable to create channel, gives Error:
Channel = await guild.create_text_channel(f'🟢︱hello')
AttributeError: 'coroutine' object has no attribute 'create_text_channel'
class pointsView(discord.ui.View(timeout=None)):
Throws RuntimeError: no running event loop
Help
you don't subclass like that
fetch_guild needs to be awaited otherwise it will just return the coroutine
How then
discord.ui.View(timeout=None) creates an instance of ui.View, when subclassing you put the class object inside the brackets, ex. (discord.ui.View)
gotchaaa
thanks!
Why do buttons stop working after bot restarts?
because the client doesn't know what callback to attribute to that particular button
you could make your own handler in on_interaction that checks the custom_id
or you could use "persistent views"
i think there's an example in the examples directory
Yeah thanks fixed it using persistent views
what's the difference between raw_status and status? Is it similar to other raw events vs events without the raw?
it tells you the difference if you click them
is there like a rate limit on the bot starting it doesnt respond for like 30 seconds if i do it too quickly
with slash commands, you can restart at most twice per minute
Is it possible to make a .check for a specific SlashCommandGroup?
you can pass the checks=[...] kwarg when creating the group, being a list of check functions
What would checks accept
any check functions or custom check functions
import discord
from discord.ui import Button
from discord.ext import commands
intents = discord.Intents.default()
intents.guilds = True
intents.messages = True
intents.message_content = True
intents.members = True
bot = discord.Bot(command_prefix='%', intents=intents, debug_guilds=758416321284276226)
TOKEN = "GRAHHHHHHHHHHHHHHHHHHHHHHHHH"
@bot.command(description="test")
async def ohio(ctx):
await ctx.send(f"Latency {bot.latency} ")
@bot.group(description="test")
@commands.has_role("OHIO LEADER")
async def add():
pass
@add.command()
@commands.has_role("OHIO LEADER")
async def councilmember(ctx, usr: discord.Member):
await usr.add_roles("OHIO COUNCIL")
await ctx.send("ohio council member added")
bot.run(TOKEN)
And then i get this error message
- TypeError: add() got an unexpected keyword argument 'guild_ids'
full traceback, thanks
-Traceback (most recent call last):
- File "C:\Users\paul\PycharmProjects\stuffs\main.py", line 22, in <module>
- async def add():
- File "C:\Users\paul\PycharmProjects\stuffs\venv\lib\site-packages\discord\bot.py", line 893, in inner
- group = cls(
- TypeError: add() got an unexpected keyword argument 'guild_ids'
you are using discord.Bot which does not support prefixed commands
im trying to do slash commands
i deleted the command prefix thing but then it still gave me the same error
Here's the slash groups example.
this is how you create a slash command group. it is different than prefixed commands.
Excuse me, can someone help with loading and unloading with the cog files? The slash commands work, but the load/unload does not do anything.
I made a thread here:
https://discord.com/channels/881207955029110855/1026389086946197564
how can i use async init function to initialize a select menu?
addmember = discord.SlashCommandGroup("add", "peen")
@addmember.command()
@commands.has_role("OHIO LEADER")
async def councilmember(ctx, usr: discord.Member):
await usr.add_roles("OHIO COUNCIL")
await ctx.respond("ohio council member added")
bot.add_application_command(addmember)
Gives me this error
Ignoring exception in command add councilmember:
Traceback (most recent call last):
File "C:\Users\paul\PycharmProjects\stuffs\venv\lib\site-packages\discord\commands\core.py", line 127, in wrapped
ret = await coro(arg)
File "C:\Users\paul\PycharmProjects\stuffs\venv\lib\site-packages\discord\commands\core.py", line 881, in _invoke
await self.callback(ctx, **kwargs)
File "C:\Users\paul\PycharmProjects\stuffs\main.py", line 25, in councilmember
await usr.add_roles("OHIO COUNCIL")
File "C:\Users\paul\PycharmProjects\stuffs\venv\lib\site-packages\discord\member.py", line 975, in add_roles
await req(guild_id, user_id, role.id, reason=reason)
AttributeError: 'str' object has no attribute 'id'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\paul\PycharmProjects\stuffs\venv\lib\site-packages\discord\bot.py", line 992, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\paul\PycharmProjects\stuffs\venv\lib\site-packages\discord\commands\core.py", line 358, in invoke
await injected(ctx)
File "C:\Users\paul\PycharmProjects\stuffs\venv\lib\site-packages\discord\commands\core.py", line 127, in wrapped
ret = await coro(arg)
File "C:\Users\paul\PycharmProjects\stuffs\venv\lib\site-packages\discord\commands\core.py", line 1171, in _invoke
await command.invoke(ctx)
File "C:\Users\paul\PycharmProjects\stuffs\venv\lib\site-packages\discord\commands\core.py", line 358, in invoke
await injected(ctx)
File "C:\Users\paul\PycharmProjects\stuffs\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: AttributeError: 'str' object has no attribute 'id'
@silver moat
its role.id there
you are giving a string "OHIO COUNCIL"
instead, give them the role object
Is it possible to do this in PyCord, and if so, how? I if that study API REF. but I don't know what it's called.
I didn't understand.
Do you want to have the list of slash commands?
I want those who do not have the right role to have this picture displayed. So that users do not touch the bot once again.
I just want the command unnecessary for the user to be unnecessary. Or so that this command could not use a certain role.
I don't know how to make the commands not appear.
But for the permissions, here it is
https://docs.pycord.dev/en/stable/ext/commands/api.html#discord.ext.commands.has_permissions
Mmmmm. Ok thx, but I need a Slash
Okay
Bye
Not only that, it also works with a prefix, but it won't be in the list.
Thx, for help
Is it possible to create a link to a Slash Command with pre-compiled options?
For example, I'd like the text Sky to be a link for /image name:sky.png size:1920.
From a link to a command?
From a word to a command and then to a link?
The user clicks on the word and the command appears in chat.
Where is the word written?
Does the command have to be written? As a var (ctx.respond("Your command here")) Or be used and give a result?
The word goes in the description for a filed in an Embed.
Hey, guys, is it possible to automate the new Pause Invites feature via the bot?
nvm.. await guild.edit(disable_invites=True)
thanks pycord, i love u
If I send context.user.mention in a private message, will it always appear as a mention/link to the user profile (eg. @spice oyster) or not?
Think about when you are not sharing a server with the user, so you likely never met before.
Is it possible to use something like @commands.is_owner() to check if a given user is in a list of allowed users to use that Slash Command?
I cannot use Roles because it has to work across different Discord servers where I don't have the power to add Roles.
Can my bot send private messages to users that have blocked private messages from people in the same servers as them?
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: OSError: cannot open resource
?
why this error?
the link and the text s provided by the user?
No, they are loaded from a database while building the embed.
so umI have an idea
/image [provide choices]
and link those choices with the ids of secific images
and iterate through your db to find the id matching the request and grab the link
and display result
is this what you were asking?
@spice oyster
For example, I want to click on a link and get something like this in chat.
I don't think so but it's better to ask. I know how to get the command, but not the options.
how do you get the command through a link?
#1023056728998289492 message
um if you don't mind may I ask smthing?
Sure. 
does slashcommandgroups work with slash command on your bot?
cause in mine the options never seem to appear
The command will not be written but you can send an embed containing the command to be written
Yes, they work in cogs.
ahahah same prob
#1026261825739837491 message
You should not use create_group but SlashCommandGroup except that this one works only in a cog
@fervent cradle
I had the problem and spent my morning working on it
kk
looks like gotta make some cogs for my bot
You can make one with all your orders, even if it is not super optimized it will work
I have three files for my three groups of commands
so I should create a separate file for every group?
and if possible can you tell me what are the "handlers" and "modules" files?
.
Is there something wrong here?
You don't have to, but you can.
This is my code that works with this, in module I process the commands.
In handler I realize the actions in database, I was forced to separate in several files.
Yes, I think so.
indentation, if you have copied the code from discord or a site you may have problems
his indentation seems fine to me
Sometimes the visible indentation is good but the invisible character bug
I had it again this morning, I had to delete and redo my indentation
@west flume ^ seems like u will have to do that
🗿 Alr then
If you work with VSCode and the python extension you have everything underlined
how to check if a user has accepted rules or not?
why does interaction.response.delete_original_response() now return an unknown webhook error?
i need fix
https://docs.pycord.dev/en/stable/api.html#discord.Member.pending
I think that's it
Thanks!
so pending will be true if not set up or in non-community servers by default?
What's the difference?
Me neither. I use 4 spaces to avoid confusion.
Tell your editor to convert Tab into Spaces and you will be fine, I think.
@bot.command()
@commands.has_permissions(ban_members=True)
async def ban(ctx, member: discord.Member, *, reason=None):
try:
await member.ban(reason=reason)
embed=discord.Embed(title="**Moderation: User was Banned**",description=f"{member}, Has been banned .\nReason is `{reason}`. This ban was requested from\n{ctx.author.mention}",colour=0x42F56C)
embed.add_field(name="Expiration:", value=f"``Permantly``", inline=True)
embed.add_field(name="Banned By:", value=f"``{ctx.author}``", inline=True)
await ctx.send(embed=embed)
except Exception as e:
await ctx.send(f"Failed to ban: {e}")
can someone help me?
Full traceback?
wait
Ignoring exception in command ban:
Traceback (most recent call last):
File "/home/runner/Vilan-2/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 184, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 130, in ban
await member.ban(reason=reason)
File "/home/runner/Vilan-2/venv/lib/python3.8/site-packages/discord/member.py", line 665, in ban
await self.guild.ban(self, reason=reason, delete_message_days=delete_message_days)
File "/home/runner/Vilan-2/venv/lib/python3.8/site-packages/discord/guild.py", line 2973, in ban
if not (0 <= delete_message_seconds <= 604800):
TypeError: '<=' not supported between instances of 'int' and 'NoneType'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/Vilan-2/venv/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 342, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/Vilan-2/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 951, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/runner/Vilan-2/venv/lib/python3.8/site-packages/discord/ext/commands/core.py", line 193, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: '<=' not supported between instances of 'int' and 'NoneType'****```
Where is delete_message_days in your code?
Maybe you forgot to pass it and it defaulted to None.
nvm, indentation error
How do i make my bot available for multiple guilds? I had my one guild_id as a parameter for my @bot.slash.commands. When try to add another one i get "discord.erros.Forbidden: 403 Forbidden (error code: 50001): Missing Access
i added it but the same error
The bot needs permission to be in the servers you want to add there. Invite the bot user or check if they have the correct permissions, then run the bot.
are you on 2.2.0?
ok
ty
Does anyone know i can get the values from a websites dropdown menu? I just want a command that responds with everything in this list. Example:
Aghanistan Remaining (1)
Albania Remaining (2)
...
The bot wasn't invited with the application.commands scope
try beautifulsoup4
page = get('https://mywebsite/test')
soup = BeautifulSoup(page.text, 'html.parser')
soup = soup.find('select', class_ = 'form-control')
items = soup.select('option[value]')
values = [item.get('value') for item in items]
print(values)
await ctx.respond(values)
I tried this which kind of works but it only returns the values ie "Afghanistan" and not the "Afghanistan Remaining (0)"
try values = [item.text for item in items]
That worked! Thank you.
So i formatted the results into new lines. Do you know how i could ignore all the lines containing 0?
[item.text for item in items if "(0)" not in item.text]
Thank you very much! I appreciate it.
how would yall recommend me to add persistent views?
i dont understand this example at all
https://github.com/Pycord-Development/pycord/blob/master/examples/views/persistent.py
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/persistent.py at master · Pycord-Development/pycord
daily limit? Isn't there a way around it?
Can anyone brief the situation, why am I getting this?
you are getting this because you reached the daily limit of 200 application command creations
slash command?
I believe Pycord re-registers your command when you restart your bot
What specifically do you not understand about it?
You reached the daily rate limit and you should wait it out.
me? or my bot?
cause even if I use an alt to send commands it doesn't work
on which message does the view get added? i dont see any send_message there
examples/views/persistent.py line 74
await ctx.send("What's your favourite colour?", view=PersistentView())```
It's your bot that reached the limit.
ahh ty i didnt even see that
So like my bot can't process more that 200 commands a day
No, it cannot create more than 200 commands a day
so what if my bot is in 5-6 servers and 10 people in each server use it
I didn't create any new commands other than a simple 'suggestion' and an image command
you probably restarted it too much
If you made a global command, then that's one create. If you made 5-6 guild commands that's 5-6 creates.
oh that's why it created the same command over and over again and filled the rate limit?
maybe its changed since last time
Pycord only registers/creates commands if the bot doesn't have them
lmao I am wondering the same thing
could be shared host, not sure tho.
Yea maybe I tried hosting the bot for a while
shared *
ok nvm I think ima sleep
good night
ok gn
Hey, I'm trynna lock a channel I just created to a User and a Role
how do I create the overwrtire for this
I can create overwrite for Bot and Everyone, not sure how it's done for a Specific User and Role
hey, im trying to set up this persistent view, but i keep getting this error:
ValueError: View is not persistent. Items need to have a custom_id set and View must have no timeout
i did give all of the items a custom_id except the url button since that one cant have a custom_id
did you set the view timeout to None?
No, that's not the default value.
Learn all about implementing buttons in your Discord Bot using Pycord.
ahh thanks
How to get the "About Me" section of a given user? 
my bot keeps randomly saying interaction not found even when i use await ctx.defer()
is it just discord being slow or is it my problem
not possible
if i had to guess, your bot is somehow taking longer than 3 seconds to recieve the event; perhaps a network issue or you have blocking code elsewhere in the bot?
I noticed that bot.users fluctuates between restarts. what causes this?
Caching I believe
is there a way to make it more consistent?
or is there a more accurate total-user-count?
hello again
client.run is a blocking call
anything after it isn't executed
how can i fix that?
Discord told me in no uncertain terms that this will likely never be in the API.
use ctx.respond if you use slash_command
no im trying to create multiple lines for the description
add a \n
that being the escape code for the new line character
just like you have \t for a tab and \r for carriage return
How do I enumerate() here?
for offlaner, amount in zip(offlaners, amounts):
>>> for a, (b, c) in enumerate(zip("abc", "def")):
... print(a, (b, c))
...
0 ('a', 'd')
1 ('b', 'e')
2 ('c', 'f')
addmember = discord.SlashCommandGroup("add", "peen")
@addmember.command()
@commands.has_role("OHIO LEADER")
async def councilmember(ctx, usr: discord.Member):
await usr.add_roles(id=1026656532642942986)
await ctx.respond("ohio council member added")
bot.add_application_command(addmember)
And I get this error now
- Ignoring exception in command add councilmember:
- Traceback (most recent call last):
- File "C:\Users\paul\PycharmProjects\stuffs\venv\lib\site-packages\discord\commands\core.py", line 127, in wrapped
- ret = await coro(arg)
- File "C:\Users\paul\PycharmProjects\stuffs\venv\lib\site-packages\discord\commands\core.py", line 881, in _invoke
- await self.callback(ctx, **kwargs)
- File "C:\Users\paul\PycharmProjects\stuffs\main.py", line 25, in councilmember
- await usr.add_roles(id=1026656532642942986)
- TypeError: Member.add_roles() got an unexpected keyword argument 'id'
- The above exception was the direct cause of the following exception:
- Traceback (most recent call last):
- File "C:\Users\paul\PycharmProjects\stuffs\venv\lib\site-packages\discord\bot.py", line 992, in invoke_application_command
- await ctx.command.invoke(ctx)
- File "C:\Users\paul\PycharmProjects\stuffs\venv\lib\site-packages\discord\commands\core.py", line 358, in invoke
- await injected(ctx)
- File "C:\Users\paul\PycharmProjects\stuffs\venv\lib\site-packages\discord\commands\core.py", line 127, in wrapped
- ret = await coro(arg)
- File "C:\Users\paul\PycharmProjects\stuffs\venv\lib\site-packages\discord\commands\core.py", line 1171, in _invoke
- await command.invoke(ctx)
- File "C:\Users\paul\PycharmProjects\stuffs\venv\lib\site-packages\discord\commands\core.py", line 358, in invoke
- await injected(ctx)
- File "C:\Users\paul\PycharmProjects\stuffs\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: TypeError: Member.add_roles() got an unexpected keyword argument 'id'
nevermind i got it
How do I add multiple views to one message?
Oh, I was so close to try that! Thank you. 
you don't
you can add multiple rows to a view, but there can only be 1 view per message
if you need to use a different row, add row= to your select/button object
How would we add 2 buttons to a message then? Do they need to be in the same view?
? yeah
That’s kinda annoying
I wanna have a view for my Invite button and a different view for my support server button and sometimes I want both, so now I have to make 3 different views whereas if I could have multiple views in one message, I can just add both my support server view and Invite view rather than having to create a new view for both
hope that makes sense lol
but why different views?
but sometimes I just want my invite button on my command
you can just programatically add the buttons
like py view = discord.ui.View() if True: view.add_item(invite_button) elif False: view.add_item(support_button) else: ...the logic here is just an example, but it's not that complicated
my brain is already broken looking at that 😅
eh...
if what is true?
are they both url buttons?
yup
the logic there is just an example, it can be anything
if it's url buttons then it's even easier
how so?
since you can only make them with discord.ui.Button so you aren't dealing callbacks
what decides whether it's an invite or a support server button?
depends on the command really
did you subclass the view elsewhere? or are you just doing view=discord.ui.View()
might be easier if you showed the code
Also, if you really want to you can just write a function to do this for you instead of writing that every time
well I tried quite a few things but I’ll show u what I have rn
it works but I wanna have separate views
oh
hold on let me remove the invite
yeah LOL
class OnAzielInviteView(discord.ui.View):
def __init__(self):
super().__init__()
style = discord.ButtonStyle.gray
vote = discord.ui.Button(style = style, label = "Top.gg!", url = "https://top.gg/bot/981332858230698069/vote")
support = discord.ui.Button(style = style, label = "Support", url = "https://discord.gg")
self.add_item(vote)
self.add_item(support)
ok isee
why don't we add a variable to the view call then? e.g. if you do view = OnAzielInviteView(invite=True) or something, it'll only add that button
there are several ways to go about this but that would keep it flexible
sure!
so simply we're looking to add stuff to __init__ py class OnAzielInviteView(discord.ui.View): def __init__(self, support=True, invite=True):then later on in the init, we just add conditionspy if support: ... # add the support button
this way, by default if you just call OnAzielInviteView() you'll have both buttons
but if you, for example, wanted to hide the support button, you would do OnAzielInviteView(support=False)
Ooo, I see
you can change this as you wish to set defaults etc.
class OnAzielInviteView(discord.ui.View):
def __init__(self, invite = True, support = True):
super().__init__()
style = discord.ButtonStyle.gray
vote = discord.ui.Button(style = style, label = "Top.gg!", url = "https://top.gg/bot/981332858230698069/vote")
support = discord.ui.Button(style = style, label = "Support", url = "https://discord.gg")
if support:
self.add_item(support)
if vote:
self.add_item(vote)
Like this?
remember thy indentation
^
and perhaps change the elif to just if
because you're always checking both conditions separately
got it, and could I add more buttons like this with the same type of idea?
mhm
awesome, tysm :)
I have the same thing
if you wanted you could also move the button creation inside the if statements so you don't have unused variables lying around
oh wait
also make sure your variables all have different names
e.g. they're you're overriding the support=True with support = Button, so maybe rename the buttons to support_button etc. so nothing clashes
kk ty!
issue fixed you need to add delete_message_seconds=0
wait
did this work with member.ban?
or did you use guild.ban(member, ...)
thank you.
it's fixed in the next release but just checking
await member.ban()
yea
interesting, from my testing it should have errored on member.ban but if it worked then fair enough?
Is there a rule against implementing automatic ban processes within a bot?
Like a blacklist that autobans when they join
I havnt fully read discord bot tos, and so im not fully educated if it would be some kind of foul play
i don't think so?
there may be clauses/rules regarding how you store data used with your bot, necessary data etc., but autobanning in itself would be fine
Guys. If anyone have a problem in his code, its easy to solve it, just fix it !
someone has an idea why pycharm professional is letting SQL queries look so weird?
I have a question about merging lists in Python. Anyone knows how to solve this? 
m = [("H", 1), ("A", 4)]
o = ["A", "B", "C", "H"]
r = create_results(m, o) # How to implement this function to get these results?
print(r)
> [("A", 4), ("B", 0), ("C", 0), ("H", 1)]
I'm wondering if there is a better way to do it than just using nested for loops.
results = []
for letter in o:
for x, num in m:
if letter == x:
results.append((x, num))
break
else:
results.append((letter, 0))
print(results)```
there generally are ways to do it other than this, tho it's not better, it'd be easier to use this
Thanks! I'm trying to do something similar but it's not easy. I'll try your version.
It's basically the same code until break because I was still trying to figure out the end.
That's perfect! How did you solve it so quickly and with zero mistakes? I didn't think about the else after the for loop. 
or as a list comprehension, result = [(x, num) if letter == x else (letter, 0) for x, num in m for letter in o]
(dunno if it works, didnt test)
Thanks! I'll try tomorrow. Now it's kinda late here. 
hello there, im trying to get the stats of my bot,
my code just returns a valueerror, idk what am i doing wrong
and what is the error?
oh sorry, it says ValueError, idk what i should replace
AttributeError: 'info' object has no attribute 'datetime'```
```discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: module 'discord.ext.commands' has no attribute 'ValueError'```
looks like my uptime var is the cause
have you defined self.datetime?
lemme try
why are u calling self
Probably a function they made?
you dont have to try... you have to look at the code and say "yes or no"
no
sorry
what is self.datetime?
wdym?
wait now i tottaly dont understand, i defined my current time(current) then compare the current time with the execution time(idk if i use the right ones)
it is not defined? i think idk
so why are u use it as a variable
If you can't read your own code, you shouldn't ask for help
ahhhh, im ashamed im sorry, thank you for making me realized the i should always 10x check my code, will remember this mistake for a lifetime
Edit: i forgot to make start variable as a global variable
works as intended now
can answer this now, i still dunno what is this, this is not defined and wont work
Do you realize now - start will always be 0
yea i forgot to make it as a global variable
oke now, thanks
how do i get the channel that the command was executed in?
ctx.channel
Anyone know why this isn't working? (The on_timeout, I am actually using the view)
make_pages.py
class TicketButtonsView(discord.ui.View):
def __init__(self, ticket_id):
super().__init__(timeout=20)
self.ticket_id = ticket_id
self.add_item(TicketCloseButton(ticket_id=ticket_id))
self.add_item(TicketDeleteButton(ticket_id=ticket_id))
self.add_item(TicketOpenButton(ticket_id=ticket_id))
async def on_timeout(self) -> None:
logger.debug(f"TicketButtonsView timed out for ticket {self.ticket_id}")
await self.message.delete()
make_pages.py
def make_view(ticket):
view = TicketButtonsView(ticket_id=ticket.id)
return view
async def ticket_admin_list(self, ctx: ApplicationContext):
"""List all open tickets."""
await ctx.defer(ephemeral=False)
tickets = await get_all_open_tickets()
if tickets is None:
await ctx.respond("There are no open tickets.")
return
else:
pages = []
first_page = discord.Embed(title="Open Tickets", timestamp=arw.now('US/Eastern').datetime, description="All open tickets are listed on the following pages.")
pages.append(Page(embeds=[first_page]))
for ticket in tickets:
pages.append(Page(embeds=[await make_embed(ticket, bot=ctx.bot)], custom_view=make_view(ticket)))
pager = Paginator(pages=pages)
await pager.respond(ctx.interaction, ephemeral=False)
I am not getting any traceback, yet the view doesn't delete the message on_timeout
how do i send buttons to the next row
There is an attribute on Buttons, I believe. Search for Button in docs.
how to remove global slash commands?
I need a Slash Command to only show in private messages with my bot. How to do it?
I don't want to use @commands.dm_only() as a decorator because the Slash Command will still be visible outside of private messages.
In other words, I need dm_only as attribute, similar to guild_only, but sadly it's not there.
Link: https://docs.pycord.dev/en/master/api.html#discord.SlashCommand.guild_only
I deferred an interaction and tried to send a modal after, but it says this interaction has been responded before? I don't see this error when sending normal messages
No tag code found.
?tag didnotwork
No tag didnotwork found.
gahhhh
If I remember correctly, it's not possible to defer and then send a Modal.
You have to do it differently (eg. send the Modal immediately, or add a Button to open it).
If Bot.debug_guilds is configured, is it possible to still create global commands at all? like override it on a per-command basis or something?
wasnt sure if that was just a default behaviour or a hard restriction
Because of that change, for testing commands, I prefer to use guild_ids (from Slash Commands or Slash Command Groups) or a completely different bot just for testing purposes, depending on what I need to do.
fair enough, thanks
How can i make a custom method of Bot instance? So that i can use it in other cogs too
for that you'll have to create your own bot class, inheriting from discord.Bot
How to easily convert Solved with date_time = message.created_at into content = "<t:{date_time}:F>" printable format?int(date_time.timestamp()).
Subclass discord.Bot and make your own method from there
is it possible to make command groups like how we make slashcommand groups
smthing like this
?admin ban
its possible to do that in slash commands with the groups but can we do the same for prefix commands
So basically import just Bot in main file, make a new class with its name and create method ryt?
I'm probably going to ask a dumb question and get disowned, but there is no way to "hide" a / command so that only certain people (me and my friend) can use them?
yep. Here's a page from the guide if u need help on it: https://guide.pycord.dev/popular-topics/subclassing-bots
Subclassing is a popular way of creating Discord Bots. Explore how you can create a Discord bot by subclassing.
There isn't any way to hide slash commands irc, but what u can do is to check for whether the user running it is you or your friend
Or the other way is to just load that command only in the guild that u and ur friends is in
Sure, it what i do for others commands
Thanks for the answer so !
I hope we can do that one day
oh thanks, really needed this
np
if you have manage server permissions, you can do it from guild settings
Yea ik that, but i want to make it for all the server my bot join
but if it don't have the perm, it wont work :/
but yeah no "direct" way to do it from the bot, it'd either be guild_ids or using default_member_permissions for stuff like administrator
And i need to add another intent e-e
My goal is to remove the messages intent, so i need to make bot admin command into slash commands
you can still use your prefix commands without the intent
just add the bot mention as your prefix
Nah it doesnt work :/
wdym ?
Ho i see
alternatively you could also just do them all in DMs
pretty interesting
Sure
How i can add the mention in prefix ?
remove the basic one ?
there's a built in helper for setting the prefix to the bot mention
https://docs.pycord.dev/en/master/ext/commands/api.html#discord.ext.commands.when_mentioned
or the alternate one which can be mention + your own custom prefixes
https://docs.pycord.dev/en/master/ext/commands/api.html#discord.ext.commands.when_mentioned_or
its easier that i think
So i'll try it rn
Another question, i need 2 intents for message :
intents.message_content = True
intents.messages = True```
If i remove one, it doesnt work anymore
Why ?
message_content is the privileged one for specifically message.content, message.attachments, message.embeds and probably a few others
while messages is for all message events; this isn't privileged and is necessary for the bot to see the message event at all
hmm
Okay, and i need it too with bot mention ?
yes
is there any reason you don't want it at all?
I'm trying to remove as much as possible RAM from the bot. As i read, the messages intent keep message in caches, so if i remove it it would be nice
How ?
inside commands.Bot, set max_messages=None or any integer to change the limit
I searched about the RAM on pycord/discord but found nothing, except how to raise an error when ram exceed something
Woaw it's work really well
Could it be a problem to set this one to None?
And, there is a way to remove cache from these too ?:
intents.reactions = True
intents.guilds = True
intents.members = True```
Well, i see that my bot doesnt remember his message so can't add reaction
dem that's not easy
you could reduce it to something like 100 messages instead, so it'll remember the more recent stuff
If i put a button instead of a reaction, it work ? (i dont have any commands with buttons)
these days buttons are encouraged over reactions yes
For this reason, or another one ?
well
buttons are designed to be used as responses
and as interactions they don't rely on the message/other intents
I see
it's advised you keep the guild cache because you lose a lot of functionality without it
So i can remove all the cache if i put button instead of reaction 🤔 ?
Okay
it should work yeah
as for members, you can control it with member_cache_flags=..., which takes a discord.MemberCacheFlags object
https://docs.pycord.dev/en/master/api.html#discord.MemberCacheFlags
interesting so,I didn't really want to switch to buttons but...
And members work the same way that messages ?
I use a lot of user information, and also fetch_user(), etc...
members are a bit different from messages
the docs page on MemberCacheFlags somewhat explains what you can enable/disable
So, if i use interactions i want to keep interaction and from_intents ?
to remove the others i can make member_cache_flags.joined=False ?
or member_cache_flags.intents work ?
from_intents will set joined=True since you have the members intent
So i need to put member_cache_flags.joined=False ?
Outside
Before
then do the same
kay
Options keep disappearing from my slash commands. I have no idea why.
There’s supposed to be an option here. This is happening to every command…
So, like this :```member_cache_flags= discord.MemberCacheFlags.all()
member_cache_flags.voice=False
member_cache_flags.joined=False
then in commands.bot i add `member_cache_flags=member_cache_flags`
it's that ?
Show code ?
does this happen on all clients? or does it show again if you reload or switch to another device
Everywhere
2.2 but i believe it happened on the older one too
will be fixed hopefully today when 2.2.1 releases, i think the best you can do is downgrade to 2.0.1
though this only breaks groups that were created with create_group
Ah so it’s a known issue?
Yeah uh every command on my bot uses group
did you mean cogs or groups?
Groups
info = bot.create_group(name="info", description="FAQ")
if you want you could move the commands to a cog and rework it a bit then load them, but if not then i'd say just downgrade
well... it was also broken on 2.1.3 and 2.1.1; 2.0.1 is the main version where it isn't broken
I was running on 2.1.1 without any problems until today
if it works on 2.1.1 then try that then
i wasn't sure if it was introduced in .1 or .3
So, about that ?
yeah that's fine
How i can check if it's work like i want ?
i mean, how i can check if voice for exemple is not in cache anymore
Do you know an extension for Visual Studio Code that can highlight repeated block of codes in a file/project while ignoring space characters? 
Can a slash command option accept a command (so a command is referenced)?
not built in, but you could make it a string and use bot.get_application_command to get the command by name
you could go further and make it an autocomplete based on all your bot's commands, or use choices to show specific command names
Can you run pip freeze in your terminal for me and send the output?
How can I create a say command with slash
hmm, try reading https://guide.pycord.dev
class PersistentView(discord.ui.View):
def __init__(self, bot):
super().__init__(timeout=None)
self.bot = bot
options = []
s = guild
ss = self.bot.get_guild(s)
``` howcome self is undefined?
For what do you need the bot?
Huh?
learn python. thanks
rather rude response, i figured it out though. I used an instance
well, it was a basic OOP question.
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
Ignoring exception in command close:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 126, in wrapped
ret = await coro(arg)
File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 852, in _invoke
await self.callback(self.cog, ctx, **kwargs)
File "/home/container/commands/moderation/close.py", line 65, in close
await ctx.send(f"{Author.mention}, you have been inactive for `{DurationConverter(seconds)}`. If you don't respond <t:{int((datetime.utcnow()+timedelta(minutes=10)).timestamp())}:R>, this ticket will be closed{', and you will be blacklisted.' if blacklist else '.'}")
File "/home/container/.local/lib/python3.10/site-packages/discord/abc.py", line 1521, in send
data = await state.http.send_message(
File "/home/container/.local/lib/python3.10/site-packages/discord/http.py", line 353, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access```
I get Missing permissions, but I've never seen Missing Access. Any potential reasons why this happens?
Your bot should have permissions to send messages in that channel.
im assuming bot doesnt have the correct perms.
because you are using slash commands, reinviting your bot with the application.commands scope also should happen.
The channel would have been deleted 20 minutes ago, and did not work
so when I did use /close again, got the error
well, interactions bypass default channel permissions
did you mean to use ctx.respond instead of ctx.send?
I did do that in here
Fixed it, but still getting the error "Missing Access"
Could you send your code?
It's a very big file, but I'll send the essential
if auto: #Starts a timer for the ticket to close
try:
seconds = TimeConverter(auto)
except:
return await ctx.respond(embed=SetEmbed(ctx.guild,
"Invalid Argument",
f"`{auto}` does not follow the correct time format.\nEx. `1h30m`, `1d16h40m1s`",
discord.Color.red()), ephemeral=True, delete_after=30)
view = discord.ui.View(CancelButton(ctx.author), timeout=None)
Timer = await ctx.respond(embed=SetEmbed(ctx.guild,
"Timer Started",
f"This ticket will close <t:{int((datetime.utcnow()+timedelta(seconds=seconds)).timestamp())}:R>\n**Reason:** {reason}"), view=view)
msg = await ctx.interaction.original_message()
ChannelData["Timer"] = encrypt(msg.id, True)
Save("Channels", ctx.channel.id, ChannelData)
Save("Configuration", ctx.guild.id, ConfigurationData)
if seconds > 600:
seconds -= 600
await asyncio.sleep(seconds)
ChannelData = Load("Channels", ctx.channel.id)
if ChannelData:
if ChannelData["Timer"]:
await ctx.respond(f"{Author.mention}, you have been inactive for `{DurationConverter(seconds)}`. If you don't respond <t:{int((datetime.utcnow()+timedelta(minutes=10)).timestamp())}:R>, this ticket will be closed{', and you will be blacklisted.' if blacklist else '.'}")
await asyncio.sleep(600)
ChannelData = Load("Channels", ctx.channel.id)
if not ChannelData["Timer"]:
return
else:
return
else:
await asyncio.sleep(seconds)
ChannelData = Load("Channels", ctx.channel.id)
if not ChannelData["Timer"]:
return
try:
await Timer.delete()
await msg.delete()
except:
pass```
oh ic why you used ctx.send
@silver moat do u know how to do select menus IN slash commands, i cant find any documentation
Here's the slash options example.
thank you
this isnt related to the library but i think thats okay?
why cant i invite bots when i give them more scope than just bots?
elaborate
im trying to give it the applitcations.commands scope (for slash commands) and it wont join the server
if i only give it the bots scope with admin it joins fine
this has been the case with every other scope that ive tried
so giving it both scopes doesn't let it join?
yeah
hmmmmm
so when inviting, does it not let you select the server, confirm permissions etc?
no all of that is allowed, i authorize it and everything, but it just will not join
are you sure it isn't being kicked by another bot?
i dont have other bots in my server
i could try making a dif app
nvm
it seems to work now i just flicked some random settings lol
nice
how do i get rid of this?
You can’t
Discord limitation
dang
more like lamecord imo
can i at least delete the slash command when its used
If you are that desperate, use ctx.send instead of ctx.respond. It's really not worth it though.
yes
with ctx.send
it makes it slower though
okay thankks
No
nvm no thanks (im kidding)
ctx.send doesn’t actually respond to the interaction
then you will get an interaction failed
That doesn't appear if you use ctx.send...
Really though, just use ctx.respond
not worth it
alright
If you want the command to not show, just use ephemeral=True
Yeah it does, hidden. But you still get an interaction failed pop up. So yes it does.
But that also hides the response
oh right thats what it was
thanks for the help
:) welcome
ephemeral=True hides the response, they are talking about the x used /command part
is that not hidden too?
If you use ephemeral=True yes but only for the user
They wanted it removed entirely I think
no it suffices for what i need i think
However, bear in mind that if you use ephemeral=True then just note that the message will disappear for you too, after a few minutes, if you log out, etc.
yes alright thanks
sorry if its a lot of questions, im very new to using apis
whats wrong with this?
spelling
first line
man
also ctx.respond in slash commands
oh alright
I am encountering a new issue
So I have made a modal suggestion thing
When I try it once it works fine
But when I try to send another suggestion the command doesn't show up in the list
and all of the bots command don't show up aswell
is this supposed to be a bug?
yeah a discord bug
if something like await channel.edit(...) doesn't work because my bot is rate-limited, does it raise an error or return some unique value? i've been doing the following and was wondering if there's a better way
async def try_to_edit(obj_to_edit, **kwargs):
try:
async with async_timeout.timeout(1.5) as _:
await obj_to_edit.edit(**kwargs)
return True
except:
return False
how do i get user id when im given the tag and username?
or is there a way to get user id in a slash command that doesnt look ugly and user unfriendly
if you do, for example, \@mstang, you get my id: @somber cloak
wait what
idk if that helps, it's more for users
hold on brb
i dont think it would work
unless i did some scuffed thing where i make the bot send a message to figure out user id
yeah fair
well ill keep looking
maybe look at fetch_member or similar? you should be able to get the user object from the username i think
alright thanks
i think its backwards
it takes id as input and returns the name?
yeah it does
fetch_member returns a discord.Member object, not a name.
ahhh
yeah i have a discord.Member object and want to get a user id
do you know if thats possible?
youre so cool
ok
cant believe i got hit with the ok
it wouldn't be unique, but it will be a discord.HTTPException
you can use that to check the status code (429 if rl)
bro wtf
I swear I just restarted the bot 2-3 times
and I reached the daily application command creates?
I was just working with modals
heck
local host
Ok.
didn't use any hosts
it's really frustrating but I think god wants me to have a life ig
Uh... spend the rest of today fixing any errors you find, and then try again tomorrow.
but holidays are going on I have nothing but to sleep
I use this already tbh
Is there a way to store custom data in ApplicationContext? Or to pass a custom object from on_application_command -> the command itself -> on_application_command_completion. (Where the custom object is created in on_application_command)
I'm testing the lavalink audio player in the docs
I used the exact same code, I get this error
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: ContentTypeError: 0, message='Attempt to decode JSON with unexpected mimetype: ', url=URL('http://lavalink-replit.repluser69.repl.co:443/loadtracks?identifier=ytsearch:never+gonna+give+you+up')
any idea how I could solve this?
Hello i have a problem with the buttons
I want to make two buttons, each will give one value for a variable (1 or 5)
but i don't want to make TWO callback, but ONLY one
And if possible, i don't want to make a common fonction, i want all in the button class
You can do it like this: a callback for each button and a generic function. In each callback, call the generic function.
:/
You can keep it inside that class. I think it's fine.
Hmm you think ? i'll try this
Yes, I use that method for some of my Views.
Can you show me an exemple ? cause it don't work for me
Okay, nvm, i found myself
Ty for the answer !
Is there a forum version of on_thread_create so that you can make a bot join a new forum thread automatically?
it's the same event
forum posts are threads
Oh I see what I did
I used on_thread_join instead of on_thread_create...

Thanks a bunch Nelo
lol
Is it possible to load a slash command from a separate file?
no, cogs exist for no reason
If I understand it correctly, you're adding a slash command in a cog instead?
Here's the slash cog example.
Is there a way to tell Discord that I don't want to respond to a Slash Command or Interaction?
I basically want to get rid of the "This interaction failed" message without sending a message.
Solved by using interaction.response.edit().
Thanks
I presume that autocomplete function cannot return a discord.Role e.g.
async def get_option(ctx: ....):
User_Option = ctx.options
if User_Options == "role": return discord.Role
@bot.slash_command()
async def trying(
ctx: .....4
choosing: discord.Option(str, choices=["role"]),
returning: discord.Option(autocompete=get_option)
):
# STUFF
what error is raised when the embed cannot have more fields? (i am going to put in in a try: and except: area)
this is when i use add_field
How do you create a command group in a cog?
class Shop(commands.Cog):
def __init__(self, bot):
self.bot = bot
shop = self.bot.create_group('shop')
@shop.command(description = 'Buy an item from the shop')
async def item(self, itrc):
...
class Shop(commands.Cog):
def __init__(self, bot):
self.bot = bot
poll = discord.SlashCommandGroup("name", "description")
@poll.command(description = 'Buy an item from the shop')
async def item(self, itrc):
Why is self.bot not working?
Also is that the recommended way?
because self.bot isnt defined outside of a command or that async def
I would do it like this, it works fine
Ok, and you tried to use the main group, this is a subgroup capable type and i'm pretty sure this is supposed to be used in cogs
autocomplete can only do strings yeah
though since it supports OptionChoice, you could have name as the role name and value as the role ID to make it easier to get the role object within the command
Getting this error when using embeds=embeds and the total characters between 3 embeds is greater than 6000? I thought the 6000 character limit was just for a singular embed?
anyone got a clue why this import:
from discord.ui import Item
isnt working on my vps, while it does on my laptop? i installed pycord with pip3 install py-cord
all embed fields are counted in all embeds I believe
update your python. Py-cord requires python 3.8+
I'm not sure how it works. You can do this to check if each embed is below 6000 characters.
for embed in embeds:
print(len(embed))
Ive already checked and they are all below 6000
That’s what the list above the traceback was printing
the character limit is all embeda
Is that intentional?
Where? The part I've read doesn't seem to do that.
Bit weird that the character limit for one embed would be the same as that for 3 embeds when sent in the same message. Should I just send the embeds in separate messages then?
At this point, yes. I'm also surprised by that behaviour as I believe the limit is supposed to be per embed, not per message.
Actually, the docs for another library (not in Python) say it's per message.
The sum of all characters from all embed structures in a message must not exceed 6000 characters
Hmm that’s interesting.
discord states the following for the embeds field
Embedded rich content (up to 6000 characters)
implying that it applies to the entire field
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
Hello!
Do you know how to close modal after sending the data?
My code runs fine but the modal stays open and shows me a timeout, not cool!
respond to the interaction
You must override the callback() method and, as they said, respond to the interaction.
It's not like, say, Buttons in a View, that can use a random name for their callbacks.
I can't edit my embed from my callback, otherwise I could have tried to do this.
I should not send a message after sending the modal...
I'll think about it, thanks guys 🙂
I want to get the whole role if that makes sense
Thanks. I was looking for this but couldn't find it.
Pycord should probably mention that in docs, instead of saying 6000 per embed.
is there a way to color a button for only the user that clicks it?
No, UI elements are public.
thought so. thanks
You can use an ephemeral response instead.
is this command also in pycord?
@commands.has_role('RoleName')
pycharm auto complete doesnt give a has_role function, doing this import:
from python.discord import commands
How can i make a slashcommand without the wrapper? At the moment i am doing the SlashCommand class manually and it works. But in the Docs it says "decorator or functional interface", but i cant find any function for it. Which function replaces the slashcommand wrapper?
How can I get from a discord.Interaction the VoiceChannel the user is conected to (if conected to one)?
Give the parameter a default value.
You can check if the user who clicked the button is the same if you save the ID of the user who launched the command and compare it with that of the interaction of clicking the button.
Hey, this question might have been asked before I'm not sure but how do I get the guild id of the Guild from which the slash command was sent
(Yes I read the docs, there are 2 references to guilds, I'm not sure what to do here)
interaction.guild.id contains de id of the guild.
Do you have any idea how to check in a modal if the value is hexadecimal and if it is not the case that it returns an error?
i want to delete the message with a button, but i cant do it ( inside a view)
you can't raise custom errors inside of modals without it being dismissed, and all InputText fields are just regular strings
i have an timeoit where it can be easily deleted with await self.message.delete() but nothing seem to work here 
you can't delete ephemeral messages
there was some script manager on linux so i can run multiple python files in the background does someone know the name of that?
My test bot is able to get user = interaction.message.mentions from a private message between my account and the bot account.
My live bot is not able to do the same from a private message between a random user and the bot account.
To be precise, I get an empty list for the live bot. I don't understand why there is such a difference. Do you have any ideas? Ping me.
Fixed by using user_id = interaction.message.raw_mentions[0] instead. Docs were a bit confusing but they eventually helped.
How can I respond to an Interaction (after a Button click) without actually responding?
I just need to mark it as responded to avoid the interaction failed error.
Fixed by adding await interaction.response.edit_message(view = self).
just edit the message slightly
yeah
What does the pong() command do? I saw it in the docs.
responds to ping interactions
which you don't really get
it's just documented for sake of completion
Oh, ok! It's a sort of acknowledgement.
Can I get file as an input from user?
in a slash command, you are looking for discord.Attachment option type
kk
is there a way to resend this image to the user
lLike inorder to send you have to save the image then use the file path and stuff
but I don't want to save the file
.docslink discord.Attachment
Okay so let me make this clear:
I am making a command in which the user send an attachment to the bot, then the bot somehow saves the attackment to mongoDB (motor) and sends the user a confirmation message..
but before saving I want to test that the image can be resent to the user or not
don't want to save anything on the computer just either directly save or retrieve from the DB
So can someone shed some light on how should I execute these stuff cause I am kinda stupid to understand on my own
await interaction.response.defer()
await interaction.response.send(embeds=[embed])```
I cant repsond to an interaction twice, how do I defer it, if that's the case?
no 🙂
I read the docs and got this
but when I change await.interact.response.send_message(embeds=[embed])
to await.interaction.followup.send(embeds=[embed]) I get this
ah, ok
Now even though I have followup set, I seem to have the same error
😕
Truly sad
as in it sends the same <main....?
Modals can't be deffered. Must be sent in the first response.
can commands.Bot() take in owner_id
no work
then it doesn't
maybe owner_ids? that's the one I normally use I think
nop3e
works for u in commands.Bot?
it's been some time since I last worked on my bot so I'm not exactly sure anymore
what exception do you get?
nvm got it to work
what was wrong?
Apparently, VSC does not save the file before running
and it saved when i only typed the o
I should use Run & Debug...
I think VSC doesn't save at all on its own? not sure tho, always stopped using it quite fast each time I tried it again
it does when u use Run & Debug
its just that i hate run & debug cuz it delays stuff
ty
Hello, so recently, I have been doing some development implementing FastAPI to create a web respose system using an API just for the web pokes, then using the bot to send the message, and I know that in order to run the ASGI manager I use, I have to run it differently using another async function to "serve" the server. Now I was wondering if that was possible through pycord too. Like is there a way that I can make a bot start from an already running async loop?
Goddamn
Wait so
Bruh
Isn't modal for forms and stuff, that usually takes time doesn't it,that's where defer would come in use
What
I think you're confused on what deffering does
When you defer, you're telling Discord you need more time to respond. So, my logic says you should defer on the modal callback.
I have a dropdown menu for my help command and i will get this error relating to it once and awhile in my console. It doesn't impact the bot or command in any way but i would like to stop it from happening if i can. Any ideas?
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord/ui/view.py", line 412, in _scheduled_task
await item.callback(interaction)
File "/home/container/Bot.py", line 268, in my_callback
await interaction.response.edit_message(embed=embed)
File "/home/container/.local/lib/python3.10/site-packages/discord/interactions.py", line 928, in edit_message
await self._locked_response(
File "/home/container/.local/lib/python3.10/site-packages/discord/interactions.py", line 1057, in _locked_response
await coro
File "/home/container/.local/lib/python3.10/site-packages/discord/webhook/async_.py", line 221, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
yes needs more time, filling forms takes time, hence defer, but yea i see your logic thanks
also the pycord website returns this error
nvm fixed
hey kids
remember, when the dudes on stackoverflow or discord say, "read the docs", please read the docs, they're a life saver 👍
hm never tried running my bot under an ASGI server (probably won't any time soon), so idk if it's even possible to begin with. But for the answer, probably not
Im more looking for a way to get it to log in and start functioning. I know that if I can get it to run during the already active loop, then I should be able to load cogs through the event loop. I would just need to know if there was a way with the pycord api to log in the bot and connect it during the active loop. Ik you said probably not, but maybe that wording helps better define what I mean
Is bot.run() an instance of asyncio.run(), if so, then it blocks the async loop, but the async loop has ways to start processes during its time running
in the examplecode of recording audio is the filename the user_id.mp3
I want to add the username, but i don´t understand how to solve this. I don´t understand how the id is generated
async def finished_callback(self, sink, channel: discord.TextChannel, *args):
recorded_users = [f"<@{user_id}>" for user_id, audio in sink.audio_data.items()]
await sink.vc.disconnect()
files = [
discord.File(audio.file, f"{user_id}.{sink.encoding}")
for user_id, audio in sink.audio_data.items()
I found it! Its bot.start(token) thank you for the help tho ^^
My paginator is not sent ephemerally along with await ctx.defer(), is it normal behavior?
ctx.defer() and a paginator?
OK forgot there is ephemeral to defer too
yeah
What do you do when the slash command doesn't update?
Wait, or just use @slash_command(guild_ids=GUILDS) and GUILDS is a list of Guild ids
I already had that so ig I'll just wait?
that ephemeral won't work, gonna open a thread
(Nvm just ask someone cause I'm not sure anyway)
What's the other method of adding options aside from decorators? Something like:
async def poll(self, itrc, \
choice1: discord.option(autocomplete = getframes, required = True), \
choice2: discord.option(autocomplete = getframes, required = True), \
choice3: discord.option(autocomplete = getframes, required = True)):
that's close but
- should be
discord.Option - the first positional argument of
Optionis the type
So discord.Option(str, autocomplete = getframes, required = True)?
Thanks
I only added it cause to make it consistent
if something's default it's already consistent 🙂
Consistent look I mean
Is it possible to have variable default value or is it always constant?
...?
being whatever you want
option: discord.Option(str) = "default" also works
So it also accepts a function?
assuming it returns a value, i guess...?
I see. Thanks
Wait, do I have to keep the bot running until the slash command updates?
typically you restart to update slash commands
I did that for 4 times now
what pycord version are you on?
I did, now it's missing. I guess it's on Discord again
you could start a thread with your code if it happens too often
General Python question. What's a good way to chain or statements to get something that isn't None (even (especially) if it's 0)?
result = a.get('a') or a.get('b') or a.get('c')
If a is None, b is 0 and c is None, you're still going to get None
I can't cast them to str, because then a would just return literal 'None'
I guess I can add all the values to a list and use next() to pull the first non-None, if it exists. 🤷♂️
resultlist = [a.get('a'), a.get('b'), a.get('c')]
result = next((item for item in resultlist if item is not None), None)
Hey!! How do I receive the interactions on the messages sent before the bot restart?
Message Events are only dispatched by Discord once the client is connected. As a result, that is not possible, but you can fetch the channel history to see past messages.
I think you don't need ( , None). 
You do if all items are None; you'd get a StopIteration otherwise. Would rather set default than screw with exception handling
True, if that can happen in your case. I didn't consider it.
any?
No, it would give False if None and 0 are mixed.
kinda messy but py any([a.get(x) for x in ['a', 'b', 'c']])
oh wait
i suppose i misunderstood
It wasn't clear. They want to differentiate 0 and None.
regardless the answer is probably list comprehension
Without using next? 
Surprised it's that unclear. I am searching a number of dict items and just want to find the first non-None item, including 0 (which is otherwise false-y)
if you don't want it to deal with falsey then you want is not None
Indeed. Which I did here.
As always, just wanted it as terse as possible. >.>
Now I forgot what I needed to ask when I came here. 
Oh, right! Is there a way to validate values for Embeds?
I want to deal with whitespaces that, as far as I know, get removed automatically if there are no other characters.
I couldn't find the docs to check how it actually works on Discord side.
(Unless it's the super-cool zero-length character, which serves as a great hack to get columns)
So what is it that you are actually trying to do, determine if a field title/value has only whitespace?
My final objective is to avoid that the Embed doesn't get send because there is an invalid field due to whitespace.
Thanks! That's good enough. Actually, it's perfect because it also works with Enter.
if notes is not None and not notes.isspace():
embed.add_field(...)
Can I do better than this? 
Sadly this trick is not good for mobile. 
If there's no reason the field would legitimately have leading/trailing space characters, you could always .strip() it. Then you could simplify the test as if notes:
That's probably a better solution. I'll try. 
You already have a thread going...
yeah
I'll probably get a faster solution here so I might as well ask
Just link it then. Same result, less space.
#1027467757945630770
So, the previous solution ended up being better because I don't need to modify the string. I've shortened it a little but it's basically the same.
if notes and not notes.isspace():
embed.add_field(...)
use the u200b thing instead
one sec
I don't think that's good. I need all kind of whitespace to be checked.
oh ok
raised an error: AttributeError: 'Verification' object has no attribute 'Verification_slash' why am i getting this error?
class Verification(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.bot.application_command(name="startverify", cls=discord.SlashCommand)(self.Verification_slash)
verification = discord.Embed(title="Get Verified!", description="Click the button below to get verified and be able to access the entire server!")
class Verify(discord.ui.View):
@discord.ui.button(label="Verify Me", style=discord.ButtonStyle.primary, emoji="🤝")
async def button_callback(self, button, interaction):
@commands.command(name="startverify", description="Start The Verification Progress")
async def startverify(self, ctx):
ctx.respond(embed = verification, view=Verify)
def setup(bot):
bot.add_cog(Verification(bot))```
```py
directories = ["./Fun Commands", "./Utility Commands","./Embeds"]
for directory in directories:
for filename in os.listdir(directory):
if filename.endswith(".py"):
bot.load_extension(f"{directory[2:]}.{filename[:-3]}")```
I cant see why, I've googled it, looked around my code, checked docs
(i used to code bots but havent in a while, so im rusty)
What is this supposed to do there? 
self.bot.application_command(name="startverify", cls=discord.SlashCommand)(self.Verification_slash)
Why is if message.guild.id == MY_SERVER_ID: raising an AttributeError: 'NoneType' object has no attribute 'id'
It seems like you don't have intents for that. 
I have all intents enabled :)
I’m thinking it’s because someone tried to DM my bot but I’m not 100% sure..
I see. It could be. 
Hi all. I am newb and trying to write a background task but this task can not send anything to a particular channel. I am afraid that I might miss some Intents settings so I included the screenshots of that part too. I am using py-cord 2.2.0. I have spent a lot of times trying to get this work but nothing seems to work for me. Thank you in advance.
I'm not sure what's the problem but you can try the following.
- Make sure the channel ID you are passing to
get_channel()is correct. - Do that operation inside
on_ready()and use the returned value asself.channel.
Thank you for responding. I am very sure that I use the correct channel ID. But let me try your suggestion for 2.
I was basing it off the example from pycord
I tried 2 and it still failed
I have literally looked at all the search results using google for this issue and I could not fix this
I just basically copy the channel ID there and use it directly in the codes
My bot could respond to commands in this channel so ....
you also need guild intents for guild channels
Thanks. I just added guilds=True and now it works. Damn it. I spent 1/2 day and could not figure this out. Thanks once again
Try using different examples then.
https://guide.pycord.dev/popular-topics/cogs/
https://guide.pycord.dev/interactions/ui-components/dropdowns
Hi!
I don't know if it's me who doesn't understand but I can't seem to add a link button.
Do you have a little tutorial or something to help me?
you just use view.add_item with discord.ui.Button
if you're trying to use the decorator it won't work
well the button is fine but you kinda missed the point with view
how do you normally define and send a view?
or have you not used them before
await ctx.respond(embed=embed, view=EditEmbedTools())
ah so you subclass
The idea is to add this button to a list of buttons
But I confess that I don't understand the link
well typically you'd do view = discord.ui.View(), then view.add_item(...)
if it's a subclassed view, inside __init__ you could also do self.add_item
Huuuh 
if you still don't understand, think of it like embeds
(i hope you've used them at least)
Yes, I'd like to add it here, for the moment I've looked at the old messages, it talks about class, super.init etc
you should add it inside of the subclass still...
yeah you basically want to override the default __init__ function and use super().__init__()
you can then re-order the components with
https://docs.pycord.dev/en/master/api.html#discord.ui.View.remove_item
and
https://docs.pycord.dev/en/master/api.html#discord.ui.View.add_item
Here's the link example.
i'd say refer to this example
what is your current code?
I imagine that it wouldn't be an issue.
well
since there is only one button on the other row
yeah, so just specifying the row is enough since calling super().__init__ will initialize the rest.
you didn't need to copy the whole class, the point was to use the __init__ functions inside your existing class
Google is a view, not an Item.
is that what you wanted?
