#Basic Pycord Help
1 messages · Page 18 of 1
Command.can_run is propagating past my try except block
try:
if not await command.can_run(ctx):
continue
except:
continue
the command is of type BridgeCommand
Okay, thanks
What?
Oh, I thought this was my answer
Learn to code? That question has nothing to do with ui.
Fixed, had to catch only command errors for some reason. Should really make them not propagate past broad except blocks.
Why do you even use a try and exept block?
and not a error handler
It's for a specific command not broad error handling
you cant fix it
i want to write a line that looks for channel named after the command user and it does simply work, it said nonetype has no attribute delete, i d like to know whats preventing this from working and a solution and thanks
lfg_channel = discord.utils.get(interaction.guild.channels, name=f'{sanitize_author_name(interaction.author.name)})
ctx.author or interaction.user
Hm, I don't know what happened, but after an update to my bot every single commands have lost it's parameters
Like all of them
Like the parameters are just gone
any idea why?
Comment out the command, run the bot, remove the comment, run the bot again
I mean like it's for every single commands
I'm just attaching it on as an example of what the structure is
but okay
i'll just try that
And.. that didn't work
It's confusing though
Nothing changed, beside the addition of 2 commands
Okay
So I've just tried to reinstall the main version of pycord
instead of installing from git repo
and that worked
So maybe something happened up there
Slash command are not passing options on master for me as well. Application Commands in slash command groups work, but not top level @bot.slash_command() methods.
for me its working fine
does
pip show py-cord | grep Version
return Version: 2.4.1.dev214+gfc7b1042?
;3
Rolling back to 8af8454 fixes it. fc7b104 introduced the bug.
Ignoring exception in view <ProccessingOrder timeout=None children=2> for item <Button style=<ButtonStyle.success: 3> url=None disabled=True label='Accept Order' emoji=None row=None>:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/ui/view.py", line 414, in _scheduled_task
await item.callback(interaction)
File "/Users/appletumu/Documents/GitHub/Tumbot/cogs/iaf.py", line 223, in accept_order
await IAF.qm_ordering_logs(self, interaction, "interaction", "finish_order", send="qm_orders_log")
File "/Users/appletumu/Documents/GitHub/Tumbot/cogs/iaf.py", line 120, in qm_ordering_logs
user = self.bot.fetch_user(dsc_user_id)
^^^^^^^^^^^^^^^^^^^
AttributeError: module 'discord.bot' has no attribute 'fetch_user'
This happens with fetch_user, get_user, fetch_member and get_member
user = self.bot.fetch_user(dsc_user_id)
^^^^^^^^^^^^^^^^^^^
AttributeError: module 'discord.bot' has no attribute 'fetch_user'
I have checked pip list and checked that I have the correct intents
lowercase b
but you also read the error right?
yes it's smth to do with my module
oh shoot wait
i see now
;3
💀
how do i fix the certifcate problem?
Just updated pycord to its latest version. Now getting an error when trying to get the top role of a user.
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'User' object has no attribute 'top_role'
async def ban(self, ctx : commands.Context, member : discord.Option(discord.SlashCommandOptionType.user, description="The user you want to ban", required=True)...
if member.top_role >= ctx.author.top_role:
Calling the authors top role is not an issue, just the mentioned members.
discord.Member instead of OptionType.user
Ok so how would I go about getting the bots top role?
I used to just get the bot as a user through bot.get_user and then just do botuser.top_role
ctx.guild.me returns the Member instance of the bot in the guild
Hi, is there an easy way to get the thread a command is used in (or null if used outside of a thread)? I don't see one in the context api and trying to get it roundabout through trying to use the response message also seems to mess up.
thats just the channel id
This is most likely the wrong channel to do so, but ill still ask: Recently, replit updated their policies, so now you can't host on replit with webservers. Does anyone else have any other methods of hosting for free? Heroku isn't working for me.
Oracle has a free tier. Google is free, search.
Oracles free tier asks for a payment method which I can't currently provide.
you won't really find a company that offers a free tier which doesn't ask you for a payment info ¯_(ツ)_/¯
Github student developer pack offers alternatives too.
Welp. guess I'm gonna have to fry my pc.
discord.Webhook
discord.Webhook.avatar
discord.Webhook.channel
discord.Webhook.channel_id
discord.Webhook.created_at
discord.Webhook.delete
discord.Webhook.delete_message
discord.Webhook.edit
discord.Webhook.edit_message
discord.Webhook.fetch
discord.Webhook.fetch_message
discord.Webhook.from_url
discord.Webhook.guild
discord.Webhook.guild_id
discord.Webhook.id
there are examples
Ah thanks
How long can a view wait?
discord.ui.View
discord.ui.View.add_item
discord.ui.View.children
discord.ui.View.clear_items
discord.ui.View.disable_all_items
discord.ui.View.disable_on_timeout
discord.ui.View.enable_all_items
discord.ui.View.from_message
discord.ui.View.get_item
discord.ui.View.interaction_check
discord.ui.View.is_dispatching
discord.ui.View.is_finished
discord.ui.View.is_persistent
discord.ui.View.message
discord.ui.View.on_check_failure
Hey, so i have a view that uses select menu and its callback edits the orignal message depending on the user's choice. This works fine but for some reason after editing the message the select option gets cleared. How do i prevent it?
class ProfileView(discord.ui.View):
def __init__(
self,
author:int,
general_embed_:discord.Embed,
rpg_embed_:discord.Embed,
) -> None:
super().__init__(disable_on_timeout=True)
self.author = author
self.embeds = {
"General Stats": general_embed_,
"RPG Stats": rpg_embed_,
}
@discord.ui.select(
placeholder = "Choose the profile page",
options = [
discord.SelectOption(label="General Stats"),
discord.SelectOption(label="RPG Stats")
]
)
async def select_callback(self, select:Select, interaction: discord.Interaction):
await interaction.response.defer()
if interaction.user.id != self.author:
return await interaction.followup.send("This command isn't for you", ephemeral=True)
await interaction.followup.edit_message(interaction.message.id, embed=self.embeds[select.values[0]])
Can I use discord.ext.commands.Greedy[T] in application commands? Or will I have to implement it myself?
Havent you already created a thread with that?
#1193446964176617534
well no one replied yet so i thought of sending here
I tried to do this:
@root.command()
@discord.guild_only()
@commands.check(channel_must_support_webhooks)
@discord.option("roles", commands.Greedy[discord.Role])
async def mention(
self,
ctx: CommandContext,
*,
message: str,
roles: commands.Greedy[discord.Role],
):
"""Minimize collateral pings by only mentioning members with all the roles you select.
Args:
ctx (CommandContext): The invocation context.
message (str): The message to attach to the mention.
roles (commands.Greedy[discord.Role]): The roles to select.
"""
...
but it keeps erroring with this log message: (see attachment)
Why? ;3
if I replace roles: commands.Greedy[discord.Role], with roles: list[discord.Role],, I get this instead:
role: discord.Role
I know ;3
The problem is, its not gonna work
you would have to use a role select
...i GUESS i could do that. but i would very much prefer if you could just put the list of roles in the invocation instead of in its own thing.
Is there an elegant way to specify no maximum selection? i.e. you can choose any number of options from 1 to every. single. one.
My solution to this:
async def role_select_prompt(
ctx: CommandContext, *args, **kwargs
) -> list[discord.Role]:
assert ctx.guild is not None
class RoleSelectView(View):
selected: list[discord.Role]
@role_select(
placeholder="Select roles...", max_values=len(ctx.guild.roles)
)
async def update(
self, select: Select, interaction: discord.Interaction
):
self.selected: list[discord.Role] = select.values # type:ignore
await interaction.response.defer()
@button(label="Submit")
async def submit(
self, button: Button, interaction: discord.Interaction
):
assert self.message
self.stop()
self.disable_all_items()
await interaction.edit_original_response(view=self)
view = RoleSelectView(disable_on_timeout=True)
await ctx.respond(*args, **kwargs, view=view, ephemeral=True)
await view.wait()
return view.selected
That will error if you got more than 25 roles
Which is the max value of max value (lol)
Also defining a class in a function is disgusting
so i was thinking that I could do something like "own_message = await ctx.reply("stuff") and then reply to my own message with own_message.reply("other stuff") later. but my interpreter is complaining about it
and I mistaken or does that work
seems like own_message becomes a WebhookMessage which inherits from Message which means i THINK i'm fine doing it that way?
is it a slash command?
originally it's a slash command, and I want to reply to the user with a "Loading whatever, please wait" message, and then once the slash command function is done I want it to reply to that "Loading whatever, please wait" message with the image output
Or maybe there's even a better way to do that too
particularly because I vaguely remember discord complaining if you respond to a slash command too late, and the function running in the background takes up to like 45-60 seconds
though i suppose i COULD just send messages instead of replying to a slash command. so maybe that'd be better
I just don't like ctx.respond'ing to slash commands because you just get a reply to a message that doesn't exist
like it works but it looks ugly
so for the webhook in a cmd i put this code inside the cmd function but its not working at all
anyone know why
aww I wanted to send a rickroll... 🥹
xd
Just a test one lol
boo. I have two slash command groups defined seemingly exactly the same way and the newer ones won't show
is there still some sorta timer or should it be instant
like does anyone see something here I don't
ignore the botw
i typed that by accident while taking the screenshot
How do you load the cog?
just like the other one
I figured it out, sort of
The command shows up on one server, but not the other
so... you import the cogs to the main file?
Yes
the main file is literally just a tiny file that initializes the bot, loads the cogs, and runs it
you could use client.load_extension(name="cogs", recursive=True) and dont have to import the stuff and adding the cog at the main file
do you use debug_guilds or guild_ids anywhere in your code?
anyone know how to turn the button into a link
Whats not working about it?
Just application is not responding
Im sure it is ctx.respond for bridge
Since user.mutual_guilds only returns mutual guilds that are in the cache, would I need to set chunk_guilds_on_startup back to True if I want all mutual guilds to be returned even on startup? My bot is in 5.8k servers do not setting it to false makes it take a while to startup.
yes
Want a custom selector view for role joining. Selector options would be a subset of roles on the server. Ideally would have the buttons enable if the user has/doesn'thave that role. Is this possible with the decorator style selector, and is there an example close to what I'm looking for? Specifically an example with the discord.ui.role_select as well.
In specific, I'm having trouble finding an example of dynamically adding something to a selector if that's an easy answer.
You cannot change permissions of individual slash commands in a slash command group ? It seems you can only change the permissions of the slash commands group but not the individual ones via the integration menu of your server
Is there an event that is fired before a command's function is executed so I can listen to it and do something before all commands?
yes
on_interaction
but not just slash comands
if normal commands, then on_message
There isn’t an on_command?
but it doesn't occur before a command
Like I don’t want commands to be usable while the bot is chunking guilds, since that takes a while for a big bot
Wait when is bot.is_ready set to True? After chunking guilds?
Oh according to the docs yes
Specifies if the client's internal cache is ready for use.```
you could intercept them in bot.process_commands or on_message, or add a global check with @bot.add_check
on_command supposedly is called before commands are run but it offers no way to control whether or not they execute
i think a check would be your best bet
in my defense, i was kind of in a functional mood. maybe i'll refactor it. maybe i won't.
There! ni li pona ala pona tawa sina? (is this good to you?)
class RoleSelectView(View):
selected: list[discord.Role]
@role_select(placeholder="Select roles...", max_values=25)
async def update(self, select: Select, interaction: discord.Interaction):
self.selected: list[discord.Role] = select.values # type:ignore
await interaction.response.defer()
@button(label="Submit")
async def submit(self, button: Button, interaction: discord.Interaction):
assert self.message
self.stop()
self.disable_all_items()
await interaction.response.edit_message(view=self)
@classmethod
async def prompt(
cls, ctx: CommandContext, *args, **kwargs
) -> list[discord.Role]:
assert ctx.guild is not None
view = cls(disable_on_timeout=True)
await ctx.respond(*args, **kwargs, view=view, ephemeral=True)
await view.wait()
return view.selected
Yes
In other, class-factory news... ||i'm just doing this to trigger someone||
T = TypeVar("T")
def function_converter_factory(fn: Callable[[str], T]) -> Converter[T]:
class FunctionConverter(Converter):
async def convert(self, ctx: Context, argument: str) -> T:
return fn(argument)
return FunctionConverter()
tenpo suno ale la sina kama sona e ijo sin. (you learn something new every day.)
how do you do that, exactly? i have never seen that in the docs!
Nvm pycord doesn't support that mb
Confused it with Hikari? 💀
...Am I the only one who uses hash(" ") as a global interpreter session ID?
For idempotency?
How can i make it not show this when someone uses a slash command
like it shows what they input
how do i hide that
like that only the person who did it can see the response right
how do i do that though
?tag ephemeral
An 'ephemeral' message is one that's only visible to the person who invoked a command. If you ever got a command error with a blue background, this is an example of one.
To do this, set ephemeral=True when you first use an ApplicationContext. (This includes .defer()ing it; the choice of whether a message is ephemeral or not must be made up front. If you .respond() to a deferred message, setting the ephemeral flag at that time will have no effect.)
This is the equivalent of hidden=True if you're coming from interactions.py
e.g.
await ctx.respond("Imagine a message!", ephemeral = True)
await interaction.response.send_message("Imagine a message!", ephemeral = True)
like this right
I use a fairly simple structure for my bot's cogs:
import logging
import discord
from pydantic import BaseModel
from core.bot import Bot, CommandContext
from core.embed_styles import OK
NAME = __name__.split(".")[-1].lower()
LOG = logging.getLogger(__name__)
class CogConfig(BaseModel):
pass
class Cog(discord.Cog, name=NAME):
def __init__(self, bot: Bot):
super().__init__()
self.bot = bot
self.config = CogConfig(**self.bot.config.cogs.get(NAME, {}))
root = discord.SlashCommandGroup(NAME)
@root.command()
async def hello(self, ctx: CommandContext, *, user: discord.User):
await ctx.respond(
embed=OK.embed(title="Hello", description=f"Hello {user.name}!")
)
When I add a @discord.default_permissions decorator to a command, like:
class Cog(discord.Cog, name=NAME):
# ...
@root.command()
@discord.default_permissions(administrator=True)
async def delete(self, ctx: CommandContext, name: str):
...
I can still see and successfully invoke the command on my alt that lacks the specified permissions, with no overrides set. ||well, about as successfully as it can be invoked while my dev database isn't running||
When I go to my bot's integration settings, I only see the top-level command groups--mod, tags, etc.
Is it possible to set default permissions per command in a group, or will I have to break them out into separate commands/use a @commands.has_permissions decorator instead?
.tias
you would need to resort to using internal checks
Finally noticed this note on discord.File, which explains why I'm having issues "crossposting" a message with an attachment to multiple servers.
(Workflow: A user uses a slash command, provides some information via args, and optionally provides an attachment. That info then gets "broadcast" to a number of servers that want to receive the messages, including reposting the attachment, if provided, onto each of the broadcast messages that gets sent out.)
Okay, I can accept that Files are single-use; that said, is there a suggested pattern for posting the same attachment / file in multiple places?
copy the link
Oh, so just grab attachment.url and repost that?
think so. I don't have documentation memorized
👍, makes sense. Thanks
I don’t like Pycord’s “username (Display)” when printing users, and would prefer it to be the opposite “Display (username)”
What would be the best way of adjusting this from my own code (especially without having to import a custom class anytime I want to reference a User)
why does it take so long to sync commands
like i put a command over 5 minutes ago it still doesnt show
is there a way to force sync them
?
you mean after a bot restart?
yeaj
@bot.slash_command(guild_ids=[guild_id])
try using it that way
not if you want to have global commands
i use client
its been like 10 minutes now no cap
and idk why its still not here
wtf
refresh your discord client -> ctrl + r
i already did
i even got on discord canary
on another account
still not there
idk
...
is the command at a cog?
.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.
format(user)
Not sure I follow. Seems like it would be best to monkey-patch the __str__ so I don't have to think about it, but was just looking for other ways of accomplishing this.
have a function that takes a user object that returns a string
can you show the pip list pls
uninstall discord, discord.py and py-cord and only reinstall py-cord
ok
Traceback (most recent call last):
File "c:\Users\usern\Downloads\Bot\main.py", line 10, in <module>
bot = discord.bot()
^^^^^^^^^^^^^
TypeError: 'module' object is not callable```
Still same error
Try changing that line to this:
bot = discord.Bot()
It is Bot not bot
Yeah
Thank you
It works now
😄
import discord
from discord import app_commands
from discord.ext import commands
class ExampleCog(commands.cog):
def __init__(self, bot):
self.bot = bot
@app_commands.slash_command(name='ping', description='pong')
async def ping(self, ctx):
await ctx.respond('Pong!')
def setup(bot):
bot.add_cog(ExampleCog(bot))
this is returning
Failed to load cogs.test: Extension 'cogs.test' raised an error: ImportError: cannot import name 'app_commands' from 'discord' (/home/pi/.local/lib/python3.7/site-packages/discord/__init__.py)
this is my first time working with slash commands
I used to work with discord.py but just upgraded to py-cord
isn't that discord.py v2.0
hmmmm i uninstalled discord.py and installed py-cord
so i don't think so?
unless i'm wrong
this is literally my fist time working with py-cord so I need basic basic help lol
any help would be appreciated
your python version is not supported. Please download a version between 3.8 and 3.11 inclusive
just use edit_original_response
Why interaction tho?
Commands receive ApplicationContext
so ctx.respond and ctx.edit should do it, the library handles it
Anyone know how user oauth works for connecting an application to your Discord account to get guilds?
I did create a separate help post but idk if anyone knows
User oauths, discord redirects to your url providing you a code, you exchange such code with oauth2/token to get the user token, then make a request to @me/guilds with the user token to get the guilds
*oauth token
Well it was a quick guide lolz
#1194162091230249020
and you didn’t say that you needed a web server for all of this
What I was going to do is have the bot provide the user with the link. to connect, then once they are done connecting, they click a Done button, then bot uses bot.http to fetch guilds. If the user didn't connect it - meaning it says no access/permission from the api - the bot would use cached guilds.
the user shouldn’t need to click a done button
Well yes. I thought that was obvious
not particularly
Not if you don't know enough about OAuth 🙂
i have no way to have it auto update the message
at least that is simple
poll for it
wdym
You can pretty much integrate a Web server with the bot
im so bad with web servers
And do some "caching"
i have no idea how to do it
To store the user waiting for a response
do you know the difference between polling vs events
no
I have a cog with a web server, sec
Polling is "Are we there yet? Are we there yet? ..."
Events are "We're here"
you can probably just spin one up in a few seconds with fastapi
I just don't know how to do the oauth and with a web server you're talking about
Of course, it'd have to be connected to the public web somewhere. Running through it in my head, wouldn't it be better to have a public endpoint simply passes messages (webhooks?) to the bot instance running internally
you can’t do oauth2 without web
I host my bot on heroku, so that provides me the way to host it as a Web
tbh if someone helps me create a system that does all that and gets the servers ill give nitro
i have too much stress from school to learn something new
dark basically already did it
i mean for my use case
Would love to pick your brain a bit more about that. I use Heroku for other apps, but haven't done it for Pycord. What tier are you running for it? Has it generally been stable?
I have student credits
And it's just a small bot so it's enough for me
it’s basically just changing the end point
yeah i have no clue how to do that
tbh if someone helps me create a system that does all that and gets the servers ill give nitro
you have a website right?
I'd do it, but not for nitro kek 
you have the code for it tho
for what 
Right, but what kind of resources does it have? Are you doing anything to keep the webserver isolated from the rest of the bot to reduce DDOS, or do you have some other protection for it?
What is your storage solution?
Actual money 
o
$10 amazon gift card /s
how much
or
I mean, it is just there
If you find my heroku link, then you can just spam requests cause I don't use authorizations or something
hire dark as a part-time employee
I never really planned protection for it
im pretty broke
Gotcha. In context of this conversation, that endpoint would naturally become public for oauth.
In any case, I'd love to hear more about how the env and code is set up, because I would like to do something like this myself and just want to get as much info as possible.
Is the bot that's running on Heroku open-source? I could get info from that instead of bugging you. (e.g. are you using FastAPI? If there's storage, is it just redis, since Heroku doesn't(?) have storage)
Heroku provides config vars (aka env vars or secrets) which you can just access with os.getenv
I dunno what you mean by heroku open-source.
For the web server I use aiohttp.Web
If you mean storage as dB, I use motor. If you mean storage as cache, I don't use redis or something. If I have to store something temporarily, I just use a bot var to store stuff and then add/remove on use. (Which I kinda do for other cog which isn't the web server, I store active queues )
No, I was asking if the [bot you were running on Heroku] was open-source.
Uhh, I think so
If you can't access that, then it isn't kek
It is. Will steal glean some inspiration. Thank you for sharing 🙏
It is not the best bot, or the "cleanest" one. But yet my best creation. I am still learning so code can be messy.
We all are! But I still always seem to learn something new when I look at Pycord bot source.
.. for instance, putting generic error handlers in their own class
is that a yes? 
If it is small, then I guess so. While I like volunteering cause I love coding, I do want some retribution back.
@bot.slash_command()
async def guilds(ctx):
button = discord.Button(
label="Click me to sync guilds!",
style=discord.ButtonStyle.link,
url=get_oauth_url(),
)
await ctx.respond(
content="Click the button below to sync guilds!", view=discord.ui.View([button])
)
for attempts in range(12):
user_oauth2_exists = ... # probably some database endpoint
if user_oauth2_exists:
guilds = await get_user_guilds(ctx.author.id)
break
await asyncio.sleep(5)
else:
return await ctx.edit("Timed out!")
await ctx.edit(f"Synced guilds!")
def get_oauth_url():
return discord.utils.oauth_url(
client_id=bot.user.id, redirect_uri="...", scopes=("identify", "guilds")
)
async def get_user_guilds(user_id):
access_token = {} # probably some database endpoint
guilds = ... # api call to get guilds
return []
``` this is my basic structure for the bot code i would think
It should be small. All I need to have code for is how to get guilds from a user when they do the oauth. But you have to have the user’s token correct?
Yes. The discord docs show how to exchange the code with an oauth token
I do have examples with my own testing, but they're in my laptop. I can show you tomorrow morning.
Ok sounds good
Where in the docs?
Well how does this work? https://github.com/chamburr/modmail/blob/main/utils/tools.py#L228-L284
They do something with bot.state? What even is that?
Is that built into the library or was that custom?
It seems like that's how they store the user tokens
But it doesn't look like they have a webserver
Sounds like some cache
But if they have no webserver, how are they getting the token?
I dunno
What if instead of having a select menu for it, I have a panel in the server, voiding having to do any of the oauth. The user would select Open Thread.
Up to you, but doesn't seem effective
I'm honestly open to ideas
I'm really increative when it comes to these things, that's why i didnt build my own stuff in Minecraft 
idk wtf im saying
Looks like they do have a web
Oh
i'm still getting the error.
led to load cogs.test: Extension 'cogs.test' raised an error: ImportError: cannot import name 'app_commands' from 'discord' (/home/pi/.local/lib/python3.11/site-packages/discord/__init__.py)
?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
in this case, you should uninstall pycord befeore re-installing
I just did this. still nothing
what IDE are you using
VSC
restart it
do you know how pycord slash commands work
not really. my first time working with pycord
import discord
from discord import app_commands
from discord.ext import commands
class ExampleCog(commands.cog):
def __init__(self, bot):
self.bot = bot
@app_commands.slash_command(name='ping', description='pong')
async def ping(self, ctx):
await ctx.respond('Pong!')
def setup(bot):
bot.add_cog(ExampleCog(bot))
https://guide.pycord.dev/popular-topics/cogs#creating-commands
https://guide.pycord.dev/interactions/application-commands/slash-commands
Learn all about Slash Commands and how to implement them into your Discord Bot with Pycord!
Cogs, often known as modules or extensions, are used to organize commands into groups. This is useful
this helped fixed the error. but now the slash command isn't even appearing. I will continue this tomorrow. thanks
.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.
I just got into bed and now it's working fine. Lol
I’ll have to add a db to my discord bot. I’d prefer an oop approach to a functional one. Currently have a MySQL database, but have access to a vps as well, which would allow my to use some kinda self hosted db as well.
How would you go about this? Which library would you use?
how do I exactly use delete_original_response? heres my code for example
@bot.slash_command(name="пурдж", description="Очищает указанное количество сообщений в указанном канале")
@default_permissions(manage_messages=True)
async def purge(
ctx,
количество: Option(int, description="Количество сообщений для удаления. По умолчанию - 10.") = 10,
канал: Option(discord.TextChannel, description="Канал, в котором нужно удалить сообщения. По умолчанию - текущий канал.") = None
):
if канал is None:
канал = ctx.channel
if ctx.guild.me.guild_permissions.manage_messages:
try:
deleted_messages = await канал.purge(limit=количество + 1)
await ctx.respond(f"Удалено {len(deleted_messages)} сообщений в канале {канал}!", ephemeral=True)
except discord.Forbidden:
await ctx.respond(f"У меня нет прав на удаление сообщений {saj_emoji}", ephemeral=True)
else:
await ctx.respond("У меня нет прав на управление сообщениями.", ephemeral=True)```
I dont really understand how it works, because I cant use just ctx.delete_original_response()
.rtfm discord.ApplicationContext.delete
yea I've seen the documentation
its just me being dumb
cuz I still dont understand
You need to use await ctx.delete() if you want to delete the response your bot sent earlier; if you want to use specifically delete_original_response(), use await ctx.interaction.delete_original_response(), since neither Context nor ApplicationContext classes have this method, and Interaction (can be gotten with ApplicationContext.interaction) does have it.
Also, just a recommendation: do not set Russian (or any lang other than English, which most programming languages are based on) variable/argument names, since that may be very inconvenient, misleading for other people especially, etc.
just set name="your_option_name" in your Option()
I didnt know that
thanks
(assuming your bot should be fully Russian)
Also, I can edit the interaction response, right?
thats insane
because last time
I remember myself developing a bot on pycord
it was impossible, or, maybe I was dumb
you can, with the same method (await ctx.edit())
maybe you used the different method or very old pycord version
maybe I did
I remember also that was one of the reasons I moved to discord.js
and started making a bot on javascript
but thats hella hard
when I compare it to python bot
you cannot really compare it to a python bot
and they all still doing the same at the end
Pretty sure you're just unused to it and/or that's just not your thing; there ain't a thing like "hard" or "easy", if you already learned and use the language. As Zervy have already said, they all still do the same at the end.
Should I add cogs with slash commands to bot(bot.load_extention()) before "on_ready()" or in "on_ready()"?
before
thanks!
how would i make the bot do something i tell it for example every 30 minutes
i saw somewhere that with sleep it will make events not working or whatever
or something like that
it will mess with the rest of the program
One of the most common operations when making a bot is having a loop run in the background at a specified interval. This pattern is very common but has a lot of things you need to look out for: How...
Concept
what if i want to run the same task multiple times
i got it working
can i only have 1 task runnijng at a time
then start multiple
Alright so very quick question
I have a on member join
I wanna sleep for 10 seconds and then check whether the member is still in
if i just use asyncio.sleep then check if member in member.guild.members, does that use the most-up-to-date version of the guild? or the one that was passed while the event was called?
It will probably be when the event was called
yea im testing rn, but i fear it is that
okay then
Does anyone have an updated/ just a working version of sending an embed as a dm to a user? i cant for the life of me get my code to work even though it has worked before...
I just keep getting "discord.errors.HTTPException: 400 Bad Request (error code: 50006): Cannot send an empty message" even though this is from the documentation for pycord.
"Cannot send an empty message"
I have an autocomplete that isn't searching properly. It populates the dropdown perfectly, but when a user starts typing one of the items instead of clicking on it, they receive "No Options Match your Search"
async def get_list_from_db(ctx: discord.AutocompleteContext):
user = str(ctx.interaction.user)
async with bot.db.cursor() as cursor:
await cursor.execute([sql command])
result = await cursor.fetchall()
stringsList = [i[0] for i in
result] # This takes the first item in each tuple from 'result' and converts it into a new list of strings
return [name for name in stringsList if name.startswith(ctx.value.lower())]
@bot.slash_command(name="post", description = "Post a character book")
async def autocomplete_example(
ctx: discord.ApplicationContext,
name: discord.Option(str, "Select a character", autocomplete=get_list_from_db),
)
Works fine if they just click it, but a lot of people have been trying to type it and I can't figure out why it won't work. Thanks in advance for any thoughts
- You might want to cache your result instead of making a call everytime they use autocomplete, you're spamming your dB.
- Probably lower
nametoo
Yeah I agree on the cache to optimize. Will work on that. Still though, why wouldn't the search work? In point 2 do you mean lowercase?
Yes
Lower all the items in stringslist
To then compare
Worked thanks! By the way, would you recommend cachetools (like here https://medium.com/@55swimmer55/the-power-of-caching-an-introduction-to-caching-within-python-sql-code-5cc29af4803d) or maybe something else?
No idea. I dont use such thing.
No problem, thanks anyway
why does it take a while for my slash command to register in a server?
like /ping is working but /translate is missing
.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.
Wrong tag whoops
@deft kestrel still there? ;3
if you're trying to import Option for Commands, it's
from discord.commands import Option
Hey, how can I create a slash command name with a blank space in between words instead of the _
I've tried
async def play_game(ctx: discord.ApplicationContext):```
won't let me run
you could use a slash command group
else you would have to use a - or _
Am I the only one having problems with pycord-dev?
check out #library-updates
;3
@slash_group.slash(name="command1", description="Command 1 description")
async def command1(ctx):
await ctx.send("This is command1!")```
like this?
Here's the slash cog groups example.
its also ctx.respond and not ctx.send
@little cobalt Is there a planned date for the update?
It is not possible to read the text in About me from the profile/server profile of a member on the server to check it for unauthorized words etc., is it?
afaik you can't, but you can access the users status text though
Yes okay, that's what I thought, thanks
Thank you, Zervy. It worked 🙌🏻
uninstall all other discord libraries and keep py-cord only
Will the member.guild.members use an up-to-date status of the guild?
Like, if the member leaves before the 20s pass, will the member still be in member.guild.members?
Any idea why is the except not working?
Because .ban doesn't raise and will never raise that exception.
.rtfm Member.ban
ctx.respond*
It only raises Forbidden or HttpException
Oh ok, thk
What is the var for dming a user from the bot been a bit since I was codeing.
is there a way to defer() modal responses?
so they fill out the form but the bot needs more time to respond
to the filled out modal
interaction.response.defer()
if Im not wrong
trying now thx
Do you know the answer to mine ?
you mean sending a dm message to a user?
.rtfm Member.send
@wild hill ^
Also what do the error AttributeError: '_MissingSentinel' object has no attribute mean?
Hi there, having a bot problem where I attempted to run a command while the code had an erroneous line in it, and now it is permanently stuck on (... Sending Command ...) despite restarting it several times.
Anyone has experience with this?
restart your discord
Me?
no
Hmm! Oh, that's embarrassing. Thank you. ^-^
How would I go about getting the title of a server that a command is called in?
Like the name of the server not the id.
or the docs :>
or that ;3
How would I define it in the function part as I am trying to store the name of the server and the mods name of the mod that warned said user.
The problem at saving the name is that you can change the name of the server or user
you should also store the server id
Also is FastAPI a good thing to use to make a dashboard with?
Why can't you say that?
What do you use?
I would use Flask
Do you know any good Tutorials that I can use to start off?
yea, but its in german x3
Is it possible to view webpages in Embed using a Bot?
What?
Hi guys, what should I do if I need to get, for example, 10 people using fetch_member, and 2 of them are not on the server and I need the bot to skip out, but the rest are not
In other words, I get an error Member not Found
guys can u help me pls?
when I view my account, there is no problem, the variables are translated into different languages (depending on the choice), but if I try to view another user's account, then the variables if result:
status = "Premium" if user_language == 'ru' else "Premium"
else:
status = "Free" if user_language == 'en' else "Free"
if member.id == id:
permissions = "Admin" if user_language == 'ru' else "Admin"
else:
permissions = "User" if user_language == 'ru' else "User" remain in Russian
Hello, this is an emergency if anyone can help me.
I'm running a task like this :
def __init__(self, bot: Hackbot):
self.bot = bot
self.update_teams.start()
@tasks.loop(minutes=5.0)
async def update_teams(self):
...
I get the following error : Extension raised an error: RuntimeError: There is no current event loop in thread 'MainThread'
It occurs in all my loop but i don't understand why since I didn't changed my working method and how I create them and still there's this error now
Thanks in advance for any help
how do i make two tasks looping at the same time?
Are you sure?
This is due to missing permission, it's not from the ban command.
To fix this, give the bot ban_members permission
You can literally see it's raising Forbidden
Read the docs and you will see.
I know, but it's litteraly administrator, I was trying to ban myself to make that you can't ban upper rank
ApplicationCommandInvokeError is from the error handler iirc. Not from the method itself
oh ok, I see
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 ...
If I have a listener for on_member_join, and do asyncio.wait(20) in it, and check the member's roles after those 20s using the passed member object, will that member object be up-to-date or be a snapshot of the time when the member joined?
.tias
I have both a on_error and an on_application_command_error handler. Yet, I still get errors that bypass either handler when clicking buttons. Is it possible to catch them too using a global error handler?
why is it that when I add a new slash command it takes forever to finally show up in the server?
on_error might catch them
Because registration of global command takes up to 10 mins
view.children is a list of all the items in your view
No.. objects don't get updated like that
You can get the member from cache for that
0
It's a python list so 0
It is a list.
how?
member.guild.get_member(...)
im p sure it worked in another command of mine like that lol
Then its from 0 to 23, "bruv"
Then it is from 0 to 23 lmao
Python isnt dumb
If its telling you out of range, then youre out of range
it might be dumb but it's definitely right
Is on_audit_log_entry guarantied to be called with logs in order from the oldest to more recent on the same Guild. In the doc, it says it is called as log are created, so can I assume it is called in the right order ?
How can I send an embed with a video?
You cant
thanks
It gets called when an audit log happens
Don't know what you mean called in the right order
Each event is one audit log entry
yes, but I mean if they are a lot of events at near the same time in the guilds, can the function be called in a different order that they where created initially in the guild. Example: 2 log are created one after the other, but for some reason, the bot receives the second one before for whatever reason like network
so what is this?
¯_(ツ)_/¯
it is called in order the log are created or in order the events arrives to the bot
I was able to find out. No the audit logs are not guarantied to arrives in order they are created. Discord can send them not in the right order
for web embeds. Think youtube.com links
It didn’t which is why I’m really confused
How to fix
cannot import name 'Option' from 'discord'
?
Can you show your pip list pls?
is it possible to get the ram usage of a specific shard ?
I'm tired as shit rn but i have an async def, so i need to do if await function() right
Not specifically using an if statement but sure you need to await it in an async environment
well the function returns a boolean
and it's all inside of an event which is async
so idk
Then sure
yea okay the main issue ended up being that i have a utils file, and within that file, i import discord.utils, and that messed things up a bit lol
why does ssl not working
Thats the most unspecific question ive ever seen
im sorry but this is the first time i get a error from ssl
Show the error
Traceback (most recent call last):
File "C:\Users\PC\OneDrive\Dokumente\coding\Smarthelpo\main.py", line 21, in <module>
client.run('')
File "C:\Users\PC\OneDrive\Dokumente\coding\Smarthelpo\venv\Lib\site-packages\discord\client.py", line 717, in run
return future.result()
^^^^^^^^^^^^^^^
File "C:\Users\PC\OneDrive\Dokumente\coding\Smarthelpo\venv\Lib\site-packages\discord\client.py", line 696, in runner
await self.start(*args, **kwargs)
File "C:\Users\PC\OneDrive\Dokumente\coding\Smarthelpo\venv\Lib\site-packages\discord\client.py", line 659, in start
await self.login(token)
File "C:\Users\PC\OneDrive\Dokumente\coding\Smarthelpo\venv\Lib\site-packages\discord\client.py", line 515, in login
data = await self.http.static_login(token.strip())
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\PC\OneDrive\Dokumente\coding\Smarthelpo\venv\Lib\site-packages\discord\http.py", line 418, in static_login
data = await self.request(Route("GET", "/users/@me"))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\PC\OneDrive\Dokumente\coding\Smarthelpo\venv\Lib\site-packages\discord\http.py", line 283, in request
async with self.__session.request(
File "C:\Users\PC\OneDrive\Dokumente\coding\Smarthelpo\venv\Lib\site-packages\aiohttp\client.py", line 1187, in aenter
self._resp = await self._coro
^^^^^^^^^^^^^^^^
File "C:\Users\PC\OneDrive\Dokumente\coding\Smarthelpo\venv\Lib\site-packages\aiohttp\client.py", line 574, in _request
conn = await self._connector.connect(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\PC\OneDrive\Dokumente\coding\Smarthelpo\venv\Lib\site-packages\aiohttp\connector.py", line 544, in connect
proto = await self._create_connection(req, traces, timeout)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\PC\OneDrive\Dokumente\coding\Smarthelpo\venv\Lib\site-packages\aiohttp\connector.py", line 911, in _create_connection
_, proto = await self._create_direct_connection(req, traces, timeout)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\PC\OneDrive\Dokumente\coding\Smarthelpo\venv\Lib\site-packages\aiohttp\connector.py", line 1154, in _create_direct_connection
sslcontext = self._get_ssl_context(req)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\PC\OneDrive\Dokumente\coding\Smarthelpo\venv\Lib\site-packages\aiohttp\connector.py", line 967, in _get_ssl_context
return self._make_ssl_context(True)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\PC\OneDrive\Dokumente\coding\Smarthelpo\venv\Lib\site-packages\aiohttp\connector.py", line 919, in _make_ssl_context
return ssl.create_default_context()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\PC\AppData\Local\Programs\Python\Python311\Lib\ssl.py", line 775, in create_default_context
context.load_default_certs(purpose)
File "C:\Users\PC\AppData\Local\Programs\Python\Python311\Lib\ssl.py", line 596, in load_default_certs
self._load_windows_store_certs(storename, purpose)
File "C:\Users\PC\AppData\Local\Programs\Python\Python311\Lib\ssl.py", line 588, in _load_windows_store_certs
self.load_verify_locations(cadata=certs)
ssl.SSLError: [ASN1] nested asn1 error (_ssl.c:4035)
Process finished with exit code 1
I want to create a slash command to set some configuration data.
Can I have the default value of the Option be its current value? If so, how can I reference that value from inside a Cog, because self isn't accessible within the decorator.
Hi everyone, i have a small issue.
I have a code where i store the ID of the last CategoryChannel created in a json file. When i read it i successfully get a CategoryChannel but when I try to execute the ̀create_text_channel function I get the following error : ̀'Object' object has no attribute 'create_text_channel'.
Does anybody knows why it's happening ? Thanks in advance 🙂
P.S. : I'm checking at the start and I get a good discord.CategoryChannel object by checking with type() function
Just handle it in your command callback
How do you mean?
@my_config.command('set')
async def config_set(
self,
ctx: discord.ApplicationContext,
cfg1: Option(int, default=?, min_value=0, max_value=99),
cfg2: Option(int, default=?, ...)
):
# Handle what and how?
My question was whether the default value could be changed in such a way that when the next end-user uses the command, any updated values will be the default presented value
...oh. I thought for sure the default was auto-filled. Well alright then.
Still wish there was a good way to make dynamic changes to Application commands, though. Discord could make these much more user-friendly.
For Command Groups using default_member_permissions, if you set something like manage_channels=True, does that only allow people who have global (Role) access to it, or would someone that has access to manage a specific channel be able to use that command?
Edit: Was able to quickly test. They can use it in channels they have the associated access to. Kinda neat, but also ruins what I'm trying to do (which is gate it without explicitly changing it from Integrations)
Heads up @ember flint! We've detected one or more tokens in your attachments!
- Found token of 1191231690446753803 (ultra mod) in attachment
message.txt. You can regenerate it here.
Fyi: Each token might trigger a system message by discord, if it's valid.
Please avoid uploading tokens in future, even if they aren't valid anymore.
Stay Safe!
try this article. FYI this is not directly a py-cord issue and is not due to issues in your code. You just have some installs wrong.
This error occurs when Python is unable to verify the SSL certificate of the website you are trying to access. This is a security measure to prevent ...
alr ty
import discord
from discord.commands import SlashCommandGroup, option
import json
from discord.ext import commands
intents = discord.Intents.all()
bot = discord.Bot(intents=intents)
# ------ 讀取json檔案 ------
def load_file(file_name: str) -> dict:
with open(file_name, 'r', encoding='utf-8') as files:
loaded_file = json.load(files)
return loaded_file
# ------ 儲存json檔案 ------
def save_file(file_name: str, data) -> None:
with open(file_name, 'w', encoding='utf-8') as file:
json.dump(data, file, indent=4, ensure_ascii=False)
@bot.event
async def on_ready():
await bot.change_presence(activity=discord.Game(name="廢土伺服器 | mcFallout.net"))
print(f'Logged in as {bot.user.name}')
check = SlashCommandGroup('check', '資料')
check_player = check.create_subgroup('player', '玩家')
async def get_ban(ctx: discord.AutocompleteContext):
ban_data = load_file('ban.json')
result_list = []
for key in ban_data:
result_list.append(key)
return result_list
async def get_mute(ctx: discord.AutocompleteContext):
mute_data = load_file('mute.json')
result_list = []
for key in mute_data:
result_list.append(key)
return result_list
@check_player.command(name='mute', description="取得指定被mute玩家的資訊")
@option(name = 'playerid',
description='你要查詢的玩家',
autocomplete=discord.utils.basic_autocomplete(get_mute),
required=True)
async def search_muted_player(ctx: discord.ApplicationContext, playerid):
await ctx.defer()
if playerid is None:
await ctx.respond('請輸入玩家 id')
return
elif playerid not in [target_player for target_player in load_file('mute.json')]:
await ctx.respond('這個玩家並沒有被封鎖,或這個玩家不尚未被紀錄')
return
else:
try:
mute_data = load_file('mute.json')
embed = discord.Embed(
title=f'玩家: {mute_data[playerid]["player"]}',
color=0x00ff00
)
embed.add_field(name='原因', value=mute_data[playerid]["reason"], inline=False)
embed.add_field(name='時間', value=mute_data[playerid]["time"], inline=False)
embed.add_field(name='連結', value=', '.join(mute_data[playerid]["links"]), inline=False)
await ctx.respond(embed=embed)
except Exception as e:
await ctx.respond(f'發生錯誤:\n{e}')
@check_player.command(name='ban', description="取得指定被ban玩家的資訊")
@option(name = 'playerid',
description='你要查詢的玩家',
autocomplete=discord.utils.basic_autocomplete(get_ban),
required=True)
async def search_banned_player(ctx: discord.ApplicationContext, playerid):
await ctx.defer()
if playerid is None:
await ctx.respond('請輸入玩家 id')
return
elif playerid not in [target_player for target_player in load_file('ban.json')]:
await ctx.respond('這個玩家並沒有被封鎖,或這個玩家不尚未被紀錄')
return
else:
try:
ban_data = load_file('ban.json')
embed = discord.Embed(
title=f'玩家: {ban_data[playerid]["player"]}',
color=0x00ff00
)
embed.add_field(name='原因', value=ban_data[playerid]["reason"], inline=False)
embed.add_field(name='時間', value=ban_data[playerid]["time"], inline=False)
embed.add_field(name='連結', value=', '.join(ban_data[playerid]["links"]), inline=False)
await ctx.respond(embed=embed)
except Exception as e:
await ctx.respond(f'發生錯誤:\n{e}')
bot.add_application_command(check)
bot.run('token')
why it doesn't show the options
for example, i use the code
@bot.slash_command(name="hi")
async def global_command(
ctx: discord.ApplicationContext, num: int
): # Takes one integer parameter
await ctx.respond(f"This is a global command, {num}!")
and it shows that
Ignoring exception in command hi:
Traceback (most recent call last):
File "C:\Python312\Lib\site-packages\discord\commands\core.py", line 131, in wrapped
ret = await coro(arg)
^^^^^^^^^^^^^^^
File "C:\Python312\Lib\site-packages\discord\commands\core.py", line 1006, in _invoke
await self.callback(ctx, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: global_command() missing 1 required positional argument: 'num'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Python312\Lib\site-packages\discord\bot.py", line 1133, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Python312\Lib\site-packages\discord\commands\core.py", line 381, in invoke
await injected(ctx)
File "C:\Python312\Lib\site-packages\discord\commands\core.py", line 139, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: global_command() missing 1 required positional argument: 'num'
Hello quick question I'm using v2.3.2 pycord
@commands.command()
async def reload(self, ctx, type, filePath="0"):
```|
but bot is giving me error
```'BridgeCommand' object has no attribute 'name'```
i have a command like this but it shows to people who dont have administrator aswell how can i make it not show to people who dont have administrator?
Any ideas?
You'll need to use @discord.default_permissions() for that
i just changed the things in the integrations tab
That works too, but then the change will only affect the server you changed it in
default_permissions is global
Well you can also use has_permissions
@plucky palm When we receive audio from discord in a voice channel, do we only get the data without any silence? If so, how can one interpolate the appropriate amount of silence between audio segments?
Silence is not included be default. This example should give you a start on adding the silence. https://github.com/Pycord-Development/pycord/blob/master/examples/audio_recording_merged.py Specifically line 81
why when i use slash command, it doesnt appear when i type /
is the slash command in a cog?
yes
How do you load the cog?
well yea, because commmands.command is a prefix and not a slash command
any solutions to make the slash commands work?
.rtfm slash_command
discord.commands.slash_command
discord.ext.commands.Bot.slash_command
discord.Bot.slash_command
discord.ext.commands.AutoShardedBot.slash_command
discord.Permissions.use_slash_commands
discord.AutoShardedBot.slash_command
discord.PermissionOverwrite.use_slash_commands
discord.ext.bridge.Bot.slash_command
discord.ext.bridge.AutoShardedBot.slash_command
.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.
@discord.slash_command(name="reset", description = "Reset all verification points.")
async def reset_verification(self, interaction: discord.Interaction):
data = self.load_counting_data()
guild_id_str = str(interaction.guild.id)
if guild_id_str not in data:
data[guild_id_str] = []
for user in data[guild_id_str]:
user[0] = 0
self.save_counting_data(data)
await interaction.response.send_message("All verification points have been reset.", ephemeral=True)
for example this command it doesn't appear in slash commands list
should the bot have slash command supports badge ?
What file are you using that in?
Cogs
I'm a tiny bit confused where to actuall put/define on_command_error to catch cooldown errors
Run pip freeze in your terminal and send the output here
Typically, I put it in a separate cog so it’s easy to find. Depends on how you want to categorize things. When using it in a cog, use @commands.Cog.listener() instead of @bot.event to define the listener.
gotcha
I guess you can have separate handlers per cog or just an overall catch-all?
depending on where you do it
keep in mind that on_command is for prefix commands and not slash commands
py-cord==2.4.1
oo, good catch. I'm trying to just have a reply for when a user uses a slash command on cooldown
instead of just erroring and saying the bot did not respond
No send the full output. If you can’t listen to simple directions then I’ll choose not to help you.
Hello, im getting this error:
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: classic() missing 1 required positional argument: 'custom'
while im trying to add optional parameters to this command:
from discord import option
@bot.slash_command(description='Starts a classic game')
@option(
"custom",
description="Set a custom time for the game to start.",
min_value=1,
max_value=120,
default=60
)
async def classic(ctx, custom: int):
# OTHER CODE
ive tried, reading docs, checking the official github examples but with no luck, what could possibly be the problem, or its just that the parameters take time to register?
is it in a cog?
nope
uninstall both, also uninstall and only reinstall py-cord
let me try rq
ive never looked at the @option decorator, i've always just done them inline. interesting
assume its slightly different functionality
you can use the @option or discord.Option or discord.commands.Option
yeah, same error, also to add on, the parameter doesn't show up when using the command
yeah I use discord.Option
Uninstall discord-protos and discord-py-slash-command, don’t know why you thought you needed those installed.
but i did try that too earlier and i got the same error, so i thought maybe it was outdated, checked github and switched
when applying a cooldown to a command its only applied when the command is properly invoked which means if any of the checks of the command interupted the cooldown will not be applied but i wanted it such that even when the check is executed it applies a cooldown to it so i did this
def func_cooldown():
def decorator(func):
@wraps(func)
async def wrapper(ctx: Context):
dt = ctx.message.edited_at or ctx.message.created_at
current = dt.replace(tzinfo=timezone.utc).timestamp()
bucket = ctx.command._buckets.get_bucket(ctx.message, current)
if bucket is not None:
retry_after = bucket.update_rate_limit(current)
if retry_after:
raise CommandOnCooldown(bucket, retry_after, ctx.command._buckets.type)
return await func(ctx)
return wrapper
return decorator
what i wanted to ask is ... is there a inbuilt way to do this or am i good to go with this method ?
you dont have to add required=True because it will be always True then if you havent set False
ig my error is unique
woo, got cooldown response working
^^
which py-cord version do you use?
i love how complicated this always looks but then it actually just works exactly like how you think it should
one thing i've noticed about this library lol
i use this: git+https://github.com/Pycord-Development/pycord
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - GitHub - Pycord-Development/pycord: Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API
i should probably make sure i'm on the latest pycord too, heh
i just worry about breaking things
...
whee, i get to make my first button. isn't it exciting

i changed my mind, brain not up to it rn
it's going to be quite an annoying button to build lol
Don’t think so, check the docs.
already have didnt find anything to do this thats why made my own decorator factory
should i go with this only ?
the code could be cleaner, but it looks like it works
The answer you provided was exactly what I was looking for. However, I also wanted to preserve the state of the command, as you mentioned in the comment. Is there any way through which I can do it?
Thanks! Btw is it true or is ChatGPT just hallucinating?
As far as I know discord only gives a split audio stream. ChatGPT is not good at discor dbot development stuff.
I've heard the same. So Discord should provide the metadata and hence the corresponding speaker name.. right?
yes
I couldnt find anything on setting "edit custom message" in automod block messages.
await guild.create_auto_moderation_rule(name='noWORD',
event_type=discord.AutoModEventType.message_send,
trigger_type=discord.AutoModTriggerType.keyword,
trigger_metadata=discord.AutoModTriggerMetadata(
regex_patterns=[f'{regex_word}']),
actions=[discord.AutoModAction(
discord.AutoModActionType.block_message, metadata
),
discord.AutoModAction(
discord.AutoModActionType.send_alert_message, metadata
),
discord.AutoModAction(
discord.AutoModActionType.timeout, metadata
)
],
enabled=True,
exempt_roles=None,
exempt_channels=None,
reason=f'bad: {word}'
)
also why does it seem like i need to add the same metadata 3 times?
metadata = discord.AutoModActionMetadata(channel_id=1078649685901856839, timeout_duration=timedelta(seconds=60)
Is it still unstable?
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - Pycord-Development/pycord
using bridge_commands cant we provide the description of an option ?
@bot.event
async def on_message(message):
block_words = ["fuck", "shit", "http://", "https://"]
for text in block_words:
if text in message.content:
await message.delete()
return
print('Cant Delete')
my bot has admin permissions so it should be able to delete the message but it doesn't
Which intents does your bot has?
Kind of, as discord does not send silent frames they are estimated. Also discord does not document it well so if they change something it could break.
i fixed it, thanks tho
how to disconnect someone from vc? didn't find the attribute in docs
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 ...
Just set the channel to none.
from what i read there is no such thing as "Ban duration", am i right?
@lapis dock while using bridge_command can we not give the options a description?
you can
can i get a quick example
if i use discord.Option
then it wont work as a prefix command uk
are you sure about that?
at the end you still could use @discord.option() instead the the other discord.Option()
ya like i had a command in which i had to have a limit of type int so if i give limit a type of option it wont work as normal prefix command since it will be unable to convert the given limit to an Option when using the command as a prefix command although i havent tried the same thing using @option decorator i guess that may work because in that i can just give the limit a type of int and then define it also as an option using the decorator
ya thats what i was gonna say
it may work with the decorator i suppose
Here's the slash options example.
@discord.option("member")
(ctx, member: discord.Member=None):
at the function
you could do it like that
ya thats what i was thinking
let me try that
Correct, Temp bans are just a normal ban and the bot must unban them after X time. They are not a built in discord feature
then if i wanted to make a tempban feature, i would need to use something like asyncio.sleep correct?
It depends on how long the tempban is. I think asyncio sleep only support 10-15 min. Otherwise you will need to store the end date and check ever once and a while (with ext.tasks) to see if they should be unbaned.
i tought about making the bot save the exact time a user should be unbanned in a .json file and make it check the file every once in a while but yea ill try it
thanks
that is the idea. just make sure that you check if the date has passed in case you dont check at the exact time they should be unbanned. Also
.tag nojson
JSON is a convenient and easy-to-read data storage protocol that's widely accepted by most programming languages. However, we caution against its use for storing and retrieving data in an asynchronous environment like a Discord bot. Don’t use json!
- It's a file-based data storage, which makes it vulnerable to race conditions
- You'll need to implement your own synchronization primitives to avoid corrupting data
- If you're not careful, you could accidentally wipe your entire JSON file.
Solution? Use a database. Recommended schema are SQLite, PostgreSQL, and MongoDB.
- Async libraries exist on pypi for each of these
sqlite --aiosqlite(or Danny's wrapper,?tag asqlite)
postgresql --asyncpg
mongodb --motor - Databases organize your data into tables, and are fast at inserting, retrieving, and removing records
- You can impose uniqueness constraints to ensure against duplication
- The Python libraries enforce synchronization for you
- The query language is intuitive, you can get running with simple queries in just a few hours!
yeah ill try tomorrow
thanks
while using bridge_commands if i want to send a message (not reply) (ctx.send) when its a prefix command which means its context would be BrideExtContext and when its a slash command at that time i just want to respond (ctx.respond) so would i have to check each time using the isinstance method that if the command was used as a prefix command and then instead of responding just send the message
also ctx.send doesnt cache the sent message so ctx.edit wont work i have to save the sent msg in a variable and then edit it later while at the same time when the command is used as a slash command at that time since i use ctx.respond therefore i am able to use ctx.edit later to directly edit the message for some progress updates but this way i contstantly have to keep adding the check if isinstacne(ctx, BridgeExtContext) ... so is there any alternative to this or will i have to go with this only
any idea why ?tag asqlite doesnt exist?
aiosqlite
you can basically use the sqlite docs and use whats there in aiosqlite. you only need to await some things, thats about all that changes
I have been trying to "interaction.response.edit_message" on an interaction I already responded to after a modal gets submitted, after doing a few operations on the modal's callback function and I am getting a "discord.errors.InteractionResponded: This interaction has already been responded to before" error.
Is there a way to simply edit the first response from a modal submission or the only way is by using "interaction.response.followup"?
can someone help me? its not recognizing discord_slash as a module even though i installed discord.py, discord-py-slash-command, and discord-py-interactions
This is py-cord, not d.py
do you know where i can get help on this
In the d.py server? 
do you have a link to it
Google does.
Ummm, We stole that tag from the discord.py server and we did not steal that tag XD. I will update that tag to just have the link to aiosqlite. No need to add a seperate tag. Thanks!
instead of isinstance you can use BridgeContext.is_app but otherwise that is the main way. For ctx.edit I do not think there is a better way. You could post a feature request (or even better a pull request) on the github.
Im not exactly sure how your code is setup but you can try to use Interaction.edit_original_response
otherwise interaction.followup.edit_message would be the way to go.
with the deleting of py-cord-dev, what version should we use in py-cord
The github version just like it was specified in the message.
oh but that is just the master branch, it is not unstable ?
It's not
I see thank you ! Will use that
interaction.edit_original_responseworked! Thank you 
i see ya because mostly bots dont like to respond to prefix command rather they just like to send the message using the ctx.send but that doesnt cache it therfore ctx.edit is not usable
if ctx.is_app():
await ctx.respond(embed=embed, view=view)
else:
await ctx.send(embed=embed, view=view)```
right now we will have to do this
also for the ctx.defer i would like it to be such that it only triggers typing if we pass that explicitly like ctx.defer(typing=True) otherwise it should just defer the normal slash command other wise again we will have to check if the command was used in an application context or ext context and respond accordingly
@lapis dock one more thing i would like to suggest is that when a view is orginated as a result of an interaction (not interaction.response.send_message only interaction.response.edit_message) at that time the views message is not set to the interaction.message automatically like it would have been set if the view orginated of a message command or as the reuslt of response.send_message same goes with when a view is orginated as a result of using ctx.edit in the context of Application Commands ... if the response to the command was something like ctx.defer() and later when we fetch some data and we use the ctx.edit and with this when we add a view also to the message the view.message doesnt get set and we explicilty have to set it like this .
view.message = await ctx.edit(embed=embed, view=view)```
one more thing while using the disable_on_timeout=True it obviously wont disbale in the cases when the view is orginated from a ctx.edit or interaction.response.edit_message since the self._message will be None as i mentioned above also if the view was a result of a message command and the view.message was set correctly even then if u delete the message and disable_on_timeout=True then the library will try to disable the view but since the message is deleted it will raise a NotFound error so i guess use a try xcept block over there
one more thing in slash commands if the input type is Member for an option then if u provide a user id to it (not a Member id) (someone outside of the server) then it is not going to raise the MemberNotFound error i myself have to add that check
if isinstance(member, User):
raise MemberNotFound(member)```
in prefix commands its does the job correctly it will raise the MemberNotFound error if the provided id was the id of user and not a member but in slash commands it doesnt raise the error
why commands.has_any_role won't work? i tried using name and id but nothing happens, like i don't have the required role (but i have it)
discord.ext.commands.errors.MissingAnyRole: You are missing at least one of the required roles: '['Gold', 1192424050857889843]'
Is there a utility function to let me quickly check if a string would violate a server's automod rules? Or, will I have to implement it myself?
The latter.
on_error Includes what errors? normal cmds, slash & app commands & interactions too? and even python errors?
errors during events
Is there a way to make the buttons that don't have time, when the bot restarts still working?
Here's the persistent example.
@valid panther
In the event that the button has time, for example, 3 hours and when it restarts, can it be made to continue working?
No, the timeout must be None
It's typehinting
label: str | None = None
str | None typehinting. Can be a str or None.
= None default to None, the arg isn't required.
ahhh.
Yeah makes sense
I always forget that python has logical operators as symbols as well
Smth like Label = str or None would work as well there
I already use a lot of stuff like that
but I just do ```py
text: str
data: dict
its also helping a lot at the IDE for more autocomplete
Great explanation, thx
slight nitpick, but str | None means it can be a string or not specified.
how does one use discord.ButtonStyle.link
Here's the link example.
Bascially have url= in your button creation
are hybrid groups supported in pycord?
yes, it just goes under a different name
Is there an alternate to not having a super long on_ready with a big verified bot that has 5.7k servers to have guilds cached so I can see a user’s mutual guilds with the bot accurately?
Having chunk_guilds_at_startup as True just doesn’t allow on_ready to fire since it takes so long, and I need on_ready to fire.
well, the bot is literally not ready
ok found them, it's bridges thanks
Umm in dpy we had commands.Author and we were able to use it as a default value for arguments
possible in pycord?
yes, how to call it depends on what it is though. could be message.author in an on message event, would be ctx.user in a slash command, may have some other variation in other listeners.. but its there
can you give me a example?
for a specific listener? or a slash command?
bridge command
scratches head
idk bridge command, sorry. Oh.. I missed your initial message.
oh ok
Sorry i wasted your time 😅
it's ok no worries
Its not a bridge command
its at the moment a prefix command
ctx.author will give you the author of the command for prefix, slash, or bridge. You will have to set that manually in the callback if user is None. Also like zervy mentioned, your command is currently typehinted as a prefix command. The correct typehint for a bridge command would be BridgeContext
I do wish that python understood that label: str = None inherently makes it optional. Having to put str | None = None on every pydantic member (for example) is fairly annoying.
Right i would do that, so basically i will have to do it in the callback itselves?
Yes
So... I have noticed that the master branch version is not adding the params to the slash commands at discord
its working fine if you just do pip install py-cord or a older master branch version
Is it true that the on_ready() function can be run several times? I just run tasks.loop() in my bot and later the console starts spamming with errors that tasks are already running(how to fix it?).
on_ready is can be run more than one time
To fix this you should start the task before bot.run. if you want the task to start only when the bot is read you can add
await Bot.wait_until_ready
Okay, I'll try it out. Thank you
When sending an image file into a channel with the bot, is there a way to get the file URL from it before actually sending the image? I wanted to add a "Share on Twitter" button to that message, containing a tweet intent link with some text and adding that image to the tweet, but for that I would need an image URL
(ctx, file: discord.Attachment):
url: str = file.url```
Is it possible to set a custom timeout date for AutoMod like you can with timing out a member through the API directly?
it'd be possible to get the link after sending the message and then edit it and add the button i'd say
i don't think you can get the link before actually sending the message 🤔
did you tried it? ;3
Here's what I'm trying to do:
# Prepare scorecard image as a file
scorecard_file = discord.File(io.BytesIO(scorecard_bytes), filename="scorecard.png")
# Send the success message with the scorecard image
await success_channel.send(file=scorecard_file)
# Generate the tweet intent link
tweet_text = "Check out my success case on PNL Bot!"
tweet_intent_link = generate_tweet_intent_link(tweet_text, scorecard_file)
Before actually calling channel.send(), I wanted to get a real URL for the file, so that I can add a view containing a link button with the intent tweet. I was wondering if there was a way to get it before sending the message, or the only way was by sending the image on the channel, then retrieve the URL that Discord will create automatically and then edit it with the view containing the link button.
your code is for a command, i think they asked for the case the bot uploads the picture
Yes, exactly. I should've sent the code snippet on the original question in the first place. I'm sorry, @little cobalt
You're not able to get the URL of the file before sending the message, I'm afraid
I think best would be to get the url after sending the message and then add the button
Okay, I kinda suspected that was the case. Just figured I'd ask, maybe there was I way 😄
Hmm, what would be the easiest way to get the image URL after sending the message?
You'd have to get them from the message:
message = await success_channel.send(file=scorecard_file)
attachments = message.attachments # Will give you all attachments
attachment = message.attachments[0] # Get the scorecard
Thank you! 
@commands.Cog.listener()
async def on_command_error(self, ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send("Falta un argumento requerido.")
await ctx.invoke(self.bot.get_command('help'), category=ctx.command.cog_name)
You'd have to get them from the message:
error:
Ignoring exception in on_command_error
Traceback (most recent call last):
File "/home/container/.venv/lib/python3.11/site-packages/discord/client.py", line 378, in _run_event
await coro(*args, **kwargs)
File "/home/container/cogs/excepsiones.py", line 82, in on_command_error
raise error
File "/home/container/.venv/lib/python3.11/site-packages/discord/ext/commands/bot.py", line 347, in invoke
await ctx.command.invoke(ctx)
File "/home/container/.venv/lib/python3.11/site-packages/discord/ext/commands/core.py", line 942, in invoke
await self.prepare(ctx)
File "/home/container/.venv/lib/python3.11/site-packages/discord/ext/commands/core.py", line 872, in prepare
await self._parse_arguments(ctx)
File "/home/container/.venv/lib/python3.11/site-packages/discord/ext/commands/core.py", line 774, in _parse_arguments
transformed = await self.transform(ctx, param)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/.venv/lib/python3.11/site-packages/discord/ext/bridge/core.py", line 94, in transform
return await super().transform(ctx, param)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/.venv/lib/python3.11/site-packages/discord/ext/commands/core.py", line 601, in transform
raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: member is a required argument that is missing.
I was creating an exception cog but the script for some reason doesn't want to handle the error:
commands.MissingRequiredArgument
and also try with:
commands.MemberNotFound
Well, you have a listener, you haven't overriden the original method, the error will still raise in the console.
thank you it helped me
one of the bots in the server that my bot is in sent a message and when I try to get their member object they come up as a user rather than a member of the guild why is that?
why would a bot not show up as a member?
there is no issue with normal members
@commands.Cog.listener()
async def on_message(self, message):
with Session(self.bot.DB) as session:
line 34> statement = insert(user).values(member_id=message.author.id, guild_id=message.author.guild.id).on_conflict_do_nothing()
session.execute(statement)
session.commit()
thisUser = session.query(user).filter_by(member_id=message.author.id, guild_id=message.author.guild.id).one_or_none()
thisUser.message_count += 1
session.commit()
I sent the wrong code at first whoops
message.guild
do you know why this would work normally for other members but not for this bots message in particular?
What you suggested did fix it. I should have been using message.guild from the beginning I'm not sure why I didn't think of that before, though I'm still curious why the previous code didn't work.
Is there an alternative to have guilds in the cache?
Cuz then I can't access guild.members, which is preventing user.mutual_guilds from being used.
Would
for guild in bot.guilds:
await bot.fetch_guild(guild.id)
cache the server members too?
Hi! Is there a maximal number of option choices? (discord.Option().choices)
should be 25
how would I go about making an option for a slash command that is a drop down
choices=[]
like say if for one option a user can set it to either on or off is there a way they can just click on or off rather than typing it
thank you
or autocomplete for other stuff
pretty sure it's called choices
I can't find any code examples for choices in the documentation
Here's the slash options example.
it does
here on the options section there's like no links linking to places where you can learn more
it's just like "this exists"
oh this is the guide site
that's confusing
mb
Yeah, guide site is different. We should add More info links at the bottom tho
@commands.slash_command(test_guild="1172086165332049980" , description="select whether you want to set the welcome dm or welcome channel message and attach your embed json")
@option("type", description="select whether this embed will be DM'd to the user or sent in the welcome channel", choices=["DM", "WC"])
@option("json", discord.Attachment, description="attach the embed json file you generated using the site embed.dan.onl", required=True)
async def set_welcome_message(self, ctx, type: str, attachment: discord.Attachment):
if attachment:
await ctx.respond("thanks!")
else:
await ctx.respond("you didn't attach a file!")
you dont need the check
oh I've just realized what my issue was before I even finished typing out the question lol
what do you mean
I mean the attachment check
oh will the command fail if they don't fill it
you would only need it if required=False
I see
they could not even run the command without a file
is there a way to send a custom mesage if they fail to add the attachment
oh I see
is there a way to specify a file type for attachments
nope
rip
it's kind of unfortunate how slash commands feel less conversational than non slash commands
oh nevermind what am I saying you can definitely make it conversational
is there a way to refresh the slash commands in my client without having to close and reopen it
Ctrl+r hard refreshes discord. I have had few problems with slash commands not updating though. When developing you should add debug guilds to your bot so that it is slightly faster.
It is a kwarg of bot
thanks I'll look into this
if i have made the help command using the HelpCommand class provided by the library how do we add the cooldown to that command ?
also i would like to make it a BridgeCommad
https://docs.pycord.dev/en/stable/api/clients.html#discord.Bot.owner_id
Than you need to fetch the user with get_or_fetch_user
@vestal folio
Bots: Attributes activity, allowed_mentions, application_flags, application_id, auto_sync_commands, cached_messages, cogs, debug_guilds, description, emojis, extensions, get_command, guilds, intent...
Yes, read the second part
The user object you fetch will have the name
.rtfm User.name
you could always chunk the guilds after the bot starts up
i think the only way would be if you have the guild ids stored somewhere, i may be wrong about that though. but i manually chunk my main server as i need that for some of my admin commands
i can not play a sound by my bot
the bot connect to lavalink but there is no sound
i have PyNaCl
lavalink and pycord
installed
is it possible to get "segments" of the audio data that the sinks have or do i have to make the bot leave to get a workable file
Fixed it
how do I make a discord.HelpCommand recognize slash commands
Is there a way to let the InputText fields on a Modal only accept numeric values in a specific range? Other than validating the user input after they submit the modal, of course.
No
Okay, just wanted to confirm it. Thank you, thank you 
its only str
Can we rebuild an Interaction object from it's ID? Motive is to defer the interaction, store in DB, and respond later
How much later are we talking about?
Interactions are not supposed to be deferred indefinitely... They should be responded to immediately, the defer is just for some computations that take a bit longer than the default time.
Also I think I read somewhere that interactions (even deferred) become invalid after about 15 mins or so.
Correct
anyone knows how to sort to mathcing options with autocomplete context? (theres a list, when they write, only the elements that has a matching part with the input shows up)
I think that's automatically done by the discord client
hmm ty
do you use autocomplete or choices?
autocomplete
Did you make your own autocomplete function?
yes
Then you have to return a parsed list by yourself
It's pretty much return [value for value if ctx.value.lower() in value]
Here's the slash autocomplete example.
here's another question: how do i know if the user invoked the slash version or the prefix version of the command in bridge commands?
You can check it with is_app
how do you add your bot to the menu when you right click a message and it shows there in Apps
Here's the context menus example.
@deft kestrel
thank you!
#💩posting
Figured it
But, shimmy shimmy yay yay
If I have a text saved in a variable, how would I go about sending that text as a file instead
I don't want to create a file, but I want to send it as a file on discord
You have to convert it to a file first
I guess so
Did discord ever add a way to check how a member joined, through the API? Or is that still something we have to find and store ourselves?
You still need to track invites yourself
how can i make modals?
Learn how you can implement Modals in your Discord Bot with Pycord!
How can I make a slash help command that recognizes slash commands?
use bot.commands
use that arg
Ignoring exception in on_ready
Traceback (most recent call last):
File "C:\Users\jarex\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 378, in _run_event
await coro(*args, **kwargs)
File "C:\Users\jarex\Downloads\TOOLS\Jarexs Tools\terracord\bot\terracord.py", line 36, in on_ready
await connect_nodes()
File "C:\Users\jarex\Downloads\TOOLS\Jarexs Tools\terracord\bot\terracord.py", line 14, in connect_nodes
await wavelink.NodePool.create_node(
AttributeError: module 'wavelink' has no attribute 'NodePool'```
Following the wavelink doc and i get thsi
Quick question: how can I respond to a deferred interaction with sending a modal?
you can install PyNaCl manually
You physically cannot. However, there are alternatives such as sending a button to send the modal instead.
What are some reasons why a bot takes so long to respond to an interaction? My hosting service provides 40 GB SSD Storage, and 3 GB RAM. Here is my code:
# main.py
@client.event
async def on_interaction(interaction):
await client.process_application_commands(interaction)
Ready = False
async def on_ready():
global Ready
if not Ready:
Ready = True
for document in Load("Channels"):
for messageID in document["CustomIDs"]:
view = discord.ui.View(timeout=None)
for button in document["CustomIDs"][messageID]:
view.add_item(classes[button](**document["CustomIDs"][messageID][button]))
client.add_view(view, messageid=messageID)
print("Bot now online!")
for category in os.listdir("./commands"):
for commandtype in os.listdir(f"./commands/{category}"):
for command in os.listdir(f"./commands/{category}/{commandtype}"):
if command.endswith(".py"):
client.load_extension(f"commands.{category}.{commandtype}.{command[:-3]}")
print(f"Loaded {category}.{commandtype}.{command[:-3]}")
print("Starting bot...")
client.run(os.getenv("token"))``````py
# commands/slash/utilities/ping.py
class Ping(commands.Cog):
def __init__(self, client):
self.client = client
@slash_command(description="Provides the bot's latency")
async def ping(self, ctx):
await ctx.respond(embed=SetEmbed(ctx.guild,
"Pong!",
f"Executed in **{round(self.client.latency * 1000)}** ms!",
discord.Color.green()))
def setup(bot):
bot.add_cog(Ping(bot))```
When I run `/ping`, it may not always return an embed, and instead return `InteractionNotFound` Error. There is nothing in the code that I think makes the interaction response take a long time to respond, yet it still throws an error anyway.
When /ping does respond, the latency is 1 ms
In other words, what are some causes that prolong the duration an application responds to a slash command?
Network speed
to get the default colour of the banner is with the colour = ctx.bot.user.colour ?
No
You can't get that colour as far as I am aware.
Could your hosting provider suspend the VPS when it is seeing no traffic and the wake-up time is longer than the allowed interaction response time?
🥲
Hey there, I need quick help to use the ID of message / reaction because I do not understand why my code isn't working. Can I message there or should I create a thread ?
I also wanted to ask what's the point of using bridge command and what's the difference between these and normals command since I never used them
Create a thread
#main.py frfr
monitored_channels = [1185369048456904805, 1185355137187844107, 1185354638325715095, 1185355055713497249, 1185354338420400279]
@client.event
async def on_message(message):
if message.channel.id in monitored_channels:
try:
await message.add_reaction('⭐')
except discord.Forbidden:
print("Bot doesn't have permission to add reactions in the monitored channels.")
await client.process_commands(message)
Why dosent this work
What is wrong with it
No error message, it just dosent work
Do you have message intents?
Yes it used to work. But when I switched hosting softwares it just stopped
How many funcs called on_message do you got
Anyone got a recommended solution for Persistent View's not always being loaded / randomly resulting in failed interactions?
This is not due to an issue in the view itself.
I initilise all persistent views via an on_ready() event listener.
Should I do this in a loop instead?
Please reply with ping. Thanks
Hi guys I have a quick question: is it possible for a Select to keep the user's choice displayed after the callback ?
When I select something, the Select.values are correct and I can use them as expected, but at the end of the callback the Select goes back to it's label (I thought maybe by iterating through the options and setting their default attribute to True if they're selected but I wanted to know if I'm doing something wrong or if it's the normal behavior.
Thanks
did you set min and max value at the select?
yes
do you edit the select in any way?
class OrganisationSelect(discord.ui.Select):
"""Allows the user to choose one or several diving organisations"""
def __init__(self):
self.view: Menu1
options = [x.get_select_option()
for x in database.db.static_data['orgs']]
super().__init__(
placeholder='Fédérations',
min_values=1,
max_values=len(options),
row=0,
options=options
)
# Overriding the callback method
async def callback(self, interaction: Interaction):
# Selected certifications
selected: list[CertificationOrganisation] = [
await CertificationOrganisation(int(x)) for x in self.values
]
# To only show certifications from the selected organisation(s)
possible_certif = set([certif.id
for orgs in selected
for certif in orgs.certifications])
self.view.diver.organisations = selected.copy()
# As the certifications depend on the organisation, changing org select
# will reset eventual certifications selected.
if self.view.certif_select.values is not None:
self.view.certif_select.values.clear()
self.view.diver.certifications.clear()
# Updating the choices offered in the certifications
self.view.certif_select.update_certifs([await Certification(x)
for x in possible_certif])
# Updating the view
await interaction.response.edit_message(view=self.view)
When selecting
After the selection (PADI and SSI are not shown and I would like them to stay so the user doesn't think its actions didn't work)
(and the callback worked since the "Niveaux" Select is no longer disabled and offers the right choices) (sorry it's in french)
Added this bit to the first Select callback and it works, I was just wondering if there's another "cleaner" way
# Updating the view and keeping the user's choices selected
for opt in self.options:
if opt.value in self.values:
opt.default = True
and you have the newest py-cord version?
❯ pip list | grep "py-cord"
py-cord-dev 2.5.0rc5
it's probably because I edit the message
but idk how to modify the second Select without doing it
Here's the modal dialogs example.
@cog_ext.cog_slash(
name="songrequest",
description="Request a song and share it with others",
options=[
create_option(
name="artist",
description="The name of the artist",
option_type=SlashCommandOptionType.STRING,
required=True
),
create_option(
name="song",
description="The name of the song",
option_type=SlashCommandOptionType.STRING,
required=True
)
]
)
``` how can i do that in pycord?
Here's the slash cog example.
@cunning stirrup
DEBUG:asyncio:Using selector: EpollSelector
INFO:root:Starting bot
WARNING:discord.client:PyNaCl is not installed, voice will NOT be supported
INFO:root:CasinoHoldem cog initialized
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 817, in _match_option_param_names
p_name, p_obj = next(params)
StopIteration
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord/cog.py", line 789, in _load_from_module_spec
setup(self)
File "/home/container/cogs/casinoholdem.py", line 25, in setup
bot.add_cog(CasinoHoldem(bot))
File "/home/container/.local/lib/python3.10/site-packages/discord/cog.py", line 659, in add_cog
cog = cog._inject(self)
File "/home/container/.local/lib/python3.10/site-packages/discord/cog.py", line 548, in _inject
command._set_cog(self)
File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 609, in _set_cog
self.cog = cog
File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 855, in cog
self._validate_parameters()
File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 713, in _validate_parameters
self.options: list[Option] = self._match_option_param_names(params, kwop)
File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 819, in _match_option_param_names
raise ClientException("Too many arguments passed to the options kwarg.")
discord.errors.ClientException: Too many arguments passed to the options kwarg.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/container/bot.py", line 36, in <module>
asyncio.run(main())
File "/usr/local/lib/python3.10/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "/usr/local/lib/python3.10/asyncio/base_events.py", line 649, in run_until_complete
return future.result()
File "/home/container/bot.py", line 33, in main
bot = Bot()
File "/home/container/bot.py", line 23, in __init__
self.load_extension(cog_name)
File "/home/container/.local/lib/python3.10/site-packages/discord/cog.py", line 913, in load_extension
self._load_from_module_spec(spec, name)
File "/home/container/.local/lib/python3.10/site-packages/discord/cog.py", line 794, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.errors.ExtensionFailed: Extension 'cogs.casinoholdem' raised an error: ClientException: Too many arguments passed to the options kwarg.``` whenever i try to add a slash command im getting this exception and not sure exactly why
import discord
from discord.ext import commands
from discord import ApplicationContext, Option
import logging
class CasinoHoldem(commands.Cog):
def __init__(self, bot):
self.bot = bot
logging.info("CasinoHoldem cog initialized")
@discord.slash_command()
async def test(self, ctx):
await ctx.respond('This is a test.')
def setup(bot):
bot.add_cog(CasinoHoldem(bot))```
Here's the slash cog example.
@lofty hedge
Hello 👋 can some one provide me a code-snipped for a /-command that provides a list of choices.
Or ist that only possible as modal?
I have tried it by my self... but with no success... :(
Here's the slash options example.
Wrong example, my bad
this is not your fault, it's a bug, it will be fixed with the latest pull request
utilitys = terracord.create_group(name="utilitys", description="Utility commands!", guild_ids=[1198059337751474276])
class Verify(discord.ui.Modal):
def __init__(self, ctx, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.ctx = ctx
self.captcha = discord.ui.InputText(label="Captcha", placeholder="Enter Captcha")
self.add_item(self.captcha)
async def callback(self, interaction: discord.Interaction):
if self.captcha.value.lower() == "TeRrAcOdE":
role = discord.utils.get(self.ctx.guild.roles, name="Terrarian")
await interaction.user.add_roles(role)
await interaction.response.send_message("Verification successful! You've been granted the 'Terrarian' role.", ephemeral=True)
else:
await interaction.response.send_message("Incorrect captcha. Please try again.", ephemeral=True)
@utilitys.command(name="verify")
async def verify(ctx):
if ctx.author.guild_permissions.administrator:
embed = discord.Embed(
title="**TerraCord Verification!**",
description="`Please Follow The Captcha So We Can Prove That You Are Not A Robot!`",
color=discord.Colour.green()
)
embed.set_image(url="https://i.imgur.com/3l2Sh41.jpg")
embed.set_thumbnail(url="https://terracord.site/images/icon.png")
view = discord.ui.View()
button = discord.ui.Button(label="Verify", custom_id="verify_button")
view.add_item(button)
await ctx.send(embed=embed, view=view)
else:
await ctx.send("You don't have the required permissions to use this command.", ephemeral=True)
@terracord.event
async def on_button_click(interaction: discord.Interaction):
if interaction.custom_id == "verify_button":
verify_modal = Verify(ctx=interaction)
await verify_modal.start(interaction.user)
I dont get any errors i just get this interaction failed
Py-cord does not have a event with on_button_click
not entirely sure what terracord is 🤔
Terracord?
That's just what he named his bot instance
oh yea
Hey, can someone tell me how to check the ID of the message a user has replied to
For example, im replying to t he above msg, the bot should give me the ID of the above message
(1199730370384507122)
.rtfm Message.reference
ah it's called reference. Thanks
What about the author of the message?
You get/fetch the message and get the author.


