#Basic Pycord Help
1 messages · Page 66 of 1
lol
i just removed it
I'm almost certain it's something weird with that db package
could you share all of the code? With the try and except blocks
Use something like https://mystb.in/
I'd say try to switch to something like async mysql but not sure if you can do that easily
otherwise sqlite never fails
Can you try running the database script separate from the bot. Just fill in DM data instead of a message
Describe the bug I'm trying to get some data from my surreal database but every queries to tables where there are datetimes return ('no decoder for tag', 12) Steps to reproduce Here is ...
Describe the bug Using async client on SDK 0.4.1 and surrealdb 2.1.4, when I create records on schemaless table everything works fine. The moment I defined a field with a VALUE set, I can no longer...
lol, yesterday
i am trying to use datetime
maybe i need to roll back a few versions. this used to work fine in the past
Describe the bug The library code contains a very (very!) A dangerous call: surrealdb.py/surrealdb/connection_ws.py Line 112 in d72ffcc asyncio.get_event_loop().stop() Whenever surrealdb doesn'...
someone made PR draft for it
WEBSOCKET
brb making it an http connection
progress, just battling with it saying my namespace isn't set. which is a lie
https://github.com/surrealdb/surrealdb.py/issues/137
Have you hit every single bug XD
Describe the bug There was a problem with the database: There was a problem with authentication Steps to reproduce db = AsyncSurrealDB(url=url) await db.connect() await db.use(namespace=namespace, ...
i KNEW it
Is there any built-in method for implementing cooldowns?
I want to add level system and xp will come from messages. And I want to somehow stop spam-abuse
Yes
.rtfm cooldown
discord.ext.commands.Cooldown
discord.ext.commands.Cooldown.copy
discord.ext.commands.Cooldown.get_retry_after
discord.ext.commands.Cooldown.get_tokens
discord.ext.commands.Cooldown.per
discord.ext.commands.Cooldown.rate
discord.ext.commands.Cooldown.reset
discord.ext.commands.Cooldown.update_rate_limit
discord.ext.commands.CommandOnCooldown
discord.ext.commands.CommandOnCooldown.args
discord.ext.commands.CommandOnCooldown.with_traceback
discord.ext.commands.Command.cooldown
discord.ext.commands.Command.get_cooldown_retry_after
discord.ext.commands.Command.is_on_cooldown
discord.ext.commands.Command.reset_cooldown
discord.SlashCommandGroup.cooldown
discord.SlashCommandGroup.get_cooldown_retry_after
discord.SlashCommandGroup.is_on_cooldown
discord.SlashCommandGroup.reset_cooldown
discord.UserCommand.cooldown
The following section outlines the API of Pycord’s prefixed command extension module. Bots: Bot: Attributes activity, allowed_mentions, application_flags, application_id, cached_messages, case_inse...
discord.ext.commands.Cooldown
discord.ext.commands.Cooldown.copy
discord.ext.commands.Cooldown.get_retry_after
discord.ext.commands.Cooldown.get_tokens
discord.ext.commands.Cooldown.per
discord.ext.commands.Cooldown.rate
discord.ext.commands.Cooldown.reset
discord.ext.commands.Cooldown.update_rate_limit
discord.ext.commands.CommandOnCooldown
discord.ext.commands.CommandOnCooldown.args
discord.ext.commands.CommandOnCooldown.with_traceback
discord.ext.commands.Command.cooldown
discord.ext.commands.Command.get_cooldown_retry_after
discord.ext.commands.Command.is_on_cooldown
discord.ext.commands.Command.reset_cooldown
discord.SlashCommandGroup.cooldown
discord.SlashCommandGroup.get_cooldown_retry_after
discord.SlashCommandGroup.is_on_cooldown
discord.SlashCommandGroup.reset_cooldown
discord.UserCommand.cooldown
okie
@cobalt bone What exactly do you mean?
You have to send a message, but your message does not have to have any content other than the view
I'm in the process of creating a help post on the subject.
👍
what is a point of that ?
If I'm manually handling my interaction responses. do I need to do something about the callback method on the modals to regain control over the response?
nevermind, I read the source code
I think it is for http only bots.
You can have discord send interactions to your webserver instead of having a gateway connection
@round heart moving here to not hijack
Discord gives you a temporary "interaction token" that is valid for 15 minutes. You can use that specific token for 15 minutes. If a user interacts with your view you get a new interaction with a new token.
🤔 Does user code have to care about that in any way? I feel like I've had views where interaction after 15 mins was just met with 'interaction failed'
Everytime a user interacts discord sends a new token you can use for 15 minutes. But you cant have a button that when pressed waits an hour before editing the message without doing extra stuff
extra stuff
ok
Is that documented anywhere so I don't ask redundant questions? I've never seen a mention of that (but also didn't go looking for it)
(Outside of a persistent view, which isn't necessarily what I'm looking for, either.)
I feel like I've had views where interaction after 15 mins was just met with 'interaction failed'
Your bot still has to be listening for the interactions discord sends. I think the default timeout (before pycord stops listening) is 5 minutes. But you could make this as long as you want.
They were with Views with timeout=None
I guess what I'm asking is that you shouldn't need to do anything in Pycord to account for this new token, and that interactions should seamlessly work after 15 mins because it's generating that new token?
hey guys, is there an implementation of the bot.wait_for function that exactly is like that but doesn't take in an event parameter?
I need to wait until a certain condition has reached
What condition?
when a certain list reaches a length
it has to "block" until a certain condition has passed
I suggest you could subclass list or create a list handler class that accepts a callback and a condition.
Where does the list come from
Like how is it edited
I am using the list as a kind of "pointer" that is shared between multiple views (the views are all the same kind of views)
I share the list with every view so that they can modify it
and yeah every view has a timeout aswell, which will still append something to the list
Kind of structure:
class SomeView(View):
def __init__(self, ptr_list: list, *args, **kwargs):
super().__init__(*args, **kwargs)
self.ptr_list = ptr_list
# Here are some buttons that'll append things to the list
confirmations: list[bool] = []
for user in members:
channel: discord.TextChannel
await channel.send(user.mention, view=SomeView(confirmations, timeout=...))
I could technically wait until the timeout has reached
but I just want to directly continue after the length of confirmations has been met
I know I am a littlebit vague
import asyncio
from typing import TypeVar, Generic, Optional
T = TypeVar('T')
class WaitingList(list, Generic[T]):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._length_futures: dict[int, asyncio.Future] = {}
def append(self, item: T) -> None:
super().append(item)
# Check if we have any futures waiting for this length
new_length = len(self)
futures_to_resolve = [
(length, future)
for length, future in self._length_futures.items()
if length <= new_length
]
# Resolve all futures that are waiting for this length or less
for length, future in futures_to_resolve:
if not future.done():
future.set_result(None)
del self._length_futures[length]
async def wait_for(self, length: int, timeout: Optional[float] = None) -> None:
"""
Wait until the list reaches the specified length.
Args:
length: The length to wait for
timeout: Optional timeout in seconds. If None, wait indefinitely
Raises:
asyncio.TimeoutError: If the timeout is reached before the list reaches
the specified length
"""
if len(self) >= length:
return
# Create a future if we don't already have one for this length
if length not in self._length_futures:
self._length_futures[length] = asyncio.Future()
try:
await asyncio.wait_for(self._length_futures[length], timeout=timeout)
except asyncio.TimeoutError:
# Clean up the future if we timeout
if length in self._length_futures:
del self._length_futures[length]
raise
# Example usage:
async def example():
waiting_list = WaitingList[int]()
# Start waiting for length 3
wait_task = asyncio.create_task(waiting_list.wait_for(3, timeout=5.0))
# Append items with delays
await asyncio.sleep(1)
waiting_list.append(1)
await asyncio.sleep(1)
waiting_list.append(2)
await asyncio.sleep(1)
waiting_list.append(3)
# Wait for the wait_task to complete
await wait_task
print(f"List reached length 3: {waiting_list}")
# Run the example
if __name__ == "__main__":
asyncio.run(example())
Made this real quick w / chatgpt claude
oh god
Also this only works when you explicitly use .append
oop aha
You could also check for len repeatedly but that would be inefficient
Or another option
gonna review the code since ai can't do anything usefull these days
Yeah, but I'm pretty sure that's how I would have done it, especially since I told claude how to do it specifically
@lapis dock were you about to reply to me?
would be to make everything after the "wait_for" in another async function, and in the view, in every place where you .append, check for the list's lenght and call the function if applicable
aha so I must make one Instance of WaitingList
yes
It subclasses list
so it does everything a list does
plus
wait for
and some shenanigangs in .append
everything else it will behave exactly like any list
aha and append has been overwritten I suppose
there's __add__ i think or something like that
when you add it another way
that's possible
nuh I am planning to just use the append method
yeah there is
also uh just reading it quickly cant you just create a task loop that checks the list every few seconds
I don't think so
why "think"
I am gonna reply to your message
But that's not efficient at all
technically I could also use a while loop if asyncio allowed me
Nor reactive at all
It does
You will always use the new token in the interaction object passed to your callback.
class MyView(discord.ui.View)
def __init__(self, original_interaction):
self.original_interaction = original_interaction // This is the interaction that is used to send the view
super().__init__(timeout=60*3)
@discord.ui.button(label="Hi")
async def hi(self, button, interaction):
// This will work as long as pycord is listening for interactions on this view
await interaction.respond("Hi")
async def on_timeout(self):
// This will only work if the view was sent less then 15 minutes ago.
await self.original_interaction.edit(view=self)
// You could choose to update self.original_interaction everytime you get an interaction and this would allow this to work as long as it was with 15 minutes of the most recent interaction
I think this is a more clear explanation that I am pretty sure is accurate.
Also a note: Py-cord treats timeout as time since last interaction, not time since it was sent. So the timeout can keep being extended
But you would need to asyncio.sleep()
Is that possible
instead of time
The thing is if you don't wait at some point in your loop it would really consume ressources
And be blocking
Now that you mention, I do recall that interactions extend the timeout. But what is the answer for when it's been around for, say, 20 minutes without any interaction in the meantime?
ill just hold on your modified list
if you wait in it with some await asyncio.sleep it would technically be fine
but still not really efficient or reactive
If you try to edit it (without an interaction) it will not work unless you have fetched/cached the message is some other way. At that point it would also require you to have the view channel permission.
gibberish
Okay, so my earlier suggestion of setting a .message property on first interaction may not be terrible...
help
why did it uses non breaking spaces lool
oh wait no
It's me
bc when I copy pasted
I selected the text
smart you
it's an issue with the interface
yuh it doesnt render markdown correctly
Yeah @echo wraith, hope your code doesn't suck
Feeling the pressure rn
i dont mean it like that*
it's fine haha
publishing it directly to production is the best way to determine if there are errors or not ig
I guess it might be possible to have py-cord keep track of the most recent interaction (if it does not already, I did not look like it did) and try to use that when possible. My brain kinda hurts from thinking about this though, so I dont exactly know how it would be implemented
3 more minutes and I can test something. I have a simple View with a button that just ephemerally replies. I need to know for certain wether it still works after 15 mins. (or if my issue is just with editing the message, which I'm not currently testing)
Interesting. So it's not that; clicking the button yielded the expected reply. Must just be message editing. Time to test that.
ephemerally messages are only accessible through the original interaction I believe.
I believe you're right. But right now the original message is public
so this is my example View
class TestView(discord.ui.View):
def __init__(self):
self.number = 0
super().__init__(timeout=3600, disable_on_timeout=True)
@discord.ui.button(label='Test', style=discord.ButtonStyle.green)
async def test(self, button: discord.ui.Button, interaction: discord.Interaction):
self.number += 1
await interaction.edit(content=f'Clicked {self.number} times', view=self)
.. interaction.edit_original_response is not the right method, apparently. Update: It's interaction.edit()
This is why we need a visual guide on which methods to use for which situation 😅
See you in 16 minutes
I am going to make a comprehensive visual guide rn. I have wanted to for so long and after explaining everything I have somewhat confused myself as well
Just in case you're interested in ideas, https://github.com/Pycord-Development/guide/issues/476 contains my personal wishlist for items to include.
Now I too am confused. It continues to modify the message just fine, even 30 mins later 
I was sure It would mhhhm :
Claude never makes mistakes.
... actually I am curious how much better Claude is for python than ChatGPT. I've actually not used Claude much
I use a lot of ChatGPT so I dont have to search everytime it at the Internet if I need something xd
Oh, for sure. Sadly ChatGPT is not super helpful with Pydantic because it insists on v1, or Pycord because it still conflates it with d.py, but for generalized stuff (especially on using comprehensions) it works well.
human's brain works the best
Not mine, sadly
supposedly, gemini is the best for coding rn i think
From my subjective point of view, claude is much better
even compared to openai's o1
like o1 can sometimes solve better complex algorithmical problems
but claude is way better at acutally not wanting to rewrite your entire codebase
and it feels less weird overall
Actually, interestingly enough self.message is visible here (but of course using self.message.edit method doesn't mark the interaction responded).
hello - is it easy to use a rate limit warning message to work out exactly what call is being rate limited?
990888169610285056:None:/channels/{channel_id}/messages/{message_id}
this one was for 13 minutes... and just had another for 19 mins. Not ideal!
fetching messages
thanks, is there a quick reference that gets you that answer?
the api path you sent is the one for fetching messages
you can find all of them here
dont use fetch message, rely on cache as much as possible
I'm using get most of the time - in this case I'm trying to establish whether a user has deleted the message sent through a webhook? if there's a better way would be very happy
https://docs.pycord.dev/en/stable/api/clients.html#discord.Bot.get_message always use this first
and then to edit the message sent through the webhook? The partial doesn't allow much to be done
the bot sends messages through webhooks, and then updates those messages periodically. To edit the message, as far as I can tell, I have to fetch the message?
do you have to send messages with the webhook for your use case?
I think so, yes
the bot can't join the other servers
in my test case I'm only fetching four messages in ~2 seconds
a 19 minute limit seems a bit intense
i mean.. if you fetch them once thats enough already, because then you could just manually save the message object
and how often do you fetch them anyway
once an hour
hadn't realised fetch was so frowned upon! I can work in saving the objects and only fetch them at startup
sloooowly
yea i have no clue about webhooks
but yea fetching bad cause fetching is slow and counts towards ratelimits
@commands.cooldown(1, 300, commands.BucketType.user)
does this not work with on_application_command_error()
command just says "Not responding", but prints in console that its on cooldown
i changed nothing and my autocomplete stopped working #1330459008569704478
I am trying to perform a command with a cooldawn, but the cooldawn is null in the case that a user has the role x. The problem is that the decorator works correctly, but does not apply the action. That is, it assigns cooldawn to all users, even if you have the bypass role. Has this happened to anyone else
i think using a dynamic cooldown is easier for that
Sorry for the question, could you give a simple example? 
np
what's more optimized: saving data about cooldown in json fine directly in bot's directory, or use database for it? I'm between those stupid and shitty solutions because I don't know how to implement cooldown for discord users other way
Can a bot use another bot's emojis
Nope, I think teams are only for developers
@frozen silo either use the built in cooldowns or use a cache db like redis. You can see a custom cooldown implementation above
.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: 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!
you should really use the built in ones if it's about command cooldowns tho, as it's all kept in memory as well
pymongo 4.X.X has AsyncMongoClient now, so you dont have to use motor anymore. (although its still experimental)
It's about
@bot.event
async def on_message(message: discord.Message):
...
id just save it in memory, there's not much point in saving it to disk anywhere unless your cooldowns are like, hours
lmfao I'm so stupid 😭
what toothy said, You can just have a dictionary like
{user_id: time_when_cooldown_over}
yes 😭
Is there any built-in method to define roles that allowed to use commands outside of code (with other commands in discord chat)?
Like in mee6 you could pin roles to commands in webui
you typically do it in the integrations menu inside discord, per-server
I really should use redis with persistence
All my stuff is in-bot memory or yaml files 😅
To add onto Toothy’s response and directly address this message, you can only do fine-grained controls through the integrations menu. There’s no api available
there is some way to get role settings from a web ui into the integrations menu though
dyno is doing it like that, its very weird and i think not really intended but they use that
Oauth, isn’t it?
has to be
Yeah. So slight correction: there’s just no bot api for it, but can be done with more advanced oauth setups
Also, did they remove search from threads on mobile or did it never exist
defi dont become like me :3
But this isn’t trivial theming stuff, this is tangible qol
I can definitely say it was there
I remember using it
lol that looks wrong
in ol' good times there wasn't such thing as integration settings 👵
Look at aiocache, it supports redis as well as memory
Yeah it's oauth
you mean in the awful dark times
yeah, like 5-6 years ago
My thing is I have a lot of medium-term things to store. Like configuration of external platforms where parts can change (but mostly don’t)
wait... 3-4 years ago
That’s like a century in tech terms
really love how discord saved its native look and in the same time became very advanced
define "native look"
Positions of server list, short user info, channels, chat
its colors
design and icon style
I want to create voice channels that are private for users with the default role so I have:
overwrites = { guild.default_role: discord.PermissionOverwrite(connect=False), }
but, I can't figure out how to create invite links that allow these same users to join the voice channel if they receive an invite.
just want my bot to give permission to users to join certain channels if they run a certain command, but do not want to deal with dynamic changing of roles to accomplish this
you have to write an invite command, which is what i did. the admin of the channel would do /private invite @someone and it does overwrites for the @someone for that channel
just create overrides for the specific users
overwrites = channel.overwrites
overwrites[member] = discord.PermissionOverwrite(connect=True, view_channel=True, speak=True, use_voice_activation=True)
i just dont see the point if anyone can run said command lol
I can change these overwrites dyamically right? ex: update the overwrites for a channel multiple times
i do
@pvc.command(name="invite", description="Invite a member to your private channel.")
async def invite_member(self, ctx: discord.ApplicationContext, member: discord.Member):
await ctx.defer()
# Check if user is in a channel named after them
if ctx.author.voice and ctx.author.voice.channel.name == ctx.author.display_name:
channel = ctx.author.voice.channel
overwrites = channel.overwrites
overwrites[member] = discord.PermissionOverwrite(connect=True, view_channel=True, speak=True, use_voice_activation=True)
await channel.edit(overwrites=overwrites, reason="User invited to channel.")
await ctx.send_followup(f"{member.mention} has been invited to your channel.", ephemeral=True, delete_after=5)
# mention the member in the channel
await channel.send(f"{member.mention} you may now connect to this voice channel.")
else:
await ctx.send_followup("You are not in your channel.", ephemeral=True, delete_after=5
this is my invite command for private voice channels
because it deletes the defer messages
ctx.respond handles everything you need to reply to any interaction
including followups
or wdym
i was experiencing instances where running a defered command would leave the "bot is thinking" text in the channel
using followups fix that
respond should handle it all
i defer a ton too and never needed explicit followups
do you know of any downsides to deferring? I'm getting plenty of Unknown Interaction exceptions while my indecisive users mull their options...
you shouldn't unless you have to
also, wdym exactly, in what situation
eg button callbacks that edit the original message
dont see why you need a defer for that
Traceback (most recent call last):
File "/home/jon/.local/lib/python3.10/site-packages/discord/ui/view.py", line 426, in _scheduled_task
await item.callback(interaction)
File "/var/amorphia/fcoc-timetabler/fcoc-timetabler.py", line 2048, in callback
await interaction.response.edit_message(embed=embed, view=None)
File "/home/jon/.local/lib/python3.10/site-packages/discord/interactions.py", line 1082, in edit_message
await self._locked_response(
File "/home/jon/.local/lib/python3.10/site-packages/discord/interactions.py", line 1243, in _locked_response
await coro
File "/home/jon/.local/lib/python3.10/site-packages/discord/webhook/async_.py", line 220, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction```
I assume these are happening because users are taking to long to (in this case) confirm deletion of a trip
that is your view timing out i think
or they might be dismissing the ephemeral message rather than confirming...
you should set disable_on_timeout to true to make sure the view isnt accessible after it times out
default is 5m i think
or actually in that message it says the timeout is only 3 minutes so ig thats the default unless you changed it
The callback is working, the issue is that your interaction token has expired which happens when
- You dont respond in 3 seconds
- 15 minutes passes from the time that the interaction was created.
Is there a way to restrict a command to only people with a specific role? Or do I need to write my own custom decorator for that?
.rtfm commands.has_role
Youd need to handle the error tho
hm, interesting
Ideally you would leave this up to server admins to setup in the integration settings
what do you mean?
You are using slash commands correct?
If you have a slash command, you can manage the visibility through the integration settings on your server
You could set default permissions for the slash command when the bot gets added
.rtfm default_permissions
Server Settings -> Integrations -> Your Bot -> Your Command
oh. hm, that's odd
Note that this is per server, so if you need the command to only be accessible to people on ONE server with a specific role you should still use a backend check
so essentially at the application level, all commands are available to anyone, and then i would go into the integration settings on the server to limit access to certain commands?
cuz i'm not sure i like that lol
Yes, you can also make them guild commands if you only want them on specific guilds
my bot will only ever be in one guild
If you are concerned about it I suggest using both the integration settings and a backend check. Users who are not allowed to use the command in the integration settings will not even be able to see the command
right, yea i would be fine with doing the integration settings part to make it so people who can't use the command don't see it, but i definitely feel like the backend check should be there
i've always wondered if the integration settings in server settings hid the commands from users.. good to know
@commands.has_any_role(*MODERATION_ROLES)
not sure if i want to use that has_role decorator though, still kind of considering rolling my own. it's weird that it raises an exception
@bot.event
async def on_application_command_error(ctx: discord.ApplicationContext, error: commands.CommandError):
logger.error(f'Error in command "{ctx.command}" invoked by "{ctx.author}" in "{ctx.channel}": {error}')
error_messages = {
commands.CommandOnCooldown: f"This command is on cooldown. Please try again in {error.retry_after:.2f} seconds.",
commands.MissingAnyRole: "You do not have the required role to use this command.",
commands.MaxConcurrencyReached: "This command is already in use. Please wait until it's finished.",
commands.NotOwner: "You do not have permission to use this command.",
commands.MissingRole: "You do not have the required role to use this command."
}
for error_type, message in error_messages.items():
if isinstance(error, error_type):
try:
await ctx.respond(message, ephemeral=True)
except discord.errors.NotFound:
logger.error(f"Failed to respond to interaction: {error}")
return
try:
await ctx.respond("An unexpected error occurred. Please try again later.", ephemeral=True)
except discord.errors.NotFound:
logger.error(f"Failed to respond to interaction: {error}")
logger.exception(f"Unhandled exception for command '{ctx.command}' invoked by '{ctx.author}' in '{ctx.channel}': {error}")
thats why i did this
interesting
how does default_permissions work? Doesn't that also hide the command from people without the permission? It'd be nice to have a has_role that worked the same way
Command Permission Decorators: Commands: Shortcut Decorators: Objects: Attributes full_parent_name, qualified_id, qualified_name. Methods@ after_invoke,@ before_invoke,@ error, def get_cooldown_ret...
i think it just throws, if they don't have a role with XYZ permission
dunno about hiding it.
well test one sec
does not hide
interesting, so i assume you just get a discord error when trying to use it then
ERROR:discord:Error in command "mod testperms" invoked by "bsd_alt (ADMIN)" in "welcome": You are missing Manage Messages permission(s) to run this command.
i just asked someone from my server actually what commands they see, and they don't see any of the commands that are decorated with default_permissions with a permission they don't have
ah
retrying
my alt can still see the commands
oh weird. it think it has permissions
its lying
maybe restart discord?
odd
maybe its a cog issue
lol yea i can't make any use of @default_permissions at all
conflicts with discord.commands and discord.ext.commands
yea default_permissions falsely says a user has permissions
atleast for me
lol this solves the problem
i'm trying to understand how @default_permissions works. seems to modify default_member_permissions for the command object
Command Permission Decorators: Commands: Shortcut Decorators: Objects: Attributes full_parent_name, qualified_id, qualified_name. Methods@ after_invoke,@ before_invoke,@ error, def get_cooldown_ret...
which is not ideal
The thing that bugs me is that with a public bot, I may want to allow a slash command in one server but not be invokable at all in another (e.g. enabled commands) where it's not about what the server owner wants, but the fact that it shouldn't be present at all
guild_ids=[GUILD_ID] in your slashcommand definition?
ive run the same bot in multiple server, and this prevents that
But that requires a code change to update it
Technically it does not need to, you could implement something that changes the guild_IDs and syncs
Oh, is it easy to sync a single command?
I thought that was one of the things other Pycord devs were struggling with implementing
Wellll I dont know how well it works but you should just be able to sync and specify a command and a guild ID
You will have a ratelimit of 200 command CREATES per day per guild
It was something about updating a command that apparently was not getting hit with limits.
though I guess I don't know how that works in practice since you have to restart the bot to change a command (although I wonder if you could make a versioned cog, unload it, load the new version with whatever changes, and then sync those.)
changing guild id is a create
yeah, that was a later question tho.
BTW I have some changes for your voice encryption PR that I am opening a PR for rn
go for it
PRed on your branch, I think I did it right but I have never done that before so let me know if I messed up and I will get it fixed tomorrow
can you use return await ctx.respond?
Yes the return just ends the callback though it does not do anything with the return value of respond
Any suggestions for where to host discord bots? Right now I'm using an EC2 instance on AWS but it is getting expensive.
Need to run your bot 24/7? Get a cheap VPS.
Scaleway - EU
Time4VPS - Lithuania
Infomaniak - Western EU/CH
Hetzner - Germany/US
DigitalOcean - US
Vultr - US
GalaxyGate - US
HelioHost - US
- Self-hosting: Any computer
- Free hosting:
Herokudead :crab: - Kinda free: GCP, AWS (one year free micros), HelioHost (but with some constraints)
I am not an expert on hosting though so I am only relaying the community made list
What are the metrics of your bots and your current EC2 usage ?
can you make button views persist through bot reboots?
No tag persistent found.
The Issue
When you send a message with a view, button for example
if your bot restarts, you will lose the ability to use this button.
How To Fix This
- Set your view timeout to
None
- By default, the view timeout value is set to 300 seconds
- Pass a
custom_idvalue to the view
- Custom ids must be unique
- Chose a custom id that has a meaning in relation to your view
- Add the view to the bot
- You can use the method
Bot.add_view(YourViewClass()) - Make sure to add the view when the bot begin ready
Here's the persistent example.
cheers
self.add_view(PersistentView())
where is add_view declared?
it doesn't exist anywhere except as teh self.add_view
oh this is outside of a cog
In that example they are subclassing commands.Bot so self is referring to a commands.Bot instance
yea lol. dawned on me late
all good, subclassing bot is not all that common so its a bit weird to look at
message = await channel.fetch_message(message_id)
^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'fetch_message'
but i'm looking at it...
How did you get the channel? This sounds like a get_x problem
Any function that starts with get_ in Py-cord is retrieving the related object from your bots cache. If the object is not in the bots cache the get_ method will return None. Because of this behavior you should check if the get_x method is None and if it is use the fetch_x method.
Why Is Using fetch_ Without Using get_ First Bad?
The fetch_ method makes a call to the discord API. This API call is unneeded if you already have the information. It will also make your command take longer because it will have to send and than wait for a response from the discord API. It will also contribute to the discord APIs global rate limit of 50 requests per second.
What Is Cache?
The cache is a temporary storage inside your bot. It holds many objects from members to messages. When you restart your bot the cache will be empty. When the cache is full it will delete older objects to make space for the new objects.
there is no get_message though
channel = self.bot.get_channel(VERIFY_CHANNEL)
its a task, thats why, tasks was firing before the cog was ready
unless i can do the same thing with get_partial_message. im using it to update a button view
I mean the other way around.
If the bot does not have the channel in cache you need to fetch it
Do you need to update the message on startup?
well the button expires after a few minutes and noone can click it ever again
Your understanding on that is a bit off.
The bot stops listening for people clicking on the button after a few minutes, but people can still click it
yea but it fails
Then you're setting some timeout
When a user clicks a button discord will send you an interaction with a custom ID that you set when creating the button. If you did not set a custom ID pycord set one for you randomly
So you need to reverse your logic. Instead of saving the message/channel ID and updating the message with a new button. You should save the custom_id of the button and set up your view to start listening for button presses with that custom_id
yea thats what i did
my slash command that creates the message , saves the message_id with custom_id to a json file
then on boot i read those values in
Then what dark said, you are not setting the views timeout to None
its set to None
or you are stopping the view at some point
the only timeout i have is a waiting for a message reply
msg = await self.bot.wait_for('message', check=check, timeout=300) # 5 minutes timeout
Can you show how you are loading the views on startup
class VerifyView(discord.ui.View):
def __init__(self, bot, custom_id):
super().__init__(timeout=None)
self.add_item(VerifyButton(bot, custom_id))
class Verify(commands.Cog):
def __init__(self, bot):
self.bot: discord.Bot = bot
#self.update_button_task.start()
self.persistent_views_added = False
@commands.Cog.listener()
async def on_ready(self):
if not self.persistent_views_added:
self.bot.add_view(VerifyView(self.bot, "verify_button"))
self.persistent_views_added = True
ok now it seems to be working on restart with this method
and VerifyButton is using the custom_id you pass?
gonna wait for ten minutes till it "expires" again
Yeah, this will not work with any "old" messages that dont have a custom ID
class VerifyButton(discord.ui.Button):
def __init__(self, bot, custom_id):
super().__init__(label="Verify", style=discord.ButtonStyle.green, custom_id=custom_id)
self.bot = bot
does this just look for any button with "verify_button" and keep it alive?
There is nothing to keep "alive"
When you send a message containing that button the custom_id is sent with it. Discord saves the custom_id for each component (on the message object itself). Whenever someone on discord uses a component discord looks at what bot sent it and then sends an interaction to that bot along with the custom_id that was original sent with the component. Then pycord matches the custom_id to a callback and runs that callback. If you dont add the view on startup pycord will not know what callback the custom_id matches, so it just ignores it.
correct. discord does not want that because that would be a massive amount of api calls at scale 
yeah thats what i was thinking when i started writing that loop
this is what i've been working on with that button
I have been wanting to do stuff like that, but unfortunately ChatGPT makes quick work of that
I've tried a big bunch of verification systems throughout my time on Discord, and the one that worked for me best was to get a levelling bot, and limit server access to level 1. With only a welcome channel accessible otherwise. Allows you to manually weed out spammers and idiots, while letting genuine people chat for a bit until they reach level one. I also kick anyone who didn't reach level 1 within a week, and I've also made out a few sets of roles bots will always select from onboarding, so I automatically kick those as bots. Also, kicking everyone with a spammer flag is really helpful
If they join back and select the same roles does it still kick them?
I am putting await ctx.defer() at the beginning of a command to wait for the response if I put ephemeral=True, it expects all results to be of type ephemeral. I can decide that x results for example if it gives KO the command shows individually to the user with ephemeral=True and if it gives OK it shows for all?
yep
I specifically DM them telling them to select different roles if they rejoin
So if it's a bot that rejoins they'll be kicked again and if it's a person who pays attention they won't be
But it's very unlikely to select either of those sets of roles randomly
You can't change visibility after a defer
Okay
you could send a message into the channel or send another response after responding to the defer, that won't be forced to be ephemeral I think
Am I able to have every user in my server in the cache at the same time? My server has under 20 members so I want everyone in the cache.
Yup, you need to do .
(it's already like that)
default cache size is 1000 members iirc
just remember you need members intent to actually receive the member objects
that's message cache LOL
by default every member is cached
no limit?? damn
if the guild is over 75k members or you don't have presences(?) intent then it's limited to online members only
ah not quite, those conditions only send members connected to voice
odd
so by default the lib uses Request Guild Members to fill every member in chunks of 1000
how much ram do you have 
7 ram
is there a way to get the join method of users?
not on api
Bummer
hi! how do I make a slash command guild_only since version 2.6?
I'm trying something like this
import discord
bot = discord.Bot()
@bot.slash_command(guild_only=True)
async def hello(ctx, text: str = ""):
await ctx.respond("Hello!")
@bot.slash_command(contexts=set(discord.InteractionContextType.guild))
async def test(ctx):
await ctx.respond("test")
DISCORD_TOKEN = ''
bot.run(DISCORD_TOKEN)
and it raises a warning for the hello command with the old methon and an error for the test command with the new one
C:\Users\Admin\PycharmProjects\discordBots\.venv\lib\site-packages\discord\commands\core.py:736: DeprecationWarning: guild_only is deprecated since version 2.6, consider using contexts instead. See https://discord.com/developers/docs/change-log#userinstallable-apps-preview for more information.
super().__init__(func, **kwargs)
Ignoring exception in on_connect
Traceback (most recent call last):
File "C:\Users\Admin\PycharmProjects\discordBots\.venv\lib\site-packages\discord\client.py", line 412, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Admin\PycharmProjects\discordBots\.venv\lib\site-packages\discord\bot.py", line 1214, in on_connect
await self.sync_commands()
File "C:\Users\Admin\PycharmProjects\discordBots\.venv\lib\site-packages\discord\bot.py", line 742, in sync_commands
registered_commands = await self.register_commands(
File "C:\Users\Admin\PycharmProjects\discordBots\.venv\lib\site-packages\discord\bot.py", line 595, in register_commands
data = [cmd["command"].to_dict() for cmd in filtered_deleted]
File "C:\Users\Admin\PycharmProjects\discordBots\.venv\lib\site-packages\discord\bot.py", line 595, in <listcomp>
data = [cmd["command"].to_dict() for cmd in filtered_deleted]
File "C:\Users\Admin\PycharmProjects\discordBots\.venv\lib\site-packages\discord\commands\core.py", line 962, in to_dict
as_dict["contexts"] = [ctx.value for ctx in self.contexts]
File "C:\Users\Admin\PycharmProjects\discordBots\.venv\lib\site-packages\discord\commands\core.py", line 962, in <listcomp>
as_dict["contexts"] = [ctx.value for ctx in self.contexts]
AttributeError: 'int' object has no attribute 'value'
Contexts is like this {}
try like so:
contexts={discord.InteractionContextType.private_channel}
it works now
ty so much!
is it possible for a discord bot to monitor the activty of someone in discord just the spotify one
like the bot can track what music they are playing
Is there an example of @after_invoke?
for what ?
Err it's hard to explain
I want to have my bot to check the user's level and send level up messages after each command.
This would be the structure of a command:
@discord.slash_command()
async def random_command(ctx)
... # Command logic
user = UserData(ctx.user.id)
ctx.level_data = await user.add_exp(10)
class UserData:
def __init__(user_id):
...
async def add_exp(amount):
... # Some logic and database operations
return {
'hasLeveledUp': level_up,
'level': self._level,
'rewards': rewards
}
I would like to do something like:
# After invoking the command
if not ctx.level_data['hasLeveledUp']:
return
await ctx.followup.send(f"{ctx.user.mention}, you are now Level {ctx.level_data['level']}")
@after_invoke() takes one parameters, a coroutine that accepts the Context argument. Where are you running into issues?
Your coro would have to separately look up the user in your level data as ctx.user, but at least keeps you from having to add it to every command
But if it’s after invoke, I don’t know if you could use followup. Would need some testing
I actually want to know how to set up the decorator. Is it just @after_invoke(ctx)?
No, according to the docs it takes a coroutine (an awaitable method). That method is what accepts ctx
Ah, so like
@commands.after_invoke()
async def something(ctx):
because my commands are in a Cog
In a cog I would think it would be (self, ctx)
.rtfm cog_after_invoke
I think that auto does it after every command in the cog. I have not actually used it though.
I don't think there is a way to do it after every listener calls as well if that is what you are asking
I want to have sub commands with discord app commands (e.g. /vc create instead of /vccreate). But setting the command name to vc create does not work.
discord.SlashCommandGroup
discord.SlashCommandGroup.add_command
discord.SlashCommandGroup.after_invoke
discord.SlashCommandGroup.before_invoke
discord.SlashCommandGroup.call_after_hooks
discord.SlashCommandGroup.call_before_hooks
discord.SlashCommandGroup.callback
discord.SlashCommandGroup.can_run
discord.SlashCommandGroup.cog
discord.SlashCommandGroup.command
discord.SlashCommandGroup.cooldown
discord.SlashCommandGroup.copy
discord.SlashCommandGroup.create_subgroup
discord.SlashCommandGroup.dispatch_error
discord.SlashCommandGroup.error
discord.SlashCommandGroup.full_parent_name
discord.SlashCommandGroup.get_cooldown_retry_after
discord.SlashCommandGroup.has_error_handler
discord.SlashCommandGroup.invoke
discord.SlashCommandGroup.invoke_autocomplete_callback
I figured it out, you just name a method as cog_after_invoke
async def cog_after_invoke(self, ctx):
if not hasattr(ctx, 'level_data'):
return
if not ctx.level_data['hasLeveledUp']:
return
rewards = ctx.level_data['rewards']
level = ctx.level_data['level']
if rewards > 0:
await ctx.followup.send(
f"{ctx.user.mention} Great job on reaching level {level}!\n"
f"You earned ${rewards:,}"
)
else:
await ctx.followup.send(f"{ctx.user.mention} You are now level {level}!")
does pycord support optimization flags and if so whats the max it supports?
like what
-O and -OO I think
btw you can replace those followup.send with .respond, makes it a bit easier
That will result in an error because I am already responding to the Context in the command itself
i see, thanks
hi, when you specify debug_guilds, does application commands still take up to an hour to register with that attribute specified ?
commands dont take that long to register anymore
its effectively instant
you just need to restart discord
see
o, i c. thank u. i'm having a bit of trouble registering application commands rn so i guess im having another issue. i will make a thread for it
.tag slashnoshow
Application Commands Not Showing Up?
- Refresh Discord by restarting or pressing
Ctrl+R(orCommand ⌘ + R) - 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.
oo ok i will make sure i try all of these
ty
idk T-T i made it in a cog and for some reason a test prefix command works but not the slash command
if you need slash and prefix you might wanna look into bridge
o i just want to make the slash commands tbh but i thought my cog wasnt working so i made a prefix command in it to make sure it was just the application command
i should make it in a separate thread right (?)
i mean post
or idk what these things are called
As you wish
created ! (ty for the help btw)
hi! what channel_types exist in discord? Couldn't find them in docs
discord.ChannelType
discord.ChannelType.category
discord.ChannelType.directory
discord.ChannelType.forum
discord.ChannelType.group
discord.ChannelType.news
discord.ChannelType.news_thread
discord.ChannelType.private
discord.ChannelType.private_thread
discord.ChannelType.public_thread
discord.ChannelType.stage_voice
discord.ChannelType.text
discord.ChannelType.voice
discord.DMChannel.type
discord.TextChannel.type
oh wait, found it
I am in a predicament where a slash command that is inside a cog and a slash command that is just in the main bot.py file have the same implementation. They also both have the same exact autocomplete function. The slash command inside the cog is noticably slower, and also does not filter the options properly. video attached. Any ideas?
This should not be an issue? Are you sure it is not a difference in time between API/DB calls?
discord.errors.HTTPException: 400 Bad Request (error code: 30032): Maximum number of application commands reached (5).
How can i make more than 5 context menu message commands?
I think you can have 5 more guild ones. But in general you cant. It is a discord limitation.
my codebase (that heavily relies on cogs) does in fact work with python optimization flags with python -OO, and i hope this infomation helps greatly with whoever needs to know that when they use the discord search bar
nvm
whats the issue
I just dont get it
what part
Im trying to provide cooldown arg for @bot.slash_command decorator and it wants it to be a an instance of CooldownMapping, but i couldnt find way to create it
use the @commands.cooldown decorator below the slash command decorator
module 'discord.commands' has no attribute 'cooldown'
guh
veah
yes it does lol
can you show your pip list
The following section outlines the API of Pycord’s prefixed command extension module. Bots: Bot: Attributes activity, allowed_mentions, application_flags, application_id, cached_messages, case_inse...
its pretty long
from discord.ext import commands then @commands.cooldown()
are you importing it like that
discord.commands isn't even a thing i think, or its a shortcut for discord.ext.commands
so not sure why it didnt work
i tried to access it right away
yea but according to the error discord.commands exists
so im wondering what that points to lol
lets see
How come I get this: ```
Forbidden: 403 Forbidden (error code: 50005): Cannot edit a message authored by another user
from this code? ```py
async def getmsgcount(ctx: discord.ApplicationContext, channel: TextChannel):
message_count = 0
message = await ctx.respond("Counting...")
async for message in channel.history(limit=None): # Fetch all messages
if message_count % 100 == 0 and message_count != 0:
await ctx.channel.send(content=f"Got {message_count} messages in the channel <#{channel.id}> so far!")
if not message.author.bot:
message_count += 1
await message.edit(content=f"Got {message_count} messages in the channel <#{channel.id}>")
rename the message var outside of the for loop
i may have messed up something on install
no, it does exist
oh bruh yea nvm im dumb it has all the non prefix command stuff
its just imported right into the discord namespace so you never use discord.commands.*
i see ty
Is there a way to get the channels a member/user has access to in a guild without having to loop through each channel and check the permissions of it?
I’ve been doing this but in large servers it takes way too long
not really i think, what do you need that for
are you fetching every channel or something?
The “jailing” process for my bot. If a user can see channels they’re not supposed to, it’s pretty pointless
Not sure, I’d have to check. This has been on my improvement list for a while
i mean, i can't think of any reason for why that would take more than a second or two
cant you just remove all their roles lol
Yes, that’s also part of the process. It then assigns them an inmate role which has the view permissions set to deny on every single channel. That’s what takes so long is verifying that the inmate role is set properly on all the channels. Otherwise, they’d be able to see channels that @ everyone can see
just update the overrides everytime a new channel is made or overrides are changed
or make a command like /jailrole sync or something that verifies the overrides
I can get it later, I’m at work atm lol
fair
hey, I've got a little issue
@commands.slash_command(
name="generate_password",
description="Generate a random password.",
contexts={
discord.InteractionContextType.guild,
discord.InteractionContextType.bot_dm,
discord.InteractionContextType.private_channel
}
)
async def generate_password(self, ctx: discord.ApplicationContext, length: discord.Option(
name="password length",
default=16,
required=False,
input_type=discord.SlashCommandOptionType.integer,
max_value=1024,
description="The length of the generated password.",)
):
view = PasswordView(length=length)
await ctx.response.send_message(
"Please select all elements you password should contain!",
ephemeral=True,
view = view
)
This command raises AttributeError: Option does not take min_value or max_value if not of type SlashCommandOptionType.integer or SlashCommandOptionType.number even through it surely is set to input_type integer.
Also if I try doing it with the decorator it's not set at all, the option shows up but without parameters.
same issue
and I'll try the decorator
make sure to restart discord every time
else you wont see the updated command
and also, use ctx.respond(), you dont need .response.send_message
still no description no limit no default with the decorator, but the bot starts
@commands.slash_command(
name="generate_password",
description="Generate a random password.",
contexts={
discord.InteractionContextType.guild,
discord.InteractionContextType.bot_dm,
discord.InteractionContextType.private_channel
}
)
@discord.option(
name="password length",
default=16,
required=False,
type=discord.SlashCommandOptionType.integer,
max_value=1024,
description="The length of the generated password.",
)
async def generate_password(self, ctx: discord.ApplicationContext, length: int):
view = PasswordView(length=length)
await ctx.response.send_message(
"Please select all elements you password should contain!",
ephemeral=True,
view = view
)
This is the current code
you arent matching it to the argument lol
pass parameter_name="length"
and you dont need to pass contexts if you want all three i think
ohh, I didn't know that. Thank you that fixed it
docs tell you that :)
I'm doing it just for safety. Could be that it's not needed
ohh, I've looked for the Object Option not for the decorator, yeah I see the extra parameter_name 
already thought I am going crazy because it didn't work
Why cant I use ```python
@vc_group.command(name="create", description="Create a voice channel")
async def vccreate(ctx: discord.ApplicationContext, privacy: typing.Literal["Public", "Friends", "Invite only"] = "Public", name: str = None):
How else can I have a multiple choice selector
Here's the slash options example.
This didn't work and gives Application Command raised an exception: TypeError: issubclass() arg 1 must be a class
@discord.option("privacy", "Privacy of the voice channel", choices=["Public", "Generics", "Invite only"], required=False)
async def vccreate(ctx: discord.ApplicationContext, privacy: str, name: str = None):
The second positional argument is the type. So you either need to specify the type or add description= before the description
Is there a way to make certain commands only available in a specific server? Everything i see online just checks the server id when the command is run, but I only want the slash command to be visible in one server
Yes you can pass guild_ids=[list of ids] to your command decorator.
If you want all commands to only be on one server you can add debug_guilds=[list of ids] to your bot instance call
Ohh so like @commands.slash_command(name="name", description="description", guild_ids=[12345])?
yes
is there a way to make, that the bot runs some async functions, when the bot gets on a new server?
Yes
.rtfm on_guild
discord.on_guild_join
discord.on_guild_remove
discord.on_guild_update
discord.on_guild_available
discord.on_guild_role_create
discord.on_guild_role_update
discord.on_guild_emojis_update
discord.on_guild_channel_create
discord.on_guild_channel_update
discord.on_guild_channel_delete
discord.on_guild_stickers_update
discord.on_guild_channel_pins_update
discord.on_guild_integrations_update
the on_guild_join?
Is it possible, in the pypi pycord version to know if a message contains a voice message ?
probably in the raw message data
Check flags https://docs.pycord.dev/en/stable/api/data_classes.html#discord.MessageFlags.is_voice_message
if message.flags.is_voice_message:
...
Some classes are just there to be data containers, this lists them. Unlike models you are allowed to create most of these yourself, even if they can also be used to hold attributes. Nearly all clas...
These are 'NewsChannel' type correct?
Yes
Thanks
Pycord does not have a class for that though. It is just a TextChannel
Just has is_news() and follow()
and messages in the channel have the .publish()
creating permissions required for slash commands?
Do you want to lock a slash command to certain permissions?
yep
look into that
how can i make my messages ephemeral?
ephemeral=True
in ctx.respond i can just do like ctx.respond("example", ephemeral=True) ?
yes
thanks
How do I embed a link in an embed field title? It seems text only works in descriptions, and I saw online about { title: "title", url: "url" } but it seems to only be for main embed title?
I'm looking for here:
embed.add_field(
name=[text](link)
...
Other searches around github issues and such suggest it might be impossible, I just wanted to make sure
I think you can't
Ah, thanks anyway!
Works in the field value too 
https://i.imgur.com/zkxPUU9.png
set_author has a URL kwarg too
But that's not what you asked
the field title is pure text
you can't use any markdown or mentions or anything there
Titles and footers indeed don't support markdown
Title has its own link kwarg you can set
category = interaction.data['custom_id'].lower()
lessons = file_info.get(category.lower(), [])
print(lessons, category.lower())
I'm trying to print the lessons in a subject in a json file however why does it return empty?
1 min
The JSON isn't empty but still returns []
what is file_info?
data = ReadInfo.read_json()
file_info = data['subjects'][subject]['files']
def read_json():
json_file_path = os.path.join(script_dir, 'subjects_data.json')
with open(json_file_path, 'r') as file:
data = json.load(file)
return data
This one is in a file (ReadInfo) ^
I think it's due to the accents and symbols?
add encoding="utf-8" after 'r'
Yeah, I've fixed it with that
Thank you.
im having.. unexpected bahavior with views. does the timeout property start the countdown from the last interaction or from when the view is initalized? because ive been working with views for what seems like years now and im just now experiencing the first one, when ive learned to expect the second one
additionally there is nothing of help online, from what i can see
It starts from the last interaction
countdown restarts at every view interaction
gotcha. thanks
how long has that been the case?
let me guess, im an idiot and its been that way forever
is there any way to force it to timeout in a certain amount of time
or would i just have to essentuially redo the timeout system
i think ill just do that
if i could bum another answer from you quick.. i have a view set to timout in 2 minutes. so as a test i summon the view and wait for 2 minutes but the view expires at arounf 30s. is that normal behavior?
I'm pretty sure it isn't
What do you mean ?
thank you for you help
there is
like i want my view to be done after 2 or 4 minutes no matter how many people interact with it and when
Then you can probably use that
what I just sent
You create an asyncio task
I made an exmaple here of a timed task
#1132206148309749830 message this
im not saying its hard im just saying its annoying i gotta add it now
yeah
thanks for the help man
np lmk if anything else
yeah this is actually happening 😐
I'm really confused now
If you have a minimal replroductible code please open an issue on github for that
I could try yeah
it's in a big file. I haven't moved everything away or abstracted anything yet so like I just ran into what I thought was a small problem but now it kinda messes with my whole command. there goes 950 lines of hell
very ood
I'll add a gh issue tho yeah
I’ve also had some weird inconsistencies with Views. Some expiring after 15 mins despite having a longer timeout. But then when I went to explicitly recreate it, I couldn’t
So it’s also entirely possible discord quietly fixed something within the last year and gaslighted us all
To debug further you can give the view a timestamp when it is created and compare that timestamp in interactions and the on_timeout event
I know I've seen them in here before.. (doesn't seem to be in #creations) but does anyone have open examples of recording voice per user (preferably with timestamps)?
Oh. The sinks already do have it per user.. but is it easy to differentiate between someone speaking for 5 mins at the start of a 1 hour call, and someone only speaking for 5 mins at the end of the call? (i.e. timestamps)
Om made a PR for that a while ago I think. Iirc The silent time based on when we received the packet tho. So there can be slight shifts because of network lag
What exactly is this asking for? I gave it a list of SKU IDs and and a list of SKU objects and it throws an error both times
It's under member.entitlements()
SKU objects should have worked, what errors are you getting?
I think all discord objects inherit from Snowflake tho
This is all it is doing on the backend anyways
[sku.id for sku in skus] if skus else None
is there any way to make a bridge between normal slash commands and user commands?
similar to how it is possible to make a bridge between prefixed and slash commands
no
just make them both call the same function
alright, thanks 👍
Is it possible if I have the author_check enabled on a Paginator that I can then return a custom message when someone tries to use the Paginator so that I don't just get “Interaction Failed”?
If I read this correctly in the docs, then I can only implement it manually with interaction_check and on_check_failure and leave out the author_check, right?
Is there a way I can create a file for each command and register them to the same cog
??? Why would you do that.
uh my commands are getting a bit long
Should I still keep them all in a single file or cog
I remember there was a discussion about this some time ago already
Are your commands in the same group ?
Is that the reason why you want them in the same cog ?
they're in the same cog file
A cog is a class
correct
Okay thanks
no, cogs are literally made to seperate commands into multiple files lol
that's the entire point
well, alright
You could look in to not needing cogs at all. Most people do not use the features of cogs anyways. Extensions and cogs are not required to be linked
how would you do that then
https://docs.pycord.dev/en/stable/api/clients.html#discord.Bot.add_application_command
in the setup function I believe
ah yea
kinda unnecessary tho, imo just doing it the regular cog way is simpler and less prone to errors
Hi, I have a view with some buttons, and whenever a button is clicked, it sends a confirmation message to the user in ephemeral (which is another view). After confirming, the confirmation message gets edited instead of the original one.
What does your callback look like?
Something like this
async def callback(self, interaction):
result = await send_confirmation(
f"Buy **{self.item_name}** for ${self.price}?",
user = interaction.user,
interaction = interaction
)
if result:
await interaction.respond(f"You bought 1 **{self.item_name}**!", ephemeral=True)
await interaction.edit(embed=ShopEmbed(self.user), view=Shop(self.interaction_user, self.user))
await self.user.add_wallet(- self.price)
await self.user.add_item(self.item_id, 1)
That's the conformation callback?
And here's what send_confirmation_message does
import discord
class Confirm(discord.ui.View):
def __init__(self, user:discord.Member, embed):
super().__init__(timeout=30)
self.user = user
self.embed = embed
self.result = None
async def interaction_check(self, interaction: discord.Interaction):
...
async def on_timeout(self):
...
@discord.ui.button(label="Cancel", style=discord.ButtonStyle.red)
async def cancel(self, button:discord.ui.Button, interaction:discord.Interaction):
self.result = False
self.disable_all_items()
self.children[1].style = discord.ButtonStyle.gray
self.embed.title = "Action Cancelled"
self.embed.colour = discord.Colour.brand_red()
await interaction.response.edit_message(embed=self.embed, view=self)
self.stop()
@discord.ui.button(label="Confirm", style=discord.ButtonStyle.green)
async def confirm(self, button:discord.ui.Button, interaction:discord.Interaction):
self.result = True
self.disable_all_items()
self.children[0].style = discord.ButtonStyle.gray
self.embed.title = "Action Confirmed"
self.embed.colour = discord.Colour.brand_green()
await interaction.response.edit_message(embed=self.embed, view=self)
self.stop()
async def send_confirmation(message, user: discord.Member, ctx: discord.ApplicationContext=None, interaction: discord.Interaction=None, ephemeral: bool=None):
embed = discord.Embed(title="Pending Confirmation", description=message, color=discord.Colour.yellow())
view = Confirm(user, embed)
if ctx:
view.message = await ctx.respond(embed=embed, view=view, ephemeral=ephemeral if ephemeral else True)
if interaction:
view.message = await interaction.respond(embed=embed, view=view, ephemeral=ephemeral if ephemeral else True)
await view.wait()
return view.result
It's the callback for one of the uh, buttons in the context response
The confirmation callback is just a yes/no to either continue with the process of your original view?
Yup
Can't you use something like this?https://github.com/BruhDark/sally/blob/main/src%2Fresources%2Futility_views.py
You then just wait for the view on your original callback
hmm I'll try that
Are there any known/recommended 'templates' for creating a new bot (including cogs and such)? Given I haven't created one from scratch in years at this point, I'm curious if there are any resources that collect a bunch of best practices
I made one
An Advanced Framework for Crafting Sophisticated Discord Bots with py-cord - nicebots-xyz/botkit
I was just looking at this. It does look very cool, but seems more framework-y than I was personally looking for. Although I did learn about the __init__.py file, which might come in handy elsewhere.
Yeah it's true that it makes a lot of more subjective design choices for you. It's really biased towards how I myself do things, but I figured I may as well make it open
you didnt know about init?
Nope. Never built a published package, and it seemed superfluous.
I still don't get why there's both __init__.py and __main__.py 🤷♂️
main if if I run the module, init is if I import (from) the module
e.g.
pythom -m src # This will run __main__.py
from src import yada, bleh # this will import from __init__.py
Interesting. So you could theoretically build a package as an extension that also contains a full-fledged, runnable bot (if barebones aside from the extension) if run that way?
yes
Lots of packages from pypi allow both to be used with code and also executed from cli
i use it to get stuff higher up in the folder hierarchy
hey all, I have a few questions , a while back, some helpers told me to not use the has_role() decorator, I need it for my bot because I'm building something that manages roles and build some games around those roles, for example a @knight can't use magic or your not the @king you can't ask @MyBot to do this. Even though I still check user roles, I agree it doesn't mean I have to use a deprecated decorator, so here are my questions:
- Why shouldn't I use it , does it have to do with how slash commands handles contexts?
- Is there a newer decorator to check roles of a user ? if no do you think I should make my own decorator ?
you're right I don't know why I remembered someone telling me it was deprecated. But in the past you told me I shouldn't use has_role cause it was an old relict
Yeah but you should use slash commands with that
I'm using slash commands with has_role actually, so if there is nothing bad with it then I don't need more help
Is it in just one server
no
Then yeah has_role is probably good
But how do you use has_role if it's in multipe servers
the roles are different between servers
it checks for specific roles and will create the one needed for the games
I'm not sure I understand
In any case
what Toothy meant was that you should edit the server's integration settings
and change there what role can use what command
His intention is that the bot manages the needed roles for his application - using his examples earlier, roles named "King", "Knight", etc.
He wants to be sure that application commands, when run, are checked against the named roles.
Yeah so has_role is good for that
thank you for that it helped a lots !
Here's my code and full traceback
all_premium_bot_skus = await self.bot.fetch_skus()
purchased_member_skus = member.entitlements(all_premium_bot_skus)
That looks like a bug in pycord
Oh nice I'll make a report lol
Yup, already been fixed on master
https://github.com/Pycord-Development/pycord/pull/2628
We really need to do a 2.7 release
I have been trying #discussion message
I added a voice to the echo
one of the big things is doru is not very active anymore cuz country bans
Oh I forgot about that. Hopefully he has a VPN?
yeah, but i think it just makes everything harder
"You get master" 😂
Hi, anyone knows what this error means?
AttributeError: property "view" of "Button" object has no setter
Update: button already has a built in view property, so renaming the property fixed the issue
Traceback (most recent call last):
File "c:\Users\icesc\Documents\NRTH.venv\Lib\site-packages\discord\ui\view.py", line 426, in _scheduled_task
await item.callback(interaction)
File "c:\Users\icesc\Documents\NRTH\src\cogs\verification.py", line 57, in button_callback
await interaction.response.send_modal(VerificationModal(code=self.code))
File "c:\Users\icesc\Documents\NRTH.venv\Lib\site-packages\discord\interactions.py", line 1221, in send_modal
await self._locked_response(
File "c:\Users\icesc\Documents\NRTH.venv\Lib\site-packages\discord\interactions.py", line 1292, in locked_response
await coro
File "c:\Users\icesc\Documents\NRTH.venv\Lib\site-packages\discord\webhook\async.py", line 222, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
class VerificationView(discord.ui.View):
def __init__(self, *items, code:int):
super().__init__(*items)
self.code = code
@discord.ui.button(label="Enter Verification Code", style=discord.ButtonStyle.primary)
async def button_callback(self, button, interaction):
await interaction.response.send_modal(VerificationModal(code=self.code))
Line 57 is the await interaction response
added self.code as my own attribute for verification
I don't understand why the interaction isn't found
Codebin Paste:
Description: discord bot
Language: python
Last Edited: 1/29/2025, 11:01:46 AM
Expires: 1/30/2025, 9:29:24 AM
Is your internet slow ?
Does it always error like that?
it is
never tried it
could there be no other possible reasons?
Not really
try doing
await interaction.response.defer ()
before the second await?
I always get this when inputting it
Wait
Do you have a callback on your modal ?
Yes
This is the only issue ?
Or do you have issues with the / command istelf ?
on the user side yes
does the callback impact it?
bc I get this all the time
I'm not sure one can defer a modal interaction response
But this is not in the modal
it's not the same issue
try changing it like this
class VerificationView(discord.ui.View):
def __init__(self, *items, code:int):
super().__init__(*items)
self.code = code
@discord.ui.button(label="Enter Verification Code", style=discord.ButtonStyle.primary)
async def button_callback(self, button, interaction):
await interaction.response.defer()
await interaction.response.send_modal(VerificationModal(code=self.code))
Also it's not secure to use randint for secure code generation
yeah thats fine for now its just a small verification step for like a hs server so there's not really any risk
alr sure
im getting this
just changed it to that
oh yeah that's what I thought
Yeah no so then you simply can't
It's an issue with internet speed
Basically, once you recieve an interaction from discord, you have 3 seconds to respond
and if your internet is too slow, you can't respond in 3 seconds
the user has 3 seconds to respond?
No you have
Ohhh
once the user clicks on the button
or runs the command
or anything
you have 3 sec to respond with something
why is it that when running commands there is no issue tho?
wouldn't they realistically have similar requirements to run it?
Pretty sure you can't defer when sending a modal. (I can't tell if that is what you were getting at)
You indeed can't defer to then send a modal.
can dynamic cooldown be an asynchronous function?
i dont see what there makes it a no
i was looking at the docs as well
hey guys what does this error means: https://mystb.in/1dbb41cd7763be4d12
That the payload is too large
basically the image its too heavy?
yes
strange, it worked before
if you're sending a message
they changed something?
its a paginator
do you know whats the limit?
Callable[[discord.Message], Optional[Cooldown]]) means its supposed to take a Message and returns a Cooldown obj, not a Coroutine (Coroutine[Any, Any, Cooldowm | None])
also when looking at the actual cooldown impl, nothing is async https://github.com/Pycord-Development/pycord/blob/19721e2ca56bc102d933d8198af89ca0dbdec498/discord/ext/commands/cooldowns.py#L207-L271
.tag embed_limits
Field amount = 25, Title/field name = 256, Value = 1024, Description = 4096, Footer text = 2048, Author name = 256
Note that the sum of all characters in the embed should be less than or equal to 6000.
https://cdn.discordapp.com/attachments/559455534965850142/885103228566515732/unknown.png
so the problem is this change dw thanks
do you know if boosting the server to level 2 increase the limit for the bot too
Pretty sure it does
sorry for the followup, just wondering, I tested it again just now, and it immediately shows the error after I send in the form on the user side, no delay whatsoever, could it be something else causing this?
What does your callback look like?
And whats the error
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: NotFound: 404 Not Found (error code: 10015): Unknown Webhook What does this error mean?
It has something to do with how you are respondingto or preforming actions on interactions. I believe specifically when you are dealing with ephemeral messages.
We would need more code to diagnose.
You sure that value matches? Maybe print it out
Also, convert self.code to a str
Sry, took a long break from using Pycord, but is there a reason https://docs.pycord.dev/en/stable/ says "Pycord v0.1 Documentation"? I'm just looking for latest docs.
It's a bug
that's the latest
Awesome, just thought I was goin crazy for a sec 😅 Thx
i fixed, had an if statement that didn't have an interaction response
How do you define autocomplete for an Option? This is my function
def get_matching_items(cls, ctx:discord.AutocompleteContext):
'''Returns a list of matching item names based on user input.'''
cls._load_data()
if not cls._item_metadata:
return []
all_names = [
data['name']
for data in cls._item_metadata.values()
if 'name' in data
]
user_input = ctx.value.lower().replace(' ', '')
matches = [
name
for name in all_names
if name.lower().replace(' ', '') == user_input
][:25]
return matches
Can anyone tell me why my buttons aren't showing up?
Only the Resend Code button shows up
No errors or anything
nvm figured it out
each button needs its own callback function
why is that?
if it's all under the same decorator and has its own label won't it differentiate it
Thats because of how python works at a lower level.
If you have multiple functions with the same name, in the same scope, then it will always prioritize the "bottom" one.
ic
why do I keep getting this?
I gave the server id
I suspect its because discord.Client.get_guild isn't supported? so I just have to use the instance of the discord.Bot setup in my main file, which isn't connected to my cog?
So how would I be able to use bot.get_guild() when my cog doesn't inherent the bot
inherit the bot i guess
from what class
i don't think so
interaction.client will return your bot instance
And you're probably also passing the bot to the cog and have defined it as self.bot
actually yes, the cog inherits from discord.ui.Modal
yes but the thing is that this is in a dialogue modal
Ah you're talking about a class
Someone had a similar weird issue some time ago
Not specifically a commands.Cog
and I'd have to pass it through from the initial Commands.Cog to the View to the Modal
ah alr
Ic
"Issue"? They're literally trying to use a method of a class without initialising it
Even if it was called, it wouldn't work because it's not the running instance
Can you please make sure pycord is up to date and you don't have other discor dlibs installed ?
Oh yeah
Get your OOP knowledge up lmao
I'm pretty sure that it is
Thanks guys for all the help anyways
lol
class MyClass:
def method(self, arg):
pass
MyClass.method("arg") # error: MyClass.method() missing 1 required positional argument: 'arg'
MyClass().method("arg") # valid
inst = MyClass()
inst.method("arg") # valid
Hello !!
Does anyone know how I can avoid these errors ?
File "/usr/local/lib/python3.12/site-packages/discord/client.py", line 412, in _run_event
await coro(*args, **kwargs)
File "/usr/local/lib/python3.12/site-packages/discord/bot.py", line 1214, in on_connect
await self.sync_commands()
File "/usr/local/lib/python3.12/site-packages/discord/bot.py", line 761, in sync_commands
app_cmds = await self.register_commands(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.12/site-packages/discord/bot.py", line 538, in register_commands
prefetched_commands = await self._bot.http.get_guild_commands(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.12/site-packages/discord/http.py", line 368, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
They are happening when I start the bot
nvm it was a guild_ids=[...] argument with a server ID where my bot is not in..
With a Error Handler
;3
save the bot object in the cog upon creation?
that makes no sense
for a class to be a cog it needs to subclass discord.Cog
if it doesnt its not a cog
@high spire @ionic wasp just to get you two straight on vocabulary
inherit means when you take over things from a superclass when you subclass a class
import (which you probably meant) is importing a value from another file, or a module etc
just so it doesnt cause confusion later on
Do grouped slash commands not work with user apps? For example I have this: (which doesn't register)
discord.IntegrationType.guild_install,
discord.IntegrationType.user_install,
}, description="Get general stats of a player.")```
but this does:
@commands.slash_command(integration_types={
discord.IntegrationType.guild_install,
discord.IntegrationType.user_install,
}, description="List of commands.")
You probably need to register the whole group as user installable.
Subcommands are not treated as separate commands by Discord.
oops
It’s not possible to set a bot’s status message on a guild-by-guild basis, is it?
no
can you explain on this it doesn't make sense to me
Is it possible to prevent a paginator from timing out?
This module provides an easy pagination system with buttons, page groups, and custom view support. Example usage in a cog: API Reference: Page: Attributes content, custom_view, embeds, files. Metho...
timeout=None?
oh, how did I not see that. So it defaults to 180 seconds?
yea
i got too distracted by the disable_on_timeout kwarg
which only applies to the buttons for some reason
boy i'm dumb. thanks for being my rubber duck as always toothy
perhaps one of these days i'll learn how to read
what's providing the bot parameter?
ohh in setup right
so is setup automatically called in the main file?
v
its completely and entirely unnecessary
ic
It's a practice to prevent the file from running if not itself or something like that
It's a common thing
well
Not itself?
it prevents the code inside it from running if the file was imported
it only runs if the file was the original script that got ran
does the on_disconnect event happen everytime the shard resumes a session?
400 Bad Request (error code: 50034): You can only bulk delete messages that are under 14 days old.
is this a new thing?
Pretty sure not
Discord has stronger limits on older messages
Are there built in DOS protections? That is, if someone spams a command for 24 hours + is this inherently dealt with? I know slow mode exists, just wondering if I have to deal with this edge case in my code
no
no that's not new
that's why the lib deletes messages older than 14 days one-by-one in purge
What is the simplest way to deal with this
You can implement cooldowns on your commands, but if you are using slash commands it is going to be hard for people to spam the command anyways
Cool okay I am using slash commands, thank you for providing me witht the correct answer
discord.ext.commands.Cooldown
discord.ext.commands.Cooldown.copy
discord.ext.commands.Cooldown.get_retry_after
discord.ext.commands.Cooldown.get_tokens
discord.ext.commands.Cooldown.per
discord.ext.commands.Cooldown.rate
discord.ext.commands.Cooldown.reset
discord.ext.commands.Cooldown.update_rate_limit
discord.ext.commands.cooldown
discord.ext.commands.cooldowns.Cooldown
discord.ext.commands.Command.cooldown_after_parsing
discord.ext.commands.dynamic_cooldown
discord.ext.commands.CommandOnCooldown
discord.ext.commands.CommandOnCooldown.cooldown
discord.ext.commands.CommandOnCooldown.retry_after
typically you dont need cooldowns unless your code does something else that counts against an APIs ratelimit or is otherwise heavy on compute
SQL queries take place on the backend so just don't want the workers being unecessarily taxed
I want to have a job get added to a scheduler in one of my cogs, and was gonna put that logic in cog_load, but i'm realizing pycord doesn't have that. Would it make sense to put this logic in the cog's __init__ method?
Yes. You could also wait for on_ready in the cog
oh, like i can just throw
@bot.event
async def on_ready():
directly into the class or something?
@commands.Cog.listener()
async def on_ready(self):
you would want to throw a once=True in the listener
What does your situation look like? You could also add it to the setup() function instead of in the cog
I was planning on putting it in this cog because the scheduled job will be auto posting a leaderboard
When you say "job" are you talking about ext.tasks or your own system?
And are you planning on running the job ever X seconds?
i want to have it essentially invoke the weekly command every friday at 4pm ET. So i was gonna schedule it with apscheduler. ext.tasks didn't seem equipped for that to me
Yeah, init, event or setup should all work. init is probably the easiest.
oh so you think it's fine to just dump it in the cog's __init__?
I am not familiar with apscheduler but if the add job function is not async then it should be fine. The cogs init gets called once when the cog is added to the bot so it seems like a good place to put it
gotcha
Anyone else having issues playing audio files within channels on latest discord version (Android) ?
Like with a bot or on discord in general?
on_shard_disconnect fires everytime the shard disconnects
on_shard_resumed fires everytime a shard resumes
In general
This function can be called many times without a corresponding on_connect() call.
This is relevent as well
seems to work for me
I just see this now, no longer any playback interface
I dont think mobile ever had audio file playbacks
Note: there is a difference between sending a voice message and an audio file. A voice message will work on mobile
mobile has audio file playbacks
at least in ios
Huh, I might be wrong then.
why is interaction.user.id not giving me the correct id?
i don't understand
675238101253226500
instead of
675238101253226496
it's like rounding my user id
to the nearest 100
please help
Code?
for userapps, can i somehow get a event if a specific message of the bot was deleted?
Not if the bot isn't even in the server
so also not in dms? rip
That would make it a user bot technically lol


