#Basic Pycord Help
1 messages Β· Page 9 of 1
alright
I think it's the code block one
but the docs said
A dictionary of transformed arguments that were passed into the command. Similar to args, if this is accessed in the on_command_error() event then this dict could be incomplete.
A dict isnt indexed with ints
yes i know
but the dict i got is empty
if this is accessed in the on_command_error() event then this dict could be incomplete.
so how to fix it
or i have to set a global variable
What's a good way to make a settings menu? Making them parameters of a command seems like a simple solution given a user is likely to configure all of their settings at once, but also found out it has a limit. Can you use paginator and have setting buttons on those pages? Or do you realistically have to just make multiple commands for different settings?
I want to add two buttons with this style in the end
@bot.slash_command(name="help", description="Get help for the imagine command")
async def imagine_2_help(ctx):
embed = discord.Embed(title="imagine Command Help", description="Generate images with Diffusion models.", color=discord.Color.default())
embed.add_field(name="Options:", value="Here are the available options for the imagine commands:", inline=False)
embed.add_field(name="/imagine model", value="Choose a model for image generation.", inline=True)
embed.add_field(name="/imagine prompt", value="Enter a prompt to describe the image.", inline=True)
embed.add_field(name="/imagine negative_prompt", value="Enter a negative prompt (unwanted items).", inline=True)
embed.add_field(name="/imagine upscale", value="Choose whether to upscale the image.", inline=True)
embed.add_field(name="/imagine ratio", value="Choose the aspect ratio of the image (square, landscape, portrait).", inline=True)
embed.add_field(name="/imagine seed", value="Specify a seed for randomization.", inline=True)
embed.add_field(name="/imagine steps", value="Choose the number of steps for image generation.", inline=True)
embed.add_field(name="/imagine cfg_scale", value="Choose the number of CFG scaling.", inline=True)
await ctx.respond(embed=embed)```
That's my command
Here's the link example.
May I ask for a help
@bot.command(description="create a game room")
async def notavailable(ctx, room_name:str):
# variable
guild = ctx.guild
# Embed
embed = discord.Embed(
title="Welcome",
description="This channel is currently available for use",
color=discord.Color.dark_purple(),
)
embed.set_footer(text="You can use this the button below to close the channel")
# channel
channel = await guild.create_text_channel(room_name)
async def deletechannel(ctx):
channel = bot.get_channel(room_name)
if channel:
await channel.delete()
await ctx.send(f"Channel {channel.name} has been deleted.")
else:
await ctx.send("Channel not found.")
# button
button = Button(label="Close Channel", style=discord.ButtonStyle.blurple,emoji="")
delete_channel = deletechannel()
async def close_channel(interaction):
await interaction.response.send_message("Channel will be delete soon .......")
await interaction.followup.delete_channel()
button.callback = close_channel
view = View()
view.add_item(button)
# print out
await channel.send(embed=embed,view=view)
#await channel.send(f"{member2.mention} {member3.mention} {member4.mention} {member5.mention}, this channel is now available for you to join.")
await ctx.respond(f"Text channel: <#{channel}> has been create")
I don't know how to let user to delete the channel when they click the button
My application commands arent syncing and showing up in my bot
.tag slashnoshow
Application Commands Not Showing Up?
- Uninstall libraries that conflict with the
discordnamespace (e.g.discord.py). - Invite your bot with the
application.commandsscope. - Load cogs before
bot.run()(e.g. not inon_ready). - Do not override
on_connect. - Update to the newest version of
py-cord(see?tag install). - Turn off
User Settings > Accessibility > Chat Input > Use legacy chat input. - Share your code and errors.
Is it possible to connect to one bot through 2 code bases?
Like I have pyhelp command in python and rusthelp in rust, so if I use pyhelp it will launch python and rust if rusthelp
and how lol?
That's not what I want
I wanna connect to the same bot from different code bases/devices
And listen for different events
I wanna have dynamic (per guild) functions
Something like: do_that in guild 12... which will launch rust code and do_else in guild 13... which will launch C# code
how do you access a guild specific display name?
for member in ctx.guild.members:
if participant1 == (how do I access the members display name T-T):
print(x)
.tag pomelo
Before Pomelo-
member.name -> username
member.nick -> guild nick name
member.display_name -> member.nick OR member.name
After Pomelo-
member.name -> username
member.global_name -> global display name (global nick name)
member.nick -> guild nick name
member.display_name -> member.nick OR member.global_name OR member.name
Ignoring exception in on_message
Traceback (most recent call last):
File "/home/runner/Inferno-Bot-Quaker87/venv/lib/python3.10/site-packages/discord/client.py", line 378, in _run_event
await coro(*args, **kwargs)
File "main.py", line 206, in on_message
if member.global_name == participant1:
AttributeError: 'Member' object has no attribute 'global_name'
is it cuz I havent updated it?
not sure if replit auto-updates
You need to either be on the master branch for it to work or use "py-cord-dev" instead
?tag install
1. Uninstall discord.py or any other forks of discord.py you might have with the namespace discord.
python -m pip uninstall discord.py discord -y
2a. Install py-cord
python -m pip install py-cord
2b. Update py-cord
python pip install -U py-cord
Installing other builds:
Note: You need to have git installed. Use ?tag git to find out how to install git.
Updating the module to master branch (unstable):
pip install -U git+https://github.com/Pycord-Development/pycord
and if you want to use the dev version, just uninstall py-cord and install py-cord-dev
so I should
alright
so
in replit
command prompt
how do I
first uninstall pycord
:xd:
You can just click "shell" in replit and there run the commands to uninstall and then install it
whats the command to uninstall it π
?tag uninstall
"pip uninstall py-cord"
ayt ty
No tag uninstall found.
how do i create a channel with the bot
.rtfm create_text_channel
ty
i have a context menu command to warn a user, I managed to make the interaction.response send a modal that has a discord.ui.InputText. Can I use the value of the input text object in the context menu command?
Thank you, I'll check that out.
guys what is wrong with my code
@bot.slash_command(description="Cria um canal de texto")
@commands.has_permissions(manage_channels=True)
async def create(ctx, nome : discord.Option(str, description="Nome do canal", required=True), tipo : discord.Option(description="Selecione o tipo de canal", choices=tipos_canal, required=True), cargo : Option(discord.Role, description="Selecione o cargo que terΓ‘ acesso Γ esse canal", required=False), membro : Option(discord.Member, description="Selecione o membro que terΓ‘ acesso Γ esse canal", required=False)):
overwrite_cargo = {ctx.guild.default_role: discord.PermissionOverwrite(view_channel=False)}
overwrite_membro = {ctx.guild.default_role: discord.PermissionOverwrite(view_channel=False)}
if cargo:
role = discord.utils.get(ctx.guild.roles, id=cargo)
if role:
overwrite_cargo[role] = discord.PermissionOverwrite(view_channel=True)
if membro:
member = ctx.guild.get_member(membro)
if member:
overwrite_membro[member] = discord.PermissionOverwrite(view_channel=True)
overwrites = []
if tipo == "texto":
overwrites.append(overwrite_cargo)
overwrites.append(overwrite_membro)
if cargo:
overwrites.append(overwrite_cargo)
if membro:
overwrites.append(overwrite_membro)
await ctx.guild.create_text_channel(name=nome, overwrites=overwrites)
elif tipo == "voz":
overwrites.append(overwrite_cargo)
overwrites.append(overwrite_membro)
if cargo:
overwrites.append(overwrite_cargo)
if membro:
overwrites.append(overwrite_membro)
await ctx.guild.create_voice_channel(name=nome, overwrites=overwrites)
await ctx.respond("canal criado")
it says overwrites parameter expects a dict.
Hey, little stuck with ephernoumal commands
@settingsUser.command(name='token', description='Generate token for Rimuru Web experience.')
@commands.cooldown(1, 99, BucketType.user)
async def tokenmake(ctx):
. . .
await ctx.respond(
f"Your new token is: `{token}`. Please keep this token private and do not share it with another, as it allows people to do activity on the behalf of your Discord account for the Rimuru Web Dashboard.\n\nWhatever your token was before - if you had one - has been deleted. \n**What is this token used for?** This token is used to access some parts of Rimuru\'s services such as its Chrome extensions.",
ephemeral=True)
It works on my personal laptop but not on my machine when I'm hosting the bot
I have no idea why
?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.
What's expected = message gets sent
What is happening = message isn't getting sent
not really much else I can say 
This is a slash command right?
yup
do you have an on_application_command_error handler?
I do, let me check
It seems its slow to send messages so it doesn't respond quickly enough
resulting in it not being sent which is odd
Try deferring
ah yea, hang on how do you defer again?
await ctx.defer()
in this case, you would want to pass ephemeral as True to defer().
Got it, will do now
Thanks lets try that
The thinking comes through, but the final message isn't sending...
The code inbetween is fine and I've tested it
Have you tried using a debugger
I'm gonna be honest I've never used a debugger in my entire life π
I've tried to but just couldn't figure out how
π
I use PyCharm Professional- yea I know
it will basically show you where the code is "stuck"
I know that's the principal of it but just got along by using print statements.....which is bad but I just don't know how to use the debugger
Do you mark the side as red and wait till it stops at that point?
Just not too sure π
yes
and you run it in debug mode
Nah the one I'm running locally is on the testing bot
I've tried deploying this code so many times, it works fine on my own laptop but not the production host
which is why.....I'm doing it like this π
I don't normally but it's such a pain in the ass I've got no choice
but how do I run this in debugger mode....when my laptop is fine
its on the production machine that it doesnt like it
thing is there isn't an error at all
Wait nevermind now it is working! Seems like the defer() fixed it
its a little slow but that's fine, this token generation is only one time, its fine if it takes a bit longer
thanks for the help! :)
me when remote is slower local
I think it's some packages I've installed....and I'm managing a lot of stuff in memory
instead of using redis
I made this code such a while back, when it gets more demand I'll be forced to change it but for now it should be ok
In this context menus user_command that deletes a warning from an aiosqlite db, I'm passing async def removewarning(self, interaction:discord.Interaction, warning_id:int, user_id:int) -> int: but I'm getting ClientException: Callback for Remove Warning command has too many parameters. Any ideas?
is self supposed to be there?
it is inside a cog so i guess.
context menus only take one argument (other than self and interaction): user
Just a quick question, so channel.edit apparently doesn't raise an exception if it hits a ratelimit. Are there ways to check for ratelimit on specific routes, so we can tell the users the bot is getting ratelimited?
what class used for handle 403 forbidden in on_command_error?
i use
if isinstance(error,commands.BotMissingPermissions):
didn't work
How to creat select menus
Learn all about implementing Select Menus or Dropdowns in your Discord Bot with Pycord.
wdym??
how can you write the name of the user that used the command? Something like f'hello {ctx.user}'?
do you know where I can find how to retrieve all ctx information in the documentation?
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...
Assuming you're on a slash command
I had this weird issue with retrieving names, so what I want is the user nick that shows up in a server.
But to get that you gotta do many things, so the easiest way would be to do ctx.author.nick but if the user doesn't have a nick and gives None you then do ctx.author.global_name which should give you the name but what if even that gives none?? What do I do then? This happens when the user didn't get their own username after the username update and has the normal Rad#1331 username
?tag pomelo
Before Pomelo-
member.name -> username
member.nick -> guild nick name
member.display_name -> member.nick OR member.name
After Pomelo-
member.name -> username
member.global_name -> global display name (global nick name)
member.nick -> guild nick name
member.display_name -> member.nick OR member.global_name OR member.name
ok ty
what?
if ctx.author.nick == None:
if ctx.author.global_name == None:
await self.bot.db.execute(f'UPDATE gamble SET player_name = $1 WHERE player_id = $2', ctx.author.name, ctx.author.id)
else:
await self.bot.db.execute(f'UPDATE gamble SET player_name = $1 WHERE player_id = $2', ctx.author.global_name, ctx.author.id)
else:
await self.bot.db.execute(f'UPDATE gamble SET player_name = $1 WHERE player_id = $2', ctx.author.nick, ctx.author.id)
uh wait
one sec
No I don't want that
like I had this user
who had no nick name
in the server
and hadn't picked his own username after the username update
so had the legacy name
And so when I did author.global_name I got none
so does author.name work then for users like that?
How to record a voice chat?
Thank you! May you check my code? I created a topic some minutes ago
Hello, I made a slash_command command I specified the description but it's not showing when I enter /cmd
@slash_command()
@option("name", description = "This is a cmd", choices = ["hi", "hello"], required = True)
async def cmd(self, ctx: ApplicationContext, name: str):
await ctx.respond(name)```
slash_command is imported from discord.ext.commands and option is imported from discord
yup it's working it's just not showing the description
will it error if it has the same name with command name?
I would try it without the same name everywhere
Okay I replaced the name of cmd in the option but still not showing description
you're giving the description to the option, not the command
oh my bad
- @slash_command()
+ @slash_command(description = "Hello, Discord!")
@option("name", description = "This is a cmd", choices = ["hi", "hello"], required = True)
async def cmd(self, ctx: ApplicationContext, name: str):
await ctx.respond(name)
Okay I got it thanks, but to clarify where would the description in option be showed?
when you try to input the option it will show
"Tag name" would be the description there
Oh okay thank you that got me confused
guild3 = 1150140535030431854
guild = bot.get_guild(guild3)
member = guild.get_member(user_id)
if int(message_data[user_id]) >= int(messages_daily) * 0.75:
await member.add_roles(rewardid_relatively_active)
await member.add_roles(rewardid_relatively_active)
AttributeError: 'NoneType' object has no attribute 'add_roles'
?tag get_x
Any function that starts with get_ in Py-cord is retrieving the related object from your bots cache. If the object is not in the bots cache the get_ method will return None. Because of this behavior you should check if the get_x method is None and if it is use the fetch_x method.
Why Is Using fetch_ Without Using get_ First Bad?
The fetch_ method makes a call to the discord API. This API call is unneeded if you already have the information. It will also make your command take longer because it will have to send and than wait for a response from the discord API. It will also contribute to the discord APIs global rate limit of 50 requests per second.
What Is Cache?
The cache is a temporary storage inside your bot. It holds many objects from members to messages. When you restart your bot the cache will be empty. When the cache is full it will delete older objects to make space for the new objects.
aight
AttributeError: 'coroutine' object has no attribute 'fetch_member'
/home/zeyad/.local/lib/python3.10/site-packages/discord/client.py:383: RuntimeWarning: coroutine 'Client.fetch_guild' was never awaited
Did you read the error?
i did but i cant await it
?
ion understand
wait
im dumb
af
i put await in the wrong place lmfao
i think it works
@little cobalt
in add_roles
await req(guild_id, user_id, role.id, reason=reason)
AttributeError: 'str' object has no attribute 'id'
member is fetched from guild. and role is just the role id!
You really should start to read the errors
k whenu say that i actually figure out whats wrong
π
nvm
@little cobalt the role id is just a int...
how tf can i put it there
i turned it into a int again from a string it says int has no attribute with id
change role.id to role_id?
thats from the source not my source
like thats from the library
not my code
File "/home/zeyad/.local/lib/python3.10/site-packages/discord/member.py", line 1007, in add_roles
await req(guild_id, user_id, role.id, reason=reason)
see
full error:
File "/home/zeyad/Desktop/Comet Chat Tracker/chattracker.py", line 84, in on_message
await member.add_roles(int(rewardid_relatively_active))
File "/home/zeyad/.local/lib/python3.10/site-packages/discord/member.py", line 1007, in add_roles
await req(guild_id, user_id, role.id, reason=reason)
AttributeError: 'int' object has no attribute 'id'
await member.add_roles(guild.get_role(int(rewardid_relatively_active)))
fetch_role
i think
will work better
cuz @little cobalt said always use fetch
did you not read this? ^
I never sayed anything
i semi read it quick;y π but i got the point that fetch is always better than get
that's not the point at all
nvm then
but you need to get the role (with get or fetch) and pass the role object to add_roles
How to make it possible to mention in the bot profile /start
?tag slashcommandmention
</full name:ID>
You can mention a slash command like that ^
I'm sorry, maybe I did something wrong π
As I understand it, I should paste this into the botβs profile, and then full or name replace it with what I need?
is there a way to set position of buttons
like i have some defined inside init and some outside
Yeah. You need to put the slash command's name and id in it, so if the command would be "help" for example you could do like this: </help:123456> and then paste it in to the about me. Replace the numbers with the slash command's id
Thanks a lot
await interaction.response.send_dm("hi")``` how i can send to pm after used interaction
interaction.user.send
``` need
To install a user, you then need to specify what a user is in the code
ctx.author and interaction.user
When I have a response from an Interaction and I edit this response with an Button in another view class, can I still get the response with interaction.original_response()? or what do I need to do, to get the original message
thanks for nothing
this:
Ignoring exception in view <Paginator timeout=180.0 children=4> for item <Select type=<ComponentType.string_select: 3> placeholder='Filter' min_values=1 max_values=1 options=[<SelectOption label='Alle' value='all' description=None emoji=None default=False>, <SelectOption label='Sturm' value='sturm' description=None emoji=None default=False>, <SelectOption label='Mittelfeld' value='mittelfeld' description=None emoji=None default=False>, <SelectOption label='Abwehr' value='abwehr' description=None emoji=None default=False>, <SelectOption label='Torwart' value='torwart' description=None emoji=None default=False>] channel_types=[] disabled=False>:
Traceback (most recent call last):
File "C:\Users\nuc\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ui\view.py", line 421, in _scheduled_task
await item.callback(interaction)
File "C:\Users\nuc\Documents\football-minigame\cogs\management.py", line 840, in select_filter_callback
await paginator.edit(await interaction.original_response())
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\nuc\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\interactions.py", line 348, in original_response
data = await adapter.get_original_interaction_response(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\nuc\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\webhook\async_.py", line 220, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook```
I think so
paginator = Paginator(pages=pages, custom_view=TradePlayerSelectionView(self.players), author_check=False)
paginator.remove_button("first")
paginator.remove_button("last")
await paginator.edit(interaction.message)
but I don't want a new message
I want to edit the current message with a paginator to a new paginator
.rtfm ext.pages.Paginator.edit
Should work to
.rtfm ext.pages.Paginator.edit
i know this isnt directly py-cord related, but does anyone have a clue why tf
metadata = response.headers.get('Last-Modified')
timestamp = int(datetime.datetime.strptime(metadata, "%a, %d %b %Y %H:%M:%S %Z").timestamp())```
just errors
ValueError: time data 'Fri, 08 Sep 2023 11:41:42 GMT' does not match format '%a, %d %b %Y %H:%M:%S %Z'
one question. I have a button that sends a new message also with buttons and deletes the old message like this:
response = await interaction.original_response()
await response.delete()```
but when I use the same technique on the message with the new buttons it deletes the new(third) message and not the second. How can I solve this problem?
yes
I get a <property object at 0x00000162D74F4BD0> so I first need to fetch the message before deleting, right?
is None
self.message is None
but how can I pass the message object to another class?
Pass it to the class constructor?
generous people of pycord, any idea why
topic = stage_channel.topic```
is returning NoneType? I have a stage instance running
the command is invoked during the instance btw
?tag get_x
Any function that starts with get_ in Py-cord is retrieving the related object from your bots cache. If the object is not in the bots cache the get_ method will return None. Because of this behavior you should check if the get_x method is None and if it is use the fetch_x method.
Why Is Using fetch_ Without Using get_ First Bad?
The fetch_ method makes a call to the discord API. This API call is unneeded if you already have the information. It will also make your command take longer because it will have to send and than wait for a response from the discord API. It will also contribute to the discord APIs global rate limit of 50 requests per second.
What Is Cache?
The cache is a temporary storage inside your bot. It holds many objects from members to messages. When you restart your bot the cache will be empty. When the cache is full it will delete older objects to make space for the new objects.
Thank you
guys how do i send a welcome message whenever someone join my server?
ty
its not working
do you have intents?
ye
which one?
also added to your bot?
what do u mean
intents = discord.Intents.default()
bot = discord.Bot(intents=intents)
and what is the error?
Did you add prints to your code to see what's running?
Did you even try to debug it
Hello is it suitable to ask I question Iβm stuck up with my code
@bot.command(name='editchannel', description='edit the channel name')
async def editchannel(ctx, channel:discord.Option(discord.abc.GuildChannel, description=None), newname:discord.Option(str), carnum:discord.Option(int)):
oldname = channel.name
newname = f"{carnum} Channel"
await channel.edit(name=newname)
await ctx.send(f'Channel #{oldname} is now #{newname}')
I am trying to let a user edit a channel name
but they don't have to write the full name instead of writing a number before the channel
and its don't help The comand is not working and my terminal doesn't print out any error issue
please help me
I know that, but I Set the View (with the class constructor) before sending the message. So the message is None
so no one help :<
There's a rate limit on editing channel names, maximum of twice in 10 minutes
Then just give it the attribute after you send the message
Can someone recommend a tutorial/video/text/something that teaches packaging?
like so:
view = MyView(message)
view.message = await ctx.respond(..., view=view)
message = view.massage
?
Already had that open but thanks for responding
Ctx.respond doesn't return a message object
paginator = Paginator(pages=pages, author_check=False)
paginator.custom_view = TradePlayerSelectionView(self.players, message)
paginator.remove_button("first")
paginator.remove_button("last")
await paginator.respond(interaction, ephemeral=True)
this is the piece of the code and the "message" attribute at the paginator.custom_view = TradePlayerSelectionView(self.players, message) line is None so I first need to send the paginator and then pass the paginator.custom_view.message attribute to the class
how did i not see that? Thanks! π
other question:
why is mess "None"?
em = discord.Embed(title='Spielerliste wird Generiert...' , color=discord.Color.red())
mess = await interaction.response.edit_message(embed=em, view=None)
print(mess)
Because the method doesn't return anything.
hmm ok
what is this? always get this when connecting wavelink
WARNING:discord.http:We are being rate limited. Retrying in 5.38 seconds. Handled under the bucket
what is hidden=True?
hidden command from help
Hi! How do I get rid of this warning in VS Code? 
Is that your own folder and file?
Yes. Now it's gone. I opened the whole project rather than the file alone. π₯³
Currently Pylance is also really buggy
I see. I don't code often. I didn't have this issue the last time, I believe.
I had it many times that I was not able to import stuff from other locations
hi! i can't find what's wrong
i surfed internet and find a article that says 'turn on priviliged gateway intents' so... i turn on it, but it's still wrong
and if i delete the line 5(it's problem) in the code, it's operating
like this. (private DM)
BUT the bot doesn't work in the test server....
(no answer in test server)
what's wrong???
oh my
hiding token and re-upload...
what's pycord?
oh i already read it ;-;
can u give more concrete solution..?
i already tried to read the article as hard as i can read (cause of my Eng skill.. i can't find the solution..
of
oh
i solved the problem
thanks!!!
and turned on all of the three :3
classes = discord.SlashCommandGroup("classes", "Classes XP management")
@classes.command(name="endclass", description="Locks Class Channel and prints the list of atendees")
async def attendance(self, interaction: discord.Interaction):
stage_channel_instance = await self.bot.fetch_stage_instance(1150789088442589224)
stage_channel = self.bot.get_channel(1150789088442589224)
verified_role = interaction.guild.get_role(verified_role_id)
topic = stage_channel_instance.topic
if verified_role:
for member in stage_channel.listeners:
await member.move_to(None) #boot listeners only out
await stage_channel.set_permissions(verified_role, view_channel=True, connect=False)
log_channel = interaction.guild.get_channel(self.classes_log_channel_id)
if log_channel:
mentions = [interaction.guild.get_member(user_id).mention for user_id in self.users_with_xp]
timestamp = datetime.date.today()
embed=discord.Embed(title="Members:", description=f"Members who have joined the class:{' '.join(mentions)}", color=0x00a3d7)
embed.set_author(name=f"Attendance List for {topic}", icon_url=self.bot.user.default_avatar.url)
embed.set_footer(text=f"This list is for the class held on {timestamp}")
await log_channel.send(embed=embed)
await interaction.response.defer()
await asyncio.sleep(5)
await interaction.followup.send("List Embedded, channel locked.")```
The command executes but im getting a response error, and console is returning `Application Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction`
any ideas what could be the issue?
full traceback
File "/Users/ramo/testicle/testicle/lib/python3.11/site-packages/discord/bot.py", line 1133, in invoke_application_command
await ctx.command.invoke(ctx)
File "/Users/ramo/testicle/testicle/lib/python3.11/site-packages/discord/commands/core.py", line 381, in invoke
await injected(ctx)
File "/Users/ramo/testicle/testicle/lib/python3.11/site-packages/discord/commands/core.py", line 131, in wrapped
ret = await coro(arg)
^^^^^^^^^^^^^^^
File "/Users/ramo/testicle/testicle/lib/python3.11/site-packages/discord/commands/core.py", line 1363, in _invoke
await command.invoke(ctx)
File "/Users/ramo/testicle/testicle/lib/python3.11/site-packages/discord/commands/core.py", line 381, in invoke
await injected(ctx)
File "/Users/ramo/testicle/testicle/lib/python3.11/site-packages/discord/commands/core.py", line 139, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction```
i apologize for the bot's name in advance.
In Pycord, Application Command callbacks take an ApplicationContext object, not an Interaction
You should also place the defer first
hi, quick question, how to fetch the role @everyone pls? for PermissionOverwrite
ty
@commands.command(hidden=True)
async def join(self, ctx):
# initialize node
...
await ctx.author.voice.channel.connect(cls=wavelink.Player)
@commands.command(hidden=True)
async def play(self, ctx, *, track: str):
vc = wavelink.Player = ctx.voice_client
tracks = await wavelink.YouTubeTrack.search(track)
if not tracks:
await ctx.send("no track found")
else:
await vc.play(tracks[0])
await ctx.send(f"Now playing: {tracks[0]}")
why no music played? it said now playing.
btw the wavelink guide on pycord docs is using older version so i follow wavelink docs
for some reason, it doesnt work, and even say AttributeError: 'int' object has no attribute 'id' but when I print the type of ctx.guild, it send <class 'discord.guild.Guild'>
I dont get it tbh
role_everyone = ctx.guild.id
def getOverwrite(role):
return {
role : discord.PermissionOverwrite(**{
"connect": True,
"add_reactions": True,
"add_reactions": True,
"attach_files": True,
"change_nickname": True,
"create_instant_invite": True,
"create_public_threads": True,
"external_emojis": True,
"external_emojis": True,
"external_stickers": True,
"read_messages" : True,
"request_to_speak" : True,
"send_messages" : True,
"send_messages_in_threads" : True,
"send_tts_messages" : True,
"speak" : True,
"stream" : True,
"use_application_commands" : True,
"use_external_emojis" : True,
"use_external_stickers" : True,
"use_slash_commands" : True,
"use_voice_activation" : True,
"view_channel" : True
}), ctx.guild.id: discord.PermissionOverwrite(**{
"view_channel" : False
})
}
for i in range(1,6):
await ctx.guild.create_forum_channel(name=f"π§©γ»Forum",
category=get(ctx.guild.categories, name=f"π·ββγ»οΈtravailγ»βΛ {i}"),
position=0,
overwrites = getOverwrite(role_annee[i-1])
)
why not tho
I only need it there
If u want to get the everyone role you could do this :
ctx.guild.roles[0]
It works
what does this even mean... it's just guild.default_role
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 ...
so effectively, it sent me bullshit
so talking like this isn't necessary
How can we understand the on_error, like it give me this
```2023-09-12 19:52:06 [ERROR] : on_member_join : (<Member id=811635088319447092 name='gersrik' discriminator='0' bot=False nick=None guild=<Guild id=1150129145209176065 name='KR Esport | { 0,034 }' shard_id=0 chunked=True member_count=41>>,) et {}````
how can we understand this
why do you use on_error?
to get all error in a formatted fomat with logging and not a big thing
does its bette to not use the on_error ?
try
async def on_application_command_error(ctx: discord.ApplicationContext, error: discord.DiscordException):
ctx.send(f"An error happened: ```{error}```")
using the name of the command
and not the name of the groupe
does it work ?
why ctx.send?
use ctx.respond for the slash commands
not ctx.send
is it possible for a button in a view to interact with another button? for example, i would like a button to be disabled when it is pressed, and after this, if the second button is pressed, it gets disabled while the first button is re-enabled
I got it
all the messages that are cached
Is it possible to edit the select menus response?
Is it possible to make a command that work with slash and without at the same time? Or I should just dupe the lines and add slash command in one and not in the other ( I hope there is a better way)
You would be looking for bridge :P
.rtfm bridge
discord.ext.bridge.Bot
discord.ext.bridge.Bot.activity
discord.ext.bridge.Bot.add_application_command
discord.ext.bridge.Bot.add_bridge_command
discord.ext.bridge.Bot.add_check
discord.ext.bridge.Bot.add_cog
discord.ext.bridge.Bot.add_command
discord.ext.bridge.Bot.add_listener
discord.ext.bridge.Bot.add_view
discord.ext.bridge.Bot.after_invoke
discord.ext.bridge.Bot.all_commands
discord.ext.bridge.Bot.allowed_mentions
discord.ext.bridge.Bot.application_command
discord.ext.bridge.Bot.application_commands
discord.ext.bridge.Bot.application_flags
discord.ext.bridge.Bot.application_id
discord.ext.bridge.Bot.application_info
discord.ext.bridge.Bot.before_identify_hook
discord.ext.bridge.Bot.before_invoke
discord.ext.bridge.Bot.bridge_command
what happen with my bot
I didn't change anything and when I using my bot all slash command are not work and prefix command printing twice
all my code is ok and terminal didn't reply me any errors when the command does not responds
bridge_command
maybe duplicate execution/run
that happens to me sometimes, when I accidentally run the bot with IDE terminal and run again by opening the .py file
I didn't run on both file I have been rollback and test the bot again its still the same
and its still does have any errors
well then then idk
u talking to me?
.
Your error is not even close to mine π
thats because I always lazy to clone a new file and test something in python in my bot inventory
why are you guys getting that kind of error π
I don't know
Im very headache with my errors now
its working fine this morning and my code all rip right now
prefix command: printing twice
slash command: no responds
but codes are fine
How many slash_commands do you have?
i want the roles to be mentioned by autocomplete but it only shows like this:
That's not how it works
11
I have been fixed prefix command
but slash command still didn't responds
wym
it still work in the morning
aren't thats a joke
Autocomplete cant randomly mention stuff
Youd have to parse the names
i did all around but i just want the simple @ list to autocomplete a role for a command xD sure i can use the role names and parse them to the role afterwards but ppl will then ask why the heck i cant use the @Rolename and see all the roles with colors and so on like i normally would
Hello!
Is it possible to call the guild event creation window through a bot?
So far I have learned that ScheduledEvent is responsible for this.
For example, when you click a button in a message, an event creation window appears, just like with modular dialogs.
They implement human choice of date and time)
How to extract information from the game server such as name, character information, and display it on Discord.
that are a whole lot of questions π which game, which database, does the game even have access to api calls?
Quick question, can anyone give me a link to docs or any info about automod?
I saw the automod badge on one of the bots, googled what is it and there's a quote:
π‘ If your app has at least 100 rules on AutoMod across all servers, you will see this shiny new badge on its profile!
And now I'm wondering what are those rules, how do they get setup and what does my bot need in order to receive them
I, myself, could only find this documentation: https://discord.com/developers/docs/resources/auto-moderation
But It's just API for it
When it comes to StageInstances, discord.on_stage_instance_delete will trigger when an instance is ended by the stage moderators, is my understanding correct or is there something I'm missing?
because py @commands.Cog.listener() async def on_stage_instance_delete(self, stage_instance: discord.StageInstance): print(f"Ended {stage_instance.id}")
is printing nothing on my console
How can I make it so certain slash commands don't show up for specific users?
like they don't even get it in the menu when they type slash
from Integrations in the server settings
this can be done in a script right?
like adding a decorator to a slash command function
not with that one ;3
I'm mistaken then.
@fiery stratus if you want to hide a slash command you should use discord.default_permissions()
has_permissions is kinda the hard coded permission check while you can still change it with discord.default_permissions
@little cobalt I'm sorry for the ping, but do you have any insight on #1132206148309749830 message?
Discord is the easiest way to communicate over voice, video, and text. Chat, hang out, and stay close with your friends and communities.
Thank you Squid and Darp
Can you please send any example of this?
thats exactly what im needing rn
nvm i found it
Here's the slash perms example.
Is it possible/feasible to autocomplete suggest emojis?
Including default Discord emotes and custom emoji?
no, since custom emojis don't show
Even if it's just the names that'd be fine I guess
i suppose then
But since there are so many emojis, can all of them really fit..?
discord only renders the first 25, but the system does work
ooh.. yk what there's no point to doing it the way i imagined/thought of
simply typing a colon into a command argument shows the list
I made this function to load my cogs, Im facing an issue though
for filename in os.listdir(r".\cogs"):
if filename.endswith('.py'):
bot.load_extension(f'cogs.{filename[:-3]}')
as you can see the function loads the cogs inside of the cogs folder only. My issue is that most of my cogs are in folders that are inside the cogs folder, which renders them to not load. how would i edit this function to load the cogs inside folders that are nested into the cogs folder
this is my code
Remove all the stuff and create one line with bot.load_extension("cogs" requirsive=True)
I dont really if I wrote it right or not
one question, how can i make a livetime counter in seconds, my number is 158401 and i did a for and a embed edit after 1 second, that worked great the first minutes, then started to slow down and then completly stopped working
158501 s is maybe to big
i know i want to know if maybe the is a way or just rip
use a timestamp
Idk what that is, sorry
well, what probably will be more efective LMAO
alr
Alr, thx
Is it possible for my discord bot to show a video? Like, live sharing a video in a voice channel?
yea i figured that out π¦
is there like. any other way around that?
like an embed with image changing like every 5s?
i just want a lil screenshare of the machine the bot is hosted on. i did the screenshot thing. i was thinking if a video was possible or not
is this feasible? editing an image in the embed? at slow-ish intervals?
How would i go about accessing a user's connections? I want to verify that someone has a public steam account connected.
can i use a local .png in embeds?
?tag localfile
f = discord.File("some_file_path", filename="image.png")
e = discord.Embed()
e.set_image(url="attachment://image.png")
await messagable.send(file=f, embed=e)```
this sends the file but it doesnt put it in the embed, it's before it.
so im doing this: ``` image=discord.File(f'{dungeon}.png')
embed = discord.Embed(
title="My Amazing Embed",
description="Embeds are super easy, barely an inconvenience.",
color=discord.Colour.blurple(),
)
embed.set_image(url=f'attachment://{dungeon}.png')``` and responding like so ```await ctx.respond(f'you picked {dungeon} !! {level} !! so awsome',file=image, embed=embed)``` but what happens is i get:
<image>
<embed>
is it still happening if you add the filename=""?
missing 1 required positional argument: 'fp' which im guessing is the filepath
hmm ok, new problem discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: PermissionError: [Errno 13] Permission denied: from image=discord.File(os.getcwd(),filename=f'{dungeon}.png') as im getting the image from the same folder as my bot, im also running the terminal as admin too
okay thats fine, so why is my image apearing before the embed isntead of inside it
are the URL embeds size dependant? for instance if the image is to large it wont try and resize it
When running this code:
@discord.message_command(name="Open a ticket")
async def Open_a_ticket(self, message):
print(message.author.id)
I get this error:
discord.errors.ClientException: Callback for Open a ticket command is missing "message" parameter.
I am out of ideas
can anyone explain why i am getting this warning? I am trying to access a list of threads in a channel:
channel = self.bot.get_channel(1150122572294410441)
...
threads.update(channel.threads)
async for thread in channel.archived_threads():
threads.add(thread)
pycharm tells me "Cannot find reference 'threads' in 'GuildChannel | Thread | PrivateChannel | None"
I am pretty sure this used to work though, so I'm a bit confused
its probably just because pycharm doesn't know if it is a textchannel
does the code work?
its difficult for me to say right now as the website who's api i'm calling when i make new threads is being ddos'd right now lol, but i think its fine - sorry to bother
IDEs yell about many things even when they work
Have I written this line wrong?
await interaction.followup.send(role.mention, allowed_mentions=discord.AllowedMentions.all())```
I have the role in question so I would expect that to have pinged me
does the bot have permission?
oh wow
no it doesn't
thank you
it definitely used to be able to ping a few years ago
i guess discord changed stuff around
how would you print out what permissions your bot has in a server
No tag guild.permissions found.
Target not found, try again and make sure to check your spelling.
._.
.rtfm guild.perms
Target not found, try again and make sure to check your spelling.
discord.Guild.me
discord.Guild.member_count
discord.Guild.members
discord.Guild.name
discord.Guild.get_member
discord.Guild.get_member_named
discord.Guild.max_members
discord.Guild.mfa_level
discord.Guild.max_presences
discord.Guild.welcome_screen
discord.Guild.afk_timeout
discord.Guild.estimate_pruned_members
discord.Guild.fetch_member
discord.Guild.fetch_members
discord.Guild.max_video_channel_users
for permission in user.guild_permissions```
guild.me.guild_permissions
can i use bridge cmds in commands.bot
no
then does bridge.bot support all fuctions as commands.bot?
yes
How can i add a reaction to a forum post?
would anyone be kind enough and make a listener for on_stage_instance_delete inside a cog and see if it works?
How do I make a function send a message?
just use async functions
I'm using a cog so does it work if the function is outside the cog?
I think ye
Why shouldn't it?
oh wait how do I make it?
async def send_my_message(message, channel):
await channel.send(message)
If I haven't messed anything up because I haven't tested it, then so
Just use it like await send_my_message('Hi', my_channel)
is there a way to only show certain slash commands to certain users/roles?
Yeah. You can use discord.commands.default_permissions
https://docs.pycord.dev/en/stable/api/application_commands.html#discord.commands.default_permissions
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...
thank you!
how can i display the users on which shards they are
.rtfm guild.shard_id
but in the presense of each server?
i get unkown interaction when trying to reply the original msg, anybody know why?
Its in spanish, sorry for that
well, now its working and i don't even modify anything π
add an await ctx.defer() to extend the interaction window to 15 minutes. The likely reason you get "unknown interaction" is probably because it is taking more than 3 seconds
where should i add that?
the first line of the callback
after the async def line and before the euro=euro1()
alr 
another question, whats CTX in pycord, like the type
i used ctx:commands.Context
in your case, bridge.Context
alr
bridge.BridgeContext maybe?
π
whats the best way to do an exit command
and why sometimes i get this
I thinks its a discord issue bc if i do Ctrl + R i can use them now but idk
bot responding twice. bot isnt srunning twice and it happenes with hybrid and prefix cmds
@bot.hybrid_command(description="Learn About Me!")
async def about(ctx):
await ctx.respond("I'm a robot from year 2300 that came here to help You π.")
Try resetting the bot token
How can I sync slash commands with discord?
It was yesterday, havent changed anything and its not syncing today.
(Removing old commands, adding new SlashCommandOptionType-s to existing commands)
Currently i have this but its not working.
@bot.event
async def on_connect():
await bot.sync_commands(delete_existing=True, force=True, method="individual")
print(f"Commands synced")
need this fixed asap so @ me please
My bot suddenly started to throw errors on my modals, that the interaction has already been used.
But if I look through my code, it doesn't seem like that at all...
Am I just blind and missing something?
https://gist.github.com/lorddusk/c1fa7c8a3dbb6ff8a252a0696bc06d93
It doesn't reach the callback from the Feature modal, it errors on Line 6 (send_modal) with
discord.errors.InteractionResponded: This interaction has already been responded to before
But I don't see it.
Ok it's getting weirder... I've added some debug prints for interaction.response.is_done() to every other line, and they all return False, none of them return True.
Fixed. I had a on_interaction somewhere that had a misplaced defer in it. 
I don't understand what I'm doing wrong. I've tried removing the buttons after 6 seconds but it just brings up the default buttons py @discord.slash_command() async def help(self, ctx, command: str = None): pagelist = [ pages.PaginatorButton("prev", style=discord.ButtonStyle.secondary, emoji=""), pages.PaginatorButton("page_indicator", style=discord.ButtonStyle.gray, disabled=True), pages.PaginatorButton("next", style=discord.ButtonStyle.secondary, emoji=""), ] if command is None: paginator = pages.Paginator( pages=self.get_pages(), loop_pages=True, custom_buttons=pagelist, use_default_buttons=False, show_indicator=False, ) await paginator.respond(ctx.interaction, ephemeral=False) await asyncio.sleep(6) await paginator.update(custom_buttons=None, use_default_buttons=False)
how can I disable pycord logging with the logging module
I am using mypy & type annotations in my project, however Pycord hijacks these annotations for slash-command option input types. One of my options is not required, which results in the option possibly being NoneType, however Pycord complains when I annotate the function argument as such. I am already using the @discord.option() decorator so the automatic option input_types are not necessary. TL;DR how do I disable Pycord hijacking type annotations for automatic option input types?
is it a list?
is what a list?
here's an example:
@discord.slash_command(name="echo") # type: ignore[no-untyped-call, misc]
@discord.option(name="repeat", input_type=int, required=False) # type: ignore[no-untyped-call, misc]
async def echo(self, ctx: discord.ApplicationContext, repeat: int | None) -> None:
if reapeat is None:
await ctx.respond("You didn't want to repeat")
else:
for _ in range(repeat):
print("I am repeating")
await ctx.respond(f"I repeated {repeat} times")
In this instance the error TypeError: Invalid class <class 'NoneType'> used as an input type for an Option is raised
repeat: Optional[str] still results in the same error
(from typing import Optional)
no, not like that
async def echo(self, ctx: discord.ApplicationContext, repeat: Option(int) = None)
?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.
my guess is you're trying to change presence before you're connected to discord
Hmm that doesn't seem to work either. AttributeError: 'Option' object has no attribute '__name__'. Did you mean: '__ne__'? I would rather not define the option's arguments (E.g. name) inside the type annotation as I am already using the @discord.option decorator
so i have this neat little interaction message with select menus, which i want to update/resend if an option is selected, i tried
await interaction.edit_original_response(view=ConfigAboutme(self.user_id))```
but it raised
Traceback (most recent call last):
File "C:\Users\Daniel\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\ui\view.py", line 414, in _scheduled_task
await item.callback(interaction)
File "E:\PyBots\guppi\cogs\social.py", line 45, in addselect
await interaction.edit_original_response(view=ConfigAboutme(self.user_id))
File "C:\Users\Daniel\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\interactions.py", line 428, in edit_original_response
data = await adapter.edit_original_interaction_response(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Daniel\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\webhook\async_.py", line 219, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook
How do I fix this error? No specific code produced the error, but I assume itβs something to do with sharding.
should be interaction.response.edit_message()
File "/home/container/cogs/bumping py", line 486, in bump await ctx.interaction.edit_original_response(embed=embed, view=v)
If I'm not mistaken, this should also be ctx.response.edit_message()
thanks π
was going off of this lol
Is there something like a on_tag_add and on_tag_remove event or will I have to rely on on_raw_thread_update?
you have to rely on the thread event
okay, thx
How am I able to tell which tag got added? seems like on_raw_thread_update just returns the tags, but not the added/removed tags
on_thread_update has before and after
how are you meant to remove all the buttons on a pagintation after a certain amount of time
Only works if the channel is in the chache
Wans't it like view=None ?
Can someone give me a code with which i can play music via youtube?
no, against discord's tos because against youtube's tos
Hi guys, How can i do "go to " button in the paginator? Like i click on [1/12] and it calls modal dialog where i can type the number of page?
you dont really get the view option unless you go to custom_view
i'd use paginator.update to try and get rid of the buttons but it just seems to revert them back to the default ones anyway which is annoying when trying to use custom buttons beforehand
So i have maxed out all 25 options in autocomplete / option
is there a way i can make it work with strings too? would removing "required = true" help this?
only choices have a limit of 25
yes
thats what ive run into
so is there a way to use both choices and strings?
so a user can manually type out the choices that cant be displayed?
autocomplete at slash commands can be a bigger list
autocomplete is what you want
Here's the slash autocomplete example.
it depends on what product_picker is
so i obviously can localize names and descriptions, but is there a way to get a users locale to adjust the received messages for them?
ty
that shoudl work. do you have any errors?
no errors in console, and not product in display :(
discord only shows the first 25
thats what i suspected, is there a way to make the hidden ones work?
or maybe update the list as the user types?
that's what
does
You just need to select the 25 most relevent. Or do what squid said
sadly i must have all 26 work, so ill have to go with squids option
All 26 cannot show up at the same time tho. even with squids option.
What autocomplete is for is I have a list of colors
Blue, Red, Green, Black, Grey + a lot more
When I type "B" discord sends this to the bot and the bot can do what it wants with this info, generally this would filter out all colors that do not start with the letter B. So your bots code would filter the list to
Blue, Black
does anyone know of a better way(or rather easier) to localize content of messages?
ok great!
just be aware, the users can just type whatever they want and click enter
im aware, but with my current system even typing "hyenid" would keep all other 25 popped up
so this made it so that typing finally fixes the chat box
yup, made a catch just incase this edgecase pops up
thank you again squid
Privat bot
regardless, it is still against tos
as far as i know not if the dev has youtube premium
nope. Premium users and non-premium users have the same restrictions
Anyways. Is there any possibility
How to create a text channel in specific category?
thx
Hey Iβm making a bot for a school discord server, is it ok if i give it administrator perms?
since iβm making the bot and i have no ill intent it should be fine right?
iβm a bit worried however if a hacker could gain access to it but iβm not sure how theyβd even go about doing that
they would just get your bot's token
it's best to give it admin for testing and then change enable perms as needed
the thing is i plan on running my bot on a personal home server with none of the ports open so iβm not sure how theyβll be able to gain access to the token
also the bot does so much that it basically has most of the perms checked anyways
(planning for it to be an all-in-one role, moderation, warnings, levels, etc bot)
if i have all the perms check marked (besides admin) does that equal admin perms?
I have an on_raw_thread_update event. It get's triggered, but only if just the tag 1132640937076609126 is in applied_tags. It doesn't detect both tags being in applied_tags nor just 1132640430090113024.
Code:
applied_tags: list[int] = [int(tag) for tag in payload.data.get("applied_tags")]
if applied_tags is None:
print("None detected")
return
print(f"Update detected: {applied_tags}")
if 1132640937076609126 in applied_tags and 1132640430090113024 in applied_tags:
"Both detected"
return
thread: discord.Thread | None = payload.thread
if thread is None:
thread = self.bot.get_channel(payload.thread_id)
if 1132640937076609126 in applied_tags:
print("Received detected")
await core.remove_from_thread_directory(thread)
await thread.archive()
return
if 1132640430090113024 in applied_tags:
print("Waiting detected")
await core.add_members(thread)
await core.add_to_thread_directory(thread)
await thread.unarchive()
return
Output:
Update detected: [1132640430090113024, 1132640937076609126]
How would I go about making a field like this? Or is it literally just as simple as a field having an invisible name
So 1 you never print Both Detected.
- Check that the ID is correct. Im sure you did but this is simple code Im not seeing another issue,
It looks like a field with an invisible name. Discord required a name but you can trick it by input a zero width space I think.
Pefect thank you
Why does this line not send my new pfp when I do the command?
If I run the command, then change my pfp it does not send the new pfp but the old one
It can take some time
Copied it twice, should be correct
Iβll try once again when Iβm home, if it doesnβt work Iβll prob create a thread here
Its been like 12 hours and it still hasntchanged
how can i make an variable "global" that i can use it in my modal class
i want that i have a user command (app) to ban a user
and when i click on it it opens an embed where i put the reason
but idk how to get the member from the command above to ban him
It's a user context menu
The user is passed by the function
The user that used the context menu, is the interaction.user
@bot.user_command()
async def ban(ctx, user):
await user.ban()
Dude. I restart the damn bot after changing 1 slash command.. Then all 50 of my slash commands permissions reset.
This is bullshit. Is this a PyCord issue or Discord? I didn't change all 50 commands..
Why should I continue spending 20-40mins every damn time setting my permissions up again and again!
both
Well this is insanely annoying.
make sure you are on the latest version of pycord
Discord doesn't give a good way to do it
I'm on the latest version ..
I have not run into this issue, just to make sure you are doing things right. Can you show an example command definition. Also how you register commands/load cogs
I want to listen for an action in a message that was sent before the bot started, is there any way i can do that without editing/deleting and resending the message?
this is the message i have, and if the bot restarts, i dont want to resend it to make it work
Here's the persistent example.
ty
?tag persistant_view
The Issue
When you send a message with a view, button for example
if your bot restarts, you will lose the ability to use this button.
How To Fix This
- Set your view timeout to
None
- By default, the view timeout value is set to 300 seconds
- Pass a
custom_idvalue to the view
- Custom ids must be unique
- Chose a custom id that has a meaning in relation to your view
- Add the view to the bot
- You can use the method
Bot.add_view(YourViewClass()) - Make sure to add the view when the bot begin ready
These are what make it different than a normal view
The name has a typo π
persistant <- wrong
persistent <- right
Xd
ty, it worked
I am trying to make a game which can let you print stuff as accuracy so I import numpy as np but it look like error in my terminal (mention me when reply I really need a help)
@bot.command(name="spin", description="get a roll with it")
async def get_spin(ctx):
spinList = [':b1:', ':y1:', ':75:']
accuracy = [0.885, 0.085,0.03]
chosen = np.random.choice(spinList, 10, p=accuracy)
final = ' '.join(chosen)
await ctx.respond(final)
-import numpy as np
-ModuleNotFoundError: No module named 'numpy'
-Traceback (most recent call last):
what can I do
some venv or sth?
try
pip install numpy
in the environment youre using.
weird though, should be a standard library, right?
nope, numpy isn't an stdlib
OHHH! That's why
alright, there is your fix @last gull
ok let me try
its still not work I have try
os.system('pip install numpy')
i thought you'd simply open up a terminal, type pip install numpy, close it and run your unchanged code again.
while you're at it, pip list should show the package afterwards
because I'm not using my desktop to run my bot Im using a hosting server but Im not really sure is it really relevant with it
so? ssh in?
but I will still try to install it first
How to make something happen after specific user time?
Im using a Asyncio.sleep(time) and the thing I want after but I want to know if there is a better / most efficient way
send your code
my slash command isnt registering
can someone help
only 1 slash command works
Ive made 2 but only 1 works
@bot.command(
name = "homework",
description = "View and Tick off Today's homework",
)
async def homework(ctx):
await createn(ctx.author)
users = get_student()
work = users[str(ctx.author.id)]["Completion"]
embed = discord.Embed(title="Homework",description="List of work you need to do",color=discord.Colour.embed_background(theme="dark"))
for diction in work:
if diction==None:
return ctx.send("Internal error")
complete = ""
if diction["Status"] == "Complete":
complete = "βοΈ"
else:
complete = "β"
embed.add_field(name=diction["Subject"],value=diction["Description"]+" "+complete)
await ctx.respond(embed=embed)
#{"Subject":0,"Description":"No homework updates","Status":"Incomplete"}
@bot.command(name="create",
description="Create homework [Only Admin]"
)
async def create(ctx : discord.context,subject:str,description:str):
users = get_student()
for user in users.values():
user["Completion"].append({"Subject":subject,"Description":description,"Status":"Incomplete"})
ctx.respond("Done!!",ephemeral=True)
this is the code
looks like u have no slash_commands even
ur using @bot.command decorator
Change @bot.command to @bot.slash_command.
ok
Also, remember that slash commands may take a few minutes to show up on the server. Run your bot for a little if they don't show up.
It usually takes about a minute to register a command
How to test new features for your bot, but not touching your current bot?
Deploy a second bot in a test server
So, create a second bot in Discord Developer Portal?
How?
Just add guild_ids to the annotations
Can you show me an example of code?
That is fine if you use discord.Bot and not commands.Bot for slash commands
@azure kettle do you use discord.Bot or commands.Bot?
I'm not at home
I just want after certain time from a command something happen
discord.ext.tasks.Loop
discord.ext.tasks.Loop.add_exception_type
discord.ext.tasks.Loop.after_loop
discord.ext.tasks.Loop.before_loop
discord.ext.tasks.Loop.cancel
discord.ext.tasks.Loop.change_interval
discord.ext.tasks.Loop.clear_exception_types
discord.ext.tasks.Loop.current_loop
discord.ext.tasks.Loop.error
discord.ext.tasks.Loop.failed
discord.ext.tasks.Loop.get_task
discord.ext.tasks.Loop.hours
discord.ext.tasks.Loop.is_being_cancelled
discord.ext.tasks.Loop.is_running
discord.ext.tasks.Loop.minutes
discord.ext.tasks.Loop.next_iteration
discord.ext.tasks.Loop.remove_exception_type
discord.ext.tasks.Loop.restart
discord.ext.tasks.Loop.seconds
discord.ext.tasks.Loop.start
Maybe not, remembered those differently
For tasks You would have to manually create the loop object instead of using the decorator. That way you could have the same loop running multiple times.
If it is shorter (under a minute) just use asyncio.sleep(seconds)
bro i want that he get banned IN THE MODAL CLASS
after inserting the reason
the modal should return an interaciton object, use this instead of ctx to get the user
Is it possible to use the once=True kw when subclassing the bot?
You can pass the user as an argument to your model subclass.
how?
woulnd't interaction.user be faster?
that would return the author
That is basic python
They need the author and the target from the user command.
Dang Iβm stupid youβre right
Can you send one of your commands?
Not right now, but when I have an access to my PC, then sure
I mean you just pass guild_ids=[] to the decorator
I highly recommend a second bot though. That way if you break things or need to restart the bot multiple times it won't effect users.
you guys get users? 
Users were already there, I just added the bot
hmhm im kinda disappointed that while on the one hand i am having fun learning how to git gud, the community i am making my bot for is inactive af atm
invoker_top_role_position = ctx.author.top_role.position
user_top_role_position = user.top_role.position
bot = ctx.guild.get_member(self.client.user.id)
botRole = bot.top_role.position
elif botRole <= user_top_role_position or user.guild.owner:
embed = build_embed(ctx.author.guild, title="β Request Failed", description=f"The bot can not add roles to users with the {user.top_role.mention if not user == ctx.guild.owner else 'Owner'} role.")
return await ctx.respond(embed=embed, ephemeral=True)
For some reason even though the bot has a higher role it is still getting caught here. Can anyone spot what im missing?
How can i create a webhook with a channel?
i fetch it then how can i create a webhook on it

u can on discord.TextChannel
not when u use fetch for some reason
It's recommended to compare on the objects themselves. Not with .position
And you can access your bot with ctx.guild.me
Oh yeah, thanks for the response!
thanks <3
Target not found, try again and make sure to check your spelling.
i dont find my fix pls help me
@client.user_command(guild_ids = servers, name="Ban")
async def ban(ctx, member: discord.Member):
# Du kannst dich nicht selber bannen
if member == ctx.author:
await ctx.response.send_message("> Du kannst dich nicht selber bannen!", ephemeral=True)
return
# Du kannst keinen Administator bannen
if member.guild_permissions.administrator:
await ctx.response.send_message("> Du kannst keinen Administrator bannen!", ephemeral=True)
return
else:
await ctx.response.send_modal(BanModal(title="β User bannen"))
# Ban Modal mit Reason Input Feld
class BanModal(discord.ui.Modal):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs, timeout=None)
self.add_item(discord.ui.InputText(label="Ban Grund:", placeholder="Scamming", min_length=5, max_length=100))
async def callback(self, interaction: discord.Interaction):
# AusgewΓ€hlten Member von oben bannen
member = interaction.target_author
await member.ban(reason="test")```
how can i make an variable "global" that i can use it in my modal class
i want that i have a user command (app) to ban a user
and when i click on it it opens an embed where i put the reason
but idk how to get the member from the command above to ban him
You don't make variables global.
You pass variables to the modal class so you can work with them.
""
This is basic OOP.
No, you're expected to know OOP when working with pycord.
whats OOP
Object Orientated Programming.
?tag oop
There's a difference between a class and an instance. Think of it like this:
- A class is like a blueprint, or a concept. It defines what something should have, but it's not the same as actually having it.
- An instance is the 'realized' version of the class, it contains everything that the class defines should be on it, but you can actually access and interact with these features.
Let's consider the Cat. We know a Cat has a name and an age, but Cat.age won't work, because Cat isn't an actual cat, it just represents the concept of a cat. It's like asking "What is the age of a cat?" - it doesn't make sense, because we need to have an actual cat.
mimi on the other hand is an instance of a Cat - it has everything Cat says it should have. Maybe mimi was constructed, like mimi = Cat("Mimi", age=4), or maybe mimi was retrieved from somewhere else, like house.cats[0], but in any case, it has everything we need, and mimi.age will rightfully give us 4.
There are many situations in Object Oriented Programming where you will need an instance instead of a class to perform an operation properly (in fact, you almost always need an instance instead of a class), and these cases will usually be documented.
You should learn a good amount about Object Oriented Programming before working extensively with Pycord.
You're pretty much forced to learn OOP if you want to work with pycord.
You can't just expect to work with it without having basic knowledge.
i have basic knowledge
i know everything
but not this
and i ask here for help and not for an man that sends me the docs

There's a difference between "how could I work with this" and "how to do this because I don't know the basics"
youre dumb
Your main issue was answered.
We told you how to do it.
What you're lacking is the knowledgeable about it to do it.
Is there a limit to pages in a Paginator? Or can I also have 100 pages created?
You clearly don't if you can't pass a simple variable to a class
I don't think there's a limit. I have like 80.
Okay thanks! π
.rtfm pages
discord.ext.pages.Page
discord.ext.pages.Page.callback
discord.ext.pages.Page.content
discord.ext.pages.Page.custom_view
discord.ext.pages.Page.embeds
discord.ext.pages.Page.files
discord.ext.pages.Page.update_files
discord.ext.pages.Paginator
discord.ext.pages.Paginator.add_button
discord.ext.pages.Paginator.add_default_buttons
discord.ext.pages.Paginator.add_item
discord.ext.pages.Paginator.add_menu
discord.ext.pages.Paginator.cancel
discord.ext.pages.Paginator.clear_items
discord.ext.pages.Paginator.disable
discord.ext.pages.Paginator.disable_all_items
discord.ext.pages.Paginator.edit
discord.ext.pages.Paginator.enable_all_items
discord.ext.pages.Paginator.from_message
discord.ext.pages.Paginator.get_item
Search the world's information, including webpages, images, videos and more. Google has many special features to help you find exactly what you're looking for.
Are you sure about that
I can literally google it and get a million results about it
i dont
cant you just literally pass on the user id or stuff from the user_command to the modal class's init?
That's what we told him
no idk how!!
Man doesn't know how to use classes
i mean isnt it literally jsut this?
He doesn't know oop
i know how to use OOP, but making shit with OOP.... uhhhh
my shit works, that gotta suffice
so I do:
user_id = ...
await ctx.response.send_modal(BanModal(title="β User bannen"), user_id))
?
you could delete the user_idline ;3
why would you store the response in user_id?
idk how you did it too?
bro i too
??

or did you mean i should replace ctx.response.send_modal with ctx.send_modal?
im from germany i dont understand 100%
ah my bad the ... behind the = made it look like the await send... was stored inside user_id and then being sent within itself(?)
naja ich doch auch π€·ββοΈ
.
thx
btw you can remove the discord.ApplicationContext too i guess
only ctx is enough
i have it too
yes, was looking for some uhhh insight or whatever the fancy autofill shit in IDEs is called
If you want to have autocomplete at the IDE, you should add something like discord.ApplicationContext
eh, was just too lazy to 
why is localization such a damn pain in the ass, why am i bothering with en-US localization when the users are german-ish
isnt there some fancy tool just... do stuff?
Typehinting
does anyone know why when my select menu shows up, it says interaction failed after a second? but it actually works fine when i select the items in the select menu? here the code, sorry if its hard to understand:
class RerollTwoSlotsWithRig(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
self.value = None
@discord.ui.select(
custom_id='persistent_view:reroll-two-rig',
placeholder=REROLL_TWO,
min_values=2,
max_values=2,
options=REROLL_OPTIONS_RIG
)
async def select_callback(self, select, _):
self.value = select.values
self.stop()
...
async def is_random_modifier_special(
rolled_random_modifier: eft.GameRule,
need_rig: bool,
ctx,
embed_msg,
filtered_items: dict[str, list]
) -> None:
if rolled_random_modifier.name == REROLL_ONE:
select = RerollOneSlotWithRig() if need_rig else RerollOneSlotNoRig()
await reroll(ctx, select, embed_msg, filtered_items)
elif rolled_random_modifier.name == REROLL_TWO:
select = RerollTwoSlotsWithRig() if need_rig else RerollTwoSlotsNoRig()
await reroll(ctx, select, embed_msg, filtered_items)
...
async def reroll(ctx, select, embed_msg: discord.Embed, filtered_items: dict[str, list]) -> None:
await ctx.edit(embed=embed_msg, view=select)
await select.wait()
for category in select.value:
rerolled = random.choice(filtered_items[category])
if ctx.command.name == 'roll':
await reveal_roll(ctx, embed_msg, rerolled, REROLLED_PREFIX)
elif ctx.command.name == 'fastroll':
embed_msg.add_field(name=f'{REROLLED_PREFIX}{rerolled.category}:', value=f'{rerolled.name}', inline=False)
...
@bot.slash_command(name='fastroll', description='Loadout Lottery! (Without the waiting around)')
...
await is_random_modifier_special(rolled_random_modifier, need_rig, ctx, embed_msg, filtered_items)
...
It can take from 1 hour to 24
HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components.0.components.0.options: Must be between 1 and 25 in length.
Even though im only using 10 characters this error keeps happening
class SelectThings(discord.ui.S):
@discord.ui.select(
placeholder="Complete homework",
min_values=1,
max_values=1,
options=real_ops
)
async def callback(self,select,interaction):
await interaction.response.send_message(f"Good job on completing {select.values[0]}.")```
this is my select menu class and
```py
@bot.slash_command(
name = "homework",
description = "View and Tick off Today's homework",
)
async def homework(ctx):
await createn(ctx.author)
users = get_student()
work = users[str(ctx.author.id)]["Completion"]
embed = discord.Embed(title="Homework",description="List of work you need to do",color=discord.Colour.embed_background(theme="dark"))
for diction in work:
if diction==None:
return ctx.send("Internal error")
complete = ""
if diction["Status"] == "Complete":
complete = "βοΈ"
else:
complete = "β"
embed.add_field(name=diction["Subject"],value=diction["Description"]+" "+complete,inline=False)
real_ops.append(discord.SelectOption(label=diction["Subject"]))
await ctx.respond(embed=embed,view=SelectThings())```
this is the command, and real_ops is a global variable so that I can make the select options based on the list in my json.
How many items are in real_ops?
1
subclass the select object instead of the view
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'SelectThings' object has no attribute 'to_components'
anyone can help me?
send the code that goes with it?
send your code
oh you did, sorry. you still use ctx.respond(embed=embed,view=SelectThings()) where you treat SelectThings() as a view
Oh ye
I sent
how do I use it as a select
please answer me π ive been waiting for quite a few hours now
i dont use this lib either really, i came here with my own question but it seems theres no expert around^^
could only see why the error was happening
im not sure about the correct way to do it, but im looking at one example where the view itself gets subclassed, and then passed
it seems send_message (or respond or whatever) only takes view objects, not components 
This is my ping command:
@bot.slash_command(name = "ping", description = "Check the latency of this bot")
async def ping(ctx):
latency = int(bot.latency * 1000)
await ctx.respond(f"Bot latency is **{latency} ms**.")
I printed the list and this is what came <SelectOption label='Maths' value='Maths' description=None emoji=None default=False>
self.guild_ids: list[int] | None = kwargs.get("guild_ids", None)
just add guild_ids to decorator
its all there
from source
I didn notice thi message
What's decorator?
like
@bot.slash_command(name = "ping", description = "Check the latency of this bot", guild_ids = [my_guild])
async def ping(ctx):
latency = int(bot.latency * 1000)
await ctx.respond(f"Bot latency is **{latency} ms**.")
@
Thanks!
i'm not sure but try to replace ur subclass to discord.ui.View
HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components.0.components.0.options: Must be between 1 and 25 in length.
Even though im only using 10 characters this error keeps happening
class SelectThings(discord.ui.S):
@discord.ui.select(
placeholder="Complete homework",
min_values=1,
max_values=1,
options=real_ops
)
async def callback(self,select,interaction):
await interaction.response.send_message(f"Good job on completing {select.values[0]}.")
this is my select menu class and
@bot.slash_command(
name = "homework",
description = "View and Tick off Today's homework",
)
async def homework(ctx):
await createn(ctx.author)
users = get_student()
work = users[str(ctx.author.id)]["Completion"]
embed = discord.Embed(title="Homework",description="List of work you need to do",color=discord.Colour.embed_background(theme="dark"))
for diction in work:
if diction==None:
return ctx.send("Internal error")
complete = ""
if diction["Status"] == "Complete":
complete = ":ballot_box_with_check:"
else:
complete = ":x:"
embed.add_field(name=diction["Subject"],value=diction["Description"]+" "+complete,inline=False)
real_ops.append(discord.SelectOption(label=diction["Subject"]))
await ctx.respond(embed=embed,view=SelectThings())```
i told u
i did that
it doesnt work
i cant test your code now
are you 100% sure that your real_ops has the correct form?
YES
sorry caps
ill show u what it printed
[<SelectOption label='Maths' value='Maths' description=None emoji=None default=False>]
that is the list
and my options = real_ops
quick query, is there any difference between the discord.Interaction of the dropdown and the one of the button. In the button it detects that I have a cache object but the dropdown does not.
They should be the same
Could it be a bug in the IDE?
the first time I got the error, but I don't get the underlined error anymore :/
Might be your ide then
You switched to Spanish for a moment and I was so confused why it was Spanish on my notification but English here
yes, sorry, my head automatically translated into English and I thought you were writing to me in Spanish, so I answered without thinking.

Doesn't work?
I confirm it is the IDE, sorry for the inconvenience.
No worries
is it possible to take multiple text channels as an argument for a slashcommand?
it could be any number greater than 1.
like a list argument?
select menus limit it to a maximum of 25. also hard to find the desired channels in them. cz like 5 menus each with 5 options to choose from and what not
Like /set channel1 channel2 channel3?
yes!
Kind of.
*args should do the job, idk if able to just put channel objects after eachother.
With *args you need to get the channelobjects by yourself.
Its more a question of the object handling by the bot than the possibility
channel objects after eachother
i think i cant do that. but i may be wrong. ill send a snippet
async def merge_channels(ctx, *, channels: discord.TextChannel):
async def merge_channels(ctx, *channels: discord.TextChannel):
i tried these both. they only allow me to choose one channel. i may be doing a dum dum. so please correct me if im wrong
well its not wrong
only the normal one
if you do a channel one, they dont really have a limit
really. and how can i do that?
Or ask the dragon furry lmao
π
More a joke than an insult
i guess ill look around a bit more. if not. ill just do a simple text command
merge and type out channels after that.
you get it like discord.ui.user_select
got it
modal sites?
Modals with multiple site's
what I only know is that modal with text input is the only thing that works really well
I rewrote some stuff by myself to make it work. 
Ok, thanks
I know some way trying to create modal with a dropdown but that is currently not working with py-cord
Hi!
I have a little problem, when I print ctx.channel it shows me the name of my textual channel.
My goal is to retrieve the list of channel users. Obviously, I print ctx.channel.members except that this prints all the users on my server. Obviously, everyone is not allowed to see the channel.
I guess I did something wrong
;3
Hey, i tried this. but the dropdown only shows 15 channels
@discord.ui.channel_select(
min_values=1,
max_values=25
)
async def select_callback(self, select, interaction):
await interaction.response.send_message(f"{select.values}")```
and how many channels do you have?




