#Basic Pycord Help
1 messages · Page 73 of 1
ah :(
is it possible to get guild data from a autocomplete func discord.AutocompleteContext?
so i can return like [role for role in ???GUILD??? if role.id in allowed_roles and role.name.startswith(ctx.value.lower())]
yes, check https://docs.pycord.dev/en/stable/api/application_commands.html#discord.AutocompleteContext
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 tried it over the interaction attr interaction.guild but it didnt work
"didn't work" means what?
is this a guild install command or a user install command?
im so fck confused, it worked now
i got list index out of range first
i dont know how and why
show and we can help
print(f"[DEBUG] guild: {ctx.interaction.guild}") this is what i did now and it gives me the guild object ✅
but before i asked here i tried it already and it gave me the "list index out of range" error
very weird
If you can reproduce the error it might be useful for a bug report because nothing in the snipets you provided would lead to that error
i have no idea how this error is supposed to have come about... the guild attribute is not a list
i know, i will check if i can reproduce it
as i found out, i cant return discord.Role objects from the AutoComplete? is there a other way to only show specific roles in a slash option?
if use discord.Roles, it shows all from the guild
make it string optionchoices and let the values be their IDs
that's the only real workaround
^ this would also allow users to copy paste the ID if they want
lol true, any way to fix this?
fix what
that's not an error that's a feature
you have to validate the input anyway, autocomplete doesn't validate anything
why change it? you can work with an id
I think he meant only use the role like choice
And not let the user add new things
hello, im having problem with SlashCommandGroup. when i used the "commands.Context" on ctx im having a problem.
wrong typehint; either remove it entirely, or use discord.ApplicationContext
thank you
@devout badger it is only on master as of now
https://github.com/Pycord-Development/pycord/pull/2501
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
Master branch install ^
Hi,
I have started programming again after a long time and wanted to rewrite my discord.py bots to pycord. In doing so, I have already encountered some errors that I don't know how to fix.
If I have the following function:
await bot.change_presence(
activity=discord.Activity(type=discord.ActivityType.watching, name=f "about {server_count} server"),
status=discord.Status.do_not_disturb)
then pycharm gives me the following error: Expected type ‘Status | None’, got ‘str’ instead
The status does not change either. Can someone help me here?
pycharm has been a little odd on the latest update
it detects enum values (Status is an enum) wrong when passed to (correct) arguments
its just a pycharm bug
Oh, that's right. The fact that the status hasn't changed was down to me. Sorry about that.
Okay thx. :D
oh i didnt even see it didnt work first lol
also you have a space after your f of the f string, dk if that breaks it
WTF? Okay i will try it.
yea that breaks it, you cant have a space between the f and the "
i expect the answer will be no, but is it at all possible for a command to have some sort of image preview or whatever based on the arguments you've put in
no
alright
hi, is there any hosted documentation of the components-v2 branch?
all PRs have doc previews https://pycord--2707.org.readthedocs.build/en/2707/
alright, thank you!
does py-cord[speed] already include uvloop?
install it, then install uvloop, and see if its already installed 
wow lol i figured itd be more
I have a utils file that allowed me to create common "types" of embeds easily. Now that I am converting to components v2. I would sometimes combine an embed and a view, now I would not be able to do that
async def error(traceback: str, **kwargs) -> discord.Embed:
e = discord.Embed(color=0xFF0000, title="Error")
e.set_footer(text="Report This In The Support Server")
e.add_field(inline=False, name="Error:", value=traceback)
return e
I have 2 options:
- Accept a view argument
async def error(view, traceback: str, **kwargs)and put the given view "below" the rest - Make a util function to add together 2 views
Opinions?
i was kinda tempted to overload the + operator to allow you to combine view children
though i think with how children work the old view on the right side of the operation would lose its ability to run callbacks
that would be ideal, if the callbacks could be saved
I might be very confused what the actual topic is but I find overloading + really bad practice
it should rather be done with a function
I guess the other problem would be timeouts and other methods in a subclassed view
It's do able using setattr
Timeout shouldn't matter I think
I had written the following 3 years and afaik it did work
https://mystb.in/60dc827b98ff08e0dc
for dpy but should be the same
I was planning on releasing it as an extension hence the whole documentation and stuff
view.steal_children(view2)
..adopt..

Hello, is the version of pycord in the main branch stable? That is, if I use it in production, it won't break at some point.
the github master branch should never be considered stable
It is pretty much stable as of now though, just make sure you don't auto update on master branch
yea if you do it at all, bind to a specific commit
and even then, bugs can definitely still happen more frequently than on actual releases
In general yes, rn no
Three different answers. Awesome
well i guess they're not wrong
- generally speaking, master should be considered breakable at any time
- at the current moment, to our knowledge there are no issues
- if you do decide to use master, it's better to bind to a commit to avoid unintentional updates (and this is good practice for anything you stick in requirements.txt, version binding is cool)
Idk
?tags audioop
There are no tags that match your search.
?tags
Audioop?
.tag audioop
Pycord 2.6.1 may work with Python 3.13, but it is not officially supported and can cause various issues. Until Pycord 2.7 includes official support for Python 3.13, it is recommended to use a previous version.
For voice features in Pycord versions before 2.7, you might need to run pip install audioop-lts. Some users have reported issues with voice features when using Python 3.13, so ensure that you clear the __pycache__ and .pyc files before running your bot.
That one?
Yes thanks
wdym
There is a guild.fetch emoji but not a get emoji
it's bot.get_emoji
some minor exceptions but yeah
Yep but why isn’t there a get emoji for guild ?
So I can add in my pr guild.get_or_fetch(discord.GuildEmoji, id)
idk they just didn't think there was a point
if you really want we could add it but it'd be rather useless
So I could just add the get method also in my pr or it’s just useless
Ig it might be useful, I’ll see to add it inside my pr
you could also literally just do bot.get_emoji(...) or await guild.fetch_emoji(...)
yeah like the older servers and their default channel e.g.
Ik, I do that inside my code
But Bob ask for a feature for a better get or fetch
So I just made one using their suggestion and old commit
idk why i thought that, there is one
well it was and then it has been removed
Hello, the docs say discord.Interaction.user will be None in PING interaction? What does ping interaction mean and how is it done? https://docs.pycord.dev/en/stable/api/models.html#discord.Interaction.user
I believe the ping interaction is for bots with interaction URLs, I dont believe users have to do anything with it unless they want. It is a way for discord to know if your bot is online
oh okay so in regular slash commands / buttons etc it is guarenteed to not be None right?
when they are ran
yeah
alr thanks
hey, how do the ids in the components v2 work? are they per interaction? Like when my bot is chatting with one person and has 3 components, numerated 1,2,3 and chatting with a second person do they share the component ids or not?
ids are per message
okay, thank you!
Is there any way to get emojis, only emojis uploaded to the discord bot?
You mean app emojis ?
yep
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
The last one here
is that in dicord.Bot class?
(in master branch)?
yes
do sku's have to be fetched with bot.fetch_skus()? or are they chached somewhere? because when i call bot.entitlements() the Entitlement has only the sku_id and not the name or something else
are you on master ?
because i think there is a lot of issue about entitlment on 2.6
2.6.1
well i cant really help you with that, but for sure someone will
you have to fetch the skus, then save them in variables if needed
How to make it so that a command can be only used by a member with a particular role?
I've gone through the docs but I couldn't find anyhting
has_role
or has_default permission
or just from discord settings
Here's the slash perms example.
oh okay
What do you not understand at the ctx.author stuff?
like it's related to context or something and it gives info about the author and guild
i don't understand much about async def tbf
you should first learn python
i do
.tag lp
Resources For Learning Python
- Official Beginner's Guide
- Shortcut to guide for people new to programming and people with experience programming
- Official Tutorial
Other Resources To Learn Python
- Automate The Boring Stuff for complete beginners to programming
- Learn X In Y Minutes for people with experience programming
- Swaroopch is a useful book
- Code Abbey has practice for beginners
- W3Schools is a good resource for general use
def and async def is pretty much the same at the end, one is asyncio and the other is not
oh okay
i know like the basics of api
like the basic requests.get(url) and then u get it into a json
is that enough
or should i know mroe
requests is not asyncio
yea hwo to learn that
so it would block the whole bot
asyncio
no, see what i mean is
i know the basics of python
like functions classes and stuff
would that suffice
You should set this up via the discord UI.
Server Settings -> Integrations -> Your Bot -> Your Command -> Set everyone to cannot use and your role to can use
okay
This way you do not have to change the code or create your own permissions system
The one thing you need to do most importantly is to read the docs, and not ask every single question here which is easily findable with the docs, because it slows both you and us down
i've been reading docs, i just couldn't find the roles here and that is why i asked here
what roles
nono
like
uh only a perrson with certain role should be able to u se a paritcular command in the bot
i couldnt find that in documentation
do what wolfy said for that
you can technically do that using a check but for slash commands, the way wolfy said is much preferred
ah ok
Confirming: webhooks can't reply to messages, only send new messages?
I don't see any source message context in the webhook params https://discord.com/developers/docs/resources/webhook so not even 'reply by reference'.
As I feared! Alas. Thanks
they can send, edit and delete messages (only for messages sent from that webhook)
Ok so freshly installed py-cord;
ModuleNotFoundError: No module named 'audioop'
trying to generate a template bot using;
import discord
import os # default module
from dotenv import load_dotenv
load_dotenv() # load all the variables from the env file
bot = discord.Bot()
@bot.event
async def on_ready():
print(f"{bot.user} is ready and online!")
@bot.slash_command(name="hello", description="Say hello to the bot")
async def hello(ctx: discord.ApplicationContext):
await ctx.respond("Hey!")
bot.run(os.getenv('TOKEN')) # run the bot with the token
the literal example on the guide
and it fails using the error shown in the beginning
Just for sanity what python version u got?
install audioop-lts
3.13
thanks lol
3.13.1
Im guessing it has something to do with newer python versions?
audioop Deprecated since version 3.11, removed in version 3.13
Ah-
and Pycord still relies on it
oof
one more reason for 2.7
but at this point I legit gave up hope
if I need something really bad now I'll switch libraries
yea, but my patience is nearing its end
I mean it all depends on lala soooooooo
it shouldn't
not really
it depends mainly on the reviewer
if they can all review all pr and add it to the master
and who can make a pypi release?
2.7 will come faster
before making the release all review has to be made
it shouldnt but sadly she's the only one who can because theres well bob who's inactive a lot
Is pycord already support the component stuff?
No, but it is avalable in a PR
Components V2 are under development in pycord and aren't yet included in the official releases on PyPI or the master GitHub branch. However, you can access the features now by installing directly from the pull request #2707. To do this, use the following command: pip install git+https://github.com/Pycord-Development/pycord.git@refs/pull/2707/head Please be aware that this is a development version and may contain bugs, feel free to report them by adding a comment to the pull request.
@eternal kite
As Luma said, you should check wether you don't have unnecessary intents.
the intents im using is just members intent and that's all
the issue is that the memory usage starts from 100mb when i restart my bot, and it gradually increases to 1gb if i didnt restart it for a couple days, so im assuming it's the commands used by players which caused the memory usage to increase
#1316463699518816287 this may be related
It can just be the cache
and my commands doesn't store anything as well
members cache can get quite big depending on how many members there are
i only chunk members when necessary
Can you run this code as used by the other member after using the bot a little and letting it run ?
import gc
leaked_objects = [obj for obj in gc.get_objects() if isinstance(obj, discord.ui.View)]
print(f"Leaked Views: {len(leaked_objects)}")
I wanna see if it is an issue with views or not.
maybe also take a look at this: https://github.com/bloomberg/memray
alr I'll try it once im home
You can also look into https://docs.pycord.dev/en/stable/api/data_classes.html#discord.MemberCacheFlags but I am not sure if 8000 users would be that much
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...
8000 members is pretty small to be using 1gb ram, but it is 700 servers so i suspect it's higher than that...?
it rises to around 80 but decreases back, and it never surpass 100
8000 is the chunked members
i perform a lot of pil manipulation, could that be it?
Ig they might be the resin
do i have to use image.close() every time after using it?
i thought it gets deleted when the function finishes running
if you open a file you have to close it unless you use a context manager which you absolutely should
Okaay thanks.
Btw is there a way to get the person which triggered the / command from an other bot?
It should be in the interaction meta data
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 ...
Wait how can you know if someone trigger a slash command from another bot ?
whattt
didnt now that
good to know
I’ll check. Thanks
discord.components.SelectMenu
discord.components.SelectOption
discord.Message.components
discord.AutocompleteContext.interaction
discord.Interaction.is_component
discord.InteractionType.component
discord.SlashCommandOptionType.integer
discord.SlashCommandOptionType.mentionable
discord.SlashCommandOptionType.attachment
discord.ext.commands.HelpCommand.send_bot_help
discord.ext.commands.HelpCommand.remove_mentions
discord.ext.commands.HelpCommand.get_destination
discord.ext.commands.DefaultHelpCommand.indent
discord.ext.commands.DefaultHelpCommand.shorten_text
discord.ext.commands.DefaultHelpCommand.add_indented_commands
@ebon swift #app-commands
sorry >< (can't delete)
how ?
like any other message
you cannot delete a command from a bot
pretty sure you cannot, might be different for user apps
did they change it??
never been able to do that
they actually did briefly allow you to delete your own command responses on guild apps, but it got huge pushback and was reverted
ahh
I’m trying to make a basic ass starboard bot, how would I check for messages in all channels for a star reaction? I’m blind and probably aren’t seeing smth lmao
you should use the on_reaction_add listener
https://docs.pycord.dev/en/stable/api/events.html#discord.on_raw_reaction_add
This as well for when the message is not cached
This section outlines the different types of events listened by Client. There are 3 ways to register an event, the first way is through the use of Client.event(). The second way is through subclass...
followed yt thing for some guidance, i fetched the message and it.. gave back nothing?
What comes after that..? You're putting things into variables but you don't show what you're doing with it
Well it looks like it at least understands that the message was starred. Are you sure the message that was starred had content? (e.g. wasn't a message with only an embed)
probably don't have message_content intent
Ah-hah ,I always forget about intents
Hi, is there any way to check someone's tag with pycord ?
I'd like to unlock special features to member who are using my tag on my server
with a bot that can add/remove a specific role to users according to their tag
I think clan related stuff was at some point? decent chance we see the new boost features on api but no guarantees
HOLY SHIT THANKS SO MUCH
https://docs.discord.food/resources/user#primary-guild-structure not officially documented though
you can probably somehow get it with a raw api request but no guarantees
@lean garnet
thats how to get the tag, there's a few more things about it if you print raw_user["clan"]
Thank you very much, I'll use this !
keep in mind it could break anytime
because its not documented
i do expect them to update the "clan" thing to something different
itll probably be under a different name
yeah I see, it's only for my server for now, not a public bot (or at least not yet)
so if it breaks it won't be a huge issue
will be None if there's no tag btw, so no need to check for none exceptions
or rather no attribute* whatever you know what i mean
I see, thanks
Is there an event for unhandeled interactions ?
wdym
No, you would have to override on_interaction
hai so thsi is probably youtube tutorial/me being a dumbass syndrome but, my app doesnt respondd when i do the slash command and select a channel, any ideas?
you should defer your interaction
at the top of your function
await ctx.defer()
now he thinks for eternity 😭
If the cursor.fetchone() function returns a falsy value (eg. None) then the command will hang
it was indeed none
The database does not have a row containing the guild id
Which is why its None
OHHH
You need to add a row to the table containing that guild's ID
you should really use a db helper function/class
else you're duplicating so much code
Is there any fast way to get every emoji in a message as proper Emoji object?
not built in, gotta regex - <a?:\w{1,32}:([0-9]{15,20})> with re.findall should return a list of IDs, then bot.get_emoji will work if your bot has access to the relevant emojis
uhhh set_image rather than thumbnail
but yeah, you send multiple images embeds with matching urls
oh yea i just noticed that too
guhh do you have the snippet for that
i forgot the tag / command
f = discord.File("some_file_path", filename="image.png")
e = discord.Embed()
e.set_image(url="attachment://image.png")
await messagable.send(file=f, embed=e)```
im so smart
You can make multiple images appear in a single embed by matching their url attributes
first = discord.Embed(url="https://google.com", description=..., color=...)
first.set_image(url=...)
# etc. etc, do whatever you want with your first embed
second = discord.Embed(url="https://google.com")
second.set_image(url=...) # do NOTHING else with the second embed
await ctx.send(embeds=[first, second])
```This works for up to 4 images at once.
up to 4? dangit
and this was recently patched to render on mobile too
10 is allowed in mediagallery
cv2?
mhm
2.7 cant come soon enough
im a bit dumb i forgot you can set image by url godsh
marvellous
it seems like even closing the image my ram usage still increases overtime
also what is this new gradient role color thingy
Hello everyone,
Can i have a url of documents on pycord for these components?
Thank you in advance💯❤
.tag cv2
Components V2 are under development in pycord and aren't yet included in the official releases on PyPI or the master GitHub branch. However, you can access the features now by installing directly from the pull request #2707. To do this, use the following command: pip install git+https://github.com/Pycord-Development/pycord.git@refs/pull/2707/head Please be aware that this is a development version and may contain bugs, feel free to report them by adding a comment to the pull request.
Thank you
np lmk if anyhting else
Is there anyway with or without pycord to remove access to users
Like the user installs
what do you mean ?
ooo i see now
no idea how to remove them from here, however you can just create a global check to only make ur id working
not possible
you can't do that with guild apps either (the bot leaving the servers =/= deauthorizing)
essentially, you can't forcefully deauthorize for someone else
what happens then? if the bot leaves but is still authorized? like, is that any special state or
hm, thought they'd be able to join back or smth
from a quick check kicking it does deauthorise, but if the bot isn't added as a member already then that's not possible
Hey while coding my discord bot I get moments where I want to raise errors, for example I want to see if a user has a role, if the user don't I want to raise an error, what would be the best option:
- Use a basic python error ? ValueError etc..
- Use a pycord discordExeception ? MissingRole etc.. (If those exist I couldn't find it in the documentation can anyone lead me to them?)
- Make my own set of errors ? which feels a bit weird since those would look like duplicate of pycord execptions
What's the reason you wanna do that for
for better logging and overall error handling ?
I want my bot to be resilient to logic flaws I might have forgotten to implement and I think it's better to have error raised than printing in each function ("something wrong happened")
just check if they have a role and then respond that to them
the role missing was an example, in general if I want to raise an error in my code does pycord have a set of exceptions I can use ?
I know but what if I want to raise an error ?
why raise it if you can just handle it then and there tho
Missing role is ok, if this role is specific to something like premium it
And you use it often make ur own one PremiumRequieredError should be better
the function raising the error shouldn't be the one handling the resolution that better to avoid redundancy
is there a list of the pycord exception I can use ? I can't find MissingRole exception in the documentation
i mean i just let all my errors go into on_application_command_error and handle it from there by checking against the pycord exception classes
that, or i handle it where it happens
i guess you could manually raise the pycord errors but i have no idea if thats intended
Maybe in discord.errors
that's the kind of situation I'm in :
# I'm a cog
def do_something():
# part to do thing before the overall implementation
try:
my_specific_function()
catch discord.NotFound:
# The error happened I can handle it cause I'm `do_something` function
catch ????:
# Another error happened I can handle it cause I'm `do_something` function
def _my_specific_function():
# I do actions and interact with the discord
user : Member|None = discord.utils.get(client.get_all_members(), name='username')
if user is None:
# I can handle the error cause I'm `my_specific_function`
# I can raise an exception to be handled by the caller
raise discord.NotFound("User not found")
else:
# I can do something with the user
pass
Feels weird to relay on a non caller function and get out of the scope of my actions
my first thought would be simply returning None and handling None in the function above, ideally the command directly (just pass None all the way up ig) so you can respond to the user
MissingRole does indeed exist under ext.commands.MissingRole https://docs.pycord.dev/en/stable/ext/commands/api.html#discord.ext.commands.MissingRole
this is typically used in the @commands.has_role check
is this a bad behavior to raise it myself at some point ?
not particularly
okay thank you that's all I wanted to know
as long as you handle it appropriately, you can use it
thank you toothy too I revised my code to make it less tendeous to use the raising of errors
that docs page also has several other exceptions and utilities like check decorators which you might find useful, so feel free to read through
can you give me the link please ? osorry I struggle to find my way in the doc ^^
yea I was also thinking about checks but I wasn't sure if it applied here mb
https://docs.pycord.dev/en/stable/ext/commands/api.html# for reference
https://docs.pycord.dev/en/stable/ext/commands/commands.html goes into more general detail on ext.commands
Hey! Is it possible to use chatgpt and gemini api in one bot to generate responses?
sure, why not
Oh and is there wiki about this?
Ok thanks
lets you switch the API url too so you can use gemini without changes
Thanks!
i do that too actually
the only thing you need to keep in mind is to use google's openai-compatible API route, AND gemini doesn't support image input via url, you have to base64 it
ok and thanks for helping ❤️
Is there any way to get bots to join guild application threads? (Even if undocumented)
what is guild application threads?
You can either approve, deny or make a thread with the applicant
I couldnt find anything related to that in the docs
Guild settings > Access tab
oooo i understand that now
You can enable applications there
Maybe take a look at discord.food
Userdocs?
Yes
you mean the DM group that you can create from it?
Yes
?tag git
why
Logging purposes & to send components into the thread.
bots can technically create group dms, but it requires every participant to grant the bot the gdm.join oauth2 scope and so was never implemented in pycord
you could maybe use a user app for the last part, but only manually
When using webhook.from_url, it doesn't allow me to send views, even though it is application owned, just pycord doesn't know it. How can I get around / work w/ that ?
this is supported in the cv2 pr
webhook.send didn't have the view param before since they couldn't use any components before
(and you don't have to use cv2, you can still use v1 link buttons on webhooks)
X
Cause I store the url in my db
yeah
is it not possible to use ctx.respond in on_application_command_error?
sure is possible
discord.ui.Container(color=discord.Color.red())
Thanks
well, i'm getting a discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction when I try to do so
That means you shgould defer
await ctx.defer()
at the top of the commqand causing the error
or at least at the top of your error handling
That error happens if you take more than 3s to respond
well it's responding in less than 1s
well something isnt responding in time
This interaction failed
whats the error of the command causing it
empty message
cant you just, fix that in the command lol
if i put it in the on_application_command_error then it just moves the error to that line
if i put it in the command, it gets stuck thinking and also sends a message with ctx.send
it's a button, right?
what is a button?
can you just show your command code rq
This seems like it'd be easier if you just showed the- yeah
ideally you rarely ever use ctx.send
i know what's causing the error in the command
i'm just asking if using ctx.respond in on_application_command_error isn't allowed
it is allowed
ok apparently it works if the defer is in the command (and i actually tell it to send the error message correctly)
but with no defer the interaction just fails and there's no error response
yes, screenshot ideally if it isnt too long
asking for a screenshot of code is probably what i least expected
Experience told me to never trust anything people send here if it isnt an actual undeniable screenshot
so many times they changed things "for clarity" and that ended up hiding the mistake
that's crazy
just support server things
or they write it from memory (???) and obv its different than the actual thing
tried to include whatever I thought was relevant lol
if you want the full code i can link you to a github repository, though it's gonna have some slight differences
does that function you call ever respond anything
because if not thats a first case where you never respond
i can tell you that in this case that function definitely isn't called
but if it is called and doesn't immediately return True, then it does respond
async def bot_channel_warning(ctx: discord.ApplicationContext) -> bool | None:
"""Give a warning if the command is not run in a bot channel (if any exist).
If a warning was not given, or was accepted, returns True. If declined, returns False. If timed out, returns None.
"""
if ctx.guild_id is None:
return True
guild_id = str(ctx.guild_id)
if (
guild_id not in bot_data.bot_channels
or len(bot_data.bot_channels[guild_id]) < 1
):
return True
channel_id = str(ctx.channel_id)
if channel_id in bot_data.bot_channels[guild_id]:
return True
confirmation = BotWarningView()
await ctx.respond(
"❗ you are trying to use a command in a non-bot channel. are you sure?",
view=confirmation,
ephemeral=True,
)
await confirmation.wait()
return confirmation.value
i misspoke
i meant that it immediately returns true so it doesn't really change anything
alright
the code is a bit bodged due to circumstances
normally the defer would happen after the function
also just a general code tip, put as little code as possible into a try block
mmm, yeah, though this is a bit of a "if anything gives an error, just respond with an error and stop"
i supposed i could use try except else for that
you never respond in the command function, that makes it kinda harder to debug
cant immediately see the issue
the respond is located in frg.send_message (which is at the bottom of the file i sent)
hi, im trying to write a discord.Option autocomplete function. i am returning exactly 1 value in the form of List[str], but discord is saying that no option matches. any idea why? i can send over my code, but nothing is hardcoded so it wont make sense i suppose
im using autocomplete=discord.utils.basic_autocomplete(func), could that be causing the issue?
also i should clarify, when i return all the possible options (for example when nothing is typed in), it works just fine and shows all of them
Can you show func
@staticmethod
def rank_level_autocomplete(ctx: discord.AutocompleteContext):
rank_levels = ranking_data["rank_levels"]
if ctx.value in rank_levels.values():
return [rank_name for rank_name, rank_value in rank_levels.items() if rank_value == ctx.value]
return rank_levels.keys()
rank_levels is in the form of {"text1": "1", "text2": "2", ...}
eh
static method because its in the cog class
it's in a separate class from your command?
no no, same class
then you don't need it
dont need what?
just do autocomplete=rank_level_autocomplete and add the self param back, remove staticmethod
(maybe you can keep it as staticmethod but i can't remember; regardless, it's not required)
also it should ideally be async
even if it has no awaits?
async def rank_level_autocomplete(self, ctx: discord.AutocompleteContext):
...
``` like so, yeah?
nice it works, thanks
allgood
is there a point to raising an error in on_application_command_error if it's being logged
why raise an error if you're already in an error handler tho
idk i just remember reading that somewhere
You could log the traceback
I used it to raise it again tho for it to stay in the console
And using the error handler just to inform the user
Whatever fits your needs, really
I'm trying to check if a user joins a voice channel, for a test I used this listener:
@commands.Cog.listener()
async def on_voice_state_update(
self,
member: Member,
before: discord.VoiceState,
after: discord.VoiceState,
):
log.info(f"Voice state updated for {member.name} before: {before} after: {after}")
the listener isn't called when I join any voice channel, I don't see my log . Am I missing something is there any requirement for it to work ? any intent that is mandatory to check on voice channels ?
Ig you maybe need presence intent ?
I'm not certain
I'll try it
doesn't work :/
doesn't feel like an intent issue because when give all intents it still doesn't work
I added another listener _ontyping() to test if the listeners wher loaded and this last one works only the on_voice_state_update() doesn't
I'll do if I find it !
I was not able to reproduce your issue with the following code:
import logging
import os
from dotenv import load_dotenv
import discord
load_dotenv()
logging.basicConfig(level=logging.DEBUG)
TOKEN = os.getenv("TOKEN_2")
intents = discord.Intents.default()
bot = discord.Bot(intents=intents)
@bot.listen()
async def on_voice_state_update(
member: discord.Member,
before: discord.VoiceState,
after: discord.VoiceState,
):
print(f"Voice state updated for {member.name} before: {before} after: {after}")
if __name__ == "__main__":
bot.run(TOKEN)
Can you try and tell me if that still doesn't work for you ?
@echo wraith found it ! I had an identation issue !
Alright
sorry for the disturbing
np lmk if there's anything else
I'll do !
so i currently have a on_application_command_error event to handle errors, is it possible to let it show a full traceback instead of just the exception?
the default handler uses the traceback module py traceback.print_exception( type(exception), exception, exception.__traceback__, file=sys.stderr )
Sentry
oh so I can make it show the exact line of the error?
how can i make the role option as list, so i can add multiple role?
@ticket.command(name="setup", description="Create a report ticket system")
@IsAdmin()
@option(name="role", description="Role that can access the ticket", required=True, type=discord.Role)
@option(name="category", description="Category where the ticket will be created", required=True, type=discord.CategoryChannel)
async def ticket_setup(self, ctx: discord.ApplicationContext, role: discord.Role, category: discord.CategoryChannel):
....
not possible, sorry
Can there can be defaults in select type for things such as default userselect?
Alright
When using Webhook.from_url can I use an existing session from the bot or am I required to create my own? Also is there a better way for a bot to manage a webhook other the saving and loading from url?
it's silly, but you can use bot.http._HTTPClient__session
(class vars that start with __ are considered truly private, but can still be bypassed by using that notation)
that's also how the library handles webhooks in stuff like channel.webhooks so there's nothing really wrong with it py def from_state(cls, data, state) -> Webhook: http = state.http session = http._HTTPClient__session proxy_auth = http.proxy_auth proxy = http.proxy return cls( data, session=session, state=state, proxy_auth=proxy_auth, proxy=proxy, token=state.http.token, )
👍
Also answered the second half of my questions. Bot.fetch_webhook exists
yeah if you have the ID
if you don't want to fetch for whatever reason then from_url is perfectly fine too
I am setting up error logging to a discord channel
ahh fair
so it is only 1
Good afternoon, I'm trying to review the topic of new features. To be able to use command messages in private chats with other people. How do I manage it?

do you talk about user app ?
Yep
Here's the slash users example.
@valid panther ⬆️
From which version is it available?
2.6, i think
It's time to make the version jump, I'm in 2.4
jesus what

isnt that like 2 years old at this point
i mean 0.2 thing is not that much generally
luma, we are talking about pycord
but in pycord its like 0.1 every years
where minor versions have breaking changes (?????)
no joke man
better than having no update at all
pycord 3.0 before 2.7 ;)
do you just not update your packages
...yes?
ofc
i dont think you will have to change a lot of thing
What you want is not possible until 2.6 so yeah
i mean if you want you can wait for 2.7 before updating but we dont know when it will be released
When was 2.6?
I think last june July 9th, 2.6.1 was september
If I make the version jump to 2.6, the change to 2.7 should be minimal
man if pycord respected semver you wouldnt need to worry about having to make ANY changes
How fast time flies
I dont think there are any breaking changes in 2.7 other than dropping support for python 3.8
2.6, bridge tho
bridge options
but atp i have no idea who still uses prefix commands
Bridge is so broken that breaking changes dont make the code more broken
actually 2.5 was breaking too
What would you do, if slash commands are not working anymore for a longer time?
that wouldnt happen
"what if one of the major features of the platform just didnt work for a long time" is not something that happens lol
all of them
All notable changes to this project will be documented in this file. The format is based on Keep a Changelog, and this project adheres to Semantic Versioning when possible (see our Version Guarante...
this is just bs
if there was even a hint of caring about semver we'd be at like 4.0 minimum
when possible ;)
thats not something you can do "when possible"
either you respect semver or you don't.
and pycord does not
the when possible here just state that this will be respected only for public functions, however its not respected
did you ever read semver?
i was talking about pycord message
pycord specifically breaks semver exclusively when it comes to the public api
The first thing to keep in mind is that breaking changes only apply to publicly documented functions and classes.
no shit
that's why i wrote : however its not respected in my message ;)
you can still break semver for the backend code
marking patch changes as minor versions for example, or minor changes as patch
not breaking changes, but breaking semver
well i dont really care about those thing as long that i have a library that is working, so im just waiting for 2.7 even tho it doesnt respect semver
i just want finally a stable release
Its just 3.8 eol
actually seems so
raw = await bot.http.get_user(member.id)```
Any info about ratelimits?
dont do it unless necessary
not sure about the ratelimit of fetching users but just avoid it
Ratelimits will still be applied here
everything done through bot.http is ratelimited
i need to get user guild tag
"clan": {
"identity_guild_id": "1044698006395555960",
"identity_enabled": true,
"tag": "STAR",
"badge": "66dd35e973cf6054f84b0edd73ac2b02"
},
"primary_guild": {
"identity_guild_id": "1044698006395555960",
"identity_enabled": true,
"tag": "STAR",
"badge": "66dd35e973cf6054f84b0edd73ac2b02"
},```
whats the difference lol
the top one will go eventually
The second is also still technically in beta
is there an attribute for hybrid command in pycord (I know nothing but I have made small bots by using deepseek to write my code 😅😅)
currently my bot responds to prefix cmds but I want to make it such that I can use slash cmds as well
can anyone help?
Concept
Additionally I recommend not using AI for discord bots
umm.... why ?
Generally AI is not aware of the newest features that discord has. In addition much of the training material is poor quality (many online discord bot tutorials are terrible). There are also multiple python discord libraries and the AI can get them confused. And if you use AI you dont learn as quickly and it will take you longer to debug issues as you dont fully understand the code.
I took bio in my Sr. secondary school so I don't know anything about coding and I make bots only for troll commands like........ dragging someone continuously through multiple channels so for me AI works fine. Later I will definitely learn more in coding but for now I can't...... hehe 😅
till now all I've made is to troll my friends
Damn. Is there any way to reference an autocomplete from a different cog (or different class at all) in my command def?
Can't use autocomplete=self.target_cog.my_autocomplete because I can't use self.
CogClass.my_autocomplete
cog class is supposed to be the other cog you need
Yes, I am aware 🙂 I'm just saying it throws errors about not being defined.
from mycog import MyCog
how are you importing the cog ?
Which is doubly weird because it doesn't seem to error in my TYPE_CHECKING block. But when I place it outside of that, it whines
can you show me ur tree ?
because it might be possible that you dont really import the good thing from the file
make sure to put the full path or .__setup__ (if in the same folder)
the setup is my file name
bot
- main.py
\ commands
- treasury.py (class Treasury)
- developer.py (class Developer)
...
From my treasury.py, I'm trying to from developer import Develooper
Again, works fine in TYPE_CHECKING for doing IDE stuff, but complains at runtime when outside of it
is bot also a folder ?
also could you try from .developer import Develooper
with a .
Okay, from commands.developer import Developer works.
and .developer should work to
Well the IDE whined about it not being a package, so I didn't try
the . do the import from the current folder
Yeah I know. Just don't want to see any squiggles right now 😅
be careful because sometime the ide show an import somewhere but during runtime it import it from somewhere else
had this issue with commands.cog that was coming from lumabot.commands even tho i never import commands from lumabot
okay first of all why do you do exit() lol
do you want your entire bot to shut down if that's none
That's not pycord 🤓
that's why I asked in general
bcz python nerds out here
look at ur class
and if possible can you share us ur class definition ?
Because vscode does not know whether exit will “return” the code or not (because it can be handled in a try/except)
If you use a exit then add a return below it , it should fix it
as anonymous said, maybe the exit() is not considered as a return
Even if I add return after exit() (or vice versa) still error is shown
then maybe do a if self.query is not None
or a isistance str
or just put a # type ignore if nothing is slved
how is query defined?
will it be possible to include this in pycord ? instead of having to use the decorator or Option
async def test(self, ctx: LumabotContext, test: ["test1", "test2"]):
You should never do that
if you add / remove from test, it will persist across function calls
wdym ?
this would just be for passing directly inside the function def the list so i dont have to use the decorator to add choices = [test1, test2]
This also isnt correct typing wise.
This is probably what you want:
import typing as t
async def test(self, ctx: discord.ApplicationContext, test: t.Literal["test1", "test2"]):
...
But even this isnt ideal, if you pass different types of objects into the Literal
Yeah that’s what I meant
But will that work in pucord v
Like display it as choice ?
I highly doubt this is currently implemented if thats what you are asking
It should be already implemented ?
But it should be
Im gonna test than in a min
...why?
just use options
Ask Luma lol
...
people really are allergic against easy-as-fuck tools given by the library
especially luma
why tf would i want to add a fonction when i can just type hint this ?
- as anonymous said it should already be part of it
its nearing abusing typehints / defaults
so im technically just using proper python type hint
well its not implemented, i just test it
@frail basin
i might do a pr for that
this syntax should be preserved for actually setting defaults, not feeding into your urge to bend pycord to your needs
sadly for you you are not in charge of that
if maintainer think that it should not be add they will be free to let me know
why break existing python syntax just for the sake of .. zero gain at all
if as anonymous and me they think this should be implemented then it will be implemented
is it THAT hard to use options, which you should anyway for descriptions and stuff?
man pls just leave me alone
u have just been yapping for the last month and i cannot really stand that anymore
no you are literally just trying to bend the library to your very specific needs, constantly
.
good luck
just make a fork man
you have so many specific and weird wants and needs
literally fork it and you can do whatever you want
.
Using literal annotations would make sense for pycord to use choices by default to that
But not doing something like opt: str = ['smth']
ofc, this was made really fast and doesnt make sense at all
like im setting a dict as default value
You really shouldnt do that
I even sent you an example why not to
ik, that what i said
That applies to every reference type object
yeah, idk why i wrote that because that does not make any sense
i wanted to credit you on the github about this Literal, but i cant find ur account, can you help me with this ?
(in case credit is not english i meant shoutout)
I dont really want to be affiliated with that. I am on Toothy's side in this matter, the decorator is the intended way.
ok then, thanks still
poor luma just trying to improve the lib for everyone
Its just bad design imo
Plus, you kinda have to use the decorator if you wanna use a description, or anything else
like even setting options via typehints at all is not good practice imo
Apologies but I don't think we're ever adding this; your best option would be a function or subclass of Option that just takes the choices you want
The general direction of the library is to be more explicit in how users interface with discord, not less
no worries, i'll continue to use @discord.option then
You know that you're not required to use @discord.option just to present a fill-innable field when users type their slash-command, right?
The whole deal is that Py-Cord devs are not to blame: Discord's API exchanges JSON-encoded objects as (I think) UTF-8 encoded text with "Gateway" bots over Websocket connections. Py-Cord just translates the incoming JSON into runtime events with typed parameters, then translates outgoing function outputs back into JSON for transmission. So the difference between setting up an event-handler (or command-handler, call it whatever you want) with @discord.option versus just plain old input parameters is that @discord.option instructs the Py-Cord framework how to format the JSON object which represents that parameter when it transmits its command definition to Discord's API.
Your typehints in Python are useful to things with IntelliSense, like Visual Studio and PyCharm. Those type hints are only relevant to you as a programmer... even Python itself doesn't really care what data type you put in, and Discord will only give you or accept in return some kind of text-encoded string. Trying to scan those comments and thereby invent documentation comments for the Discord API would be a bit like giving everybody who buys a car the Hayne's Manual which contains all the schematics for every moving part in the vehicle.
im not blaming anyone, i was wondering if this could be a thing
Sure, I get it. I was just trying to expand on the explanation already given, because all Toothy really said is that they probably won't do it. I think I have a pretty good idea as to why they won't.
im only using decorator for list, so i was looking if there was a way to just not use it
to be fair im not listening to toothy anymore, im not saying his point is not valuable but i dont like the way he says thing in general.
You can always use annotated to
and it was logical in a way for me to continue to use typehint since we can already do everything with typehint expect choice/autocomplete
wdym ?
typing.Annotated
luma knows that..
and idk why you explain it in such an overcomplicated way lol
do you mean use typing.Annotated to pass choice from typehint ?
and discord.option doesnt set up an event handler or command handler or anything
what you are saying is literally not true
That's not what I said.
you literally said exactly that, almost word by word
It's a complicated process, and the way the Framework is designed to simplify it for you obfuscates the actual operations performed.
you love using big sentences to explain stuff lol
No, it's literally not what I said by any stretch of anybody's imagination but yours.
its really not as complicated as you make it
pycord literally just builds the options from whatever it gets, there isn't really a difference if you dont use @discord.option or if you do use it, apart from it giving you a way to actually pass option descriptions (etc)
Wow. THAT is literally what I said XD
in about 500 words
OK, you're blocked. I don't need this kind of trolling from somebody with a staff bit.
what you're doing isnt helping, its throwing around big words for braggings sake
and if you have been here even once youd knew luma knows the library enough to not need it explained to him like that
he had a valid point
what he said was the typehint should only be for me
and nothing related to library
there was no point in all his 1000 words
i dont understand why you have to be that mean with people
its just "heres many cool words i learnt used in semi-correct ways"
its literally just showing off, while being partly wrong
im not being mean, im sick of people acting like fucking smartasses like that
well @tidal pecan thanks for your explanation, it was greatly appreciate
the explanation was literally wrong
because pycord literally DOES use the typehints
if you do intoption: int it will be an int option inside the discord UI
so many words just to be fatally wrong
it does but i should not execpt pycord to use them since as he said its mainly for ide etc
I hope it helps. I know not everybody wants a deeper understanding than just what it takes to make Py-Cord work, but as someone who does want a deeper understanding I tend to target that audience.
thats what ive been saying all this time lol
the typehint methods (both!) to define command options are just bad practice
and that's true, in fact typehint are for documentation and more readable code
yet you are wrong in your main point lol
oh well they left anyway, good riddance
i understand the point of the typehint and so why nelo etc are not in favor of editing the lib to support typehint
luma typehints work to define option types
or do you specicially mean the literal thingy to define optionchoices
so thanks, its way more pleasant to have an explanation than just a dont do that
the explanation was just wrong
but who cares about facts anymore
just use like 500 words to explain a very basic concept and call everyone correcting it mean
"Don't touch the stove!"
"Why not?"
"DON'T TOUCH THE STOVE!"
looks at the stove
I have an idea: your feedback clearly isn’t welcome, so if you think they’re doing it wrong, let them go down that path of discovery
its not discovery, its just showing off and spreading false info
if you dont meet that with the appropriate response they will never stop
python in fact does not really care about typehint, its mainly to help us understand the code, and that was the ponit he was trying to show me
and if luma actually was a beginner in need of help, that overinflated "explanation" would not help at all
even tho pycord does support this typehint
Just leave it and go touch some grass
no, voidcaster is literally wrong
they said, in my own words now, "using typehints to define options would be <dumb>"
BUT PYCORD LITERALLY DOES THAT
im fine defi dw
That part is actually true. Pycord relies on typing in Options (and other places I’m sure)
yea, hence why im so mad their entire explanation ultimately went to the wrong conclusion
Well, let them figure it out.
cant if they block anyone showing em 😂
cat /etc/passwd
the thing he tried to explain me what more general (2nd part)
The way you’re reacting is immature. Just go do something else
you just leaked ur password gg
Pycord relies on typing but isn't typed
no, its unfiltered
its immature to use this stupid way of "explanation" just to throw around big words
Isn't STRONGLY typed :-D
Actually I saw something where someone getting a canned AI response on LinkedIn tricked the agent into sending the user’s ssh key
Hold ALT and press F4 repeatedly to gain instant Admin powers on any Discord server.
i think you mean python lol
or what
im waiting for pycord v3 pydantic + type everywhere
huh isnt the library pretty much typed across the board
at the very least public bits
LMAO
didnt work... what's the command for mac os
No not really even
i dont think i ever came across anything i used that wasnt typed properly
show an example
Hold COMMAND and tap W repeatedly
Q
i got tricked by that back in the day
it was supposed to "fix" my mic
wow
hm
i think its prolly because its a decorator
That dosn't mean it shouldn't be typed
yea
can I make the “default_member_permissions” in the SlashCommandGroup?
sub commands can't have their own default permissions, it has to be passed to the group
the other two can stay
oki doki
regarding the “has_permissions” decorator can be done in the SlashCommandGroup object?
well, you only need the has_permissions check if you want enforce it in every case
server owners can change the default permissions in the server settings
no, that's for each command individually
if you mean the internal checks from ext.commands, SlashCommandGroup allows you to pass a list checks to apply it to all commands in the group
example from slash_cog_groups py secret_greetings = SlashCommandGroup( "secret_greetings", "Secret greetings", checks=[ commands.is_owner().predicate ], # Ensures the owner_id user can access this group, and no one else )basically any function that returns a bool
oh yea I forgor
Is there a separate channel/forum for general bot-dev questions? I'm using Py-Cord to build the bot, but that's not what my question is really about.
you can ask in this forum anyway
discord don't generate previews of images, anyone aware of this?
I'm not clear whether this is a pycord or bot question, or just a request for help with Discord?
thx
How would I implement a global error handler for the entire bot? When an error occurs in a button callback it does not seem to trigger on_error. I thought it would as it is an error in the interaction event
I guess it is possible that I am overridding it wrong though
class SurveyWolf(discord.Bot, ABC):
async def on_error(self, event_method: str, *args: Any, **kwargs: Any) -> None:
...
I subclassed the view and added the error handler to it
im p sure you just do @bot.event no?
i think overriding the entire function breaks everything
no, on_error is a standard Client function rather than event
on_error triggers on events, but because view callbacks call their own on_error it sidesteps Client.on_error
I am looking for it to be more global, I was trying to figure out how I could catch ALL ignored exceptions but I think pycord does too much in the background so I settled on on_error and on_application_command_error
Ah ok
I will make an feature request issue for now 👍
That would be a really neat addition for everyone really
in the meantime either just edit view.py or subclass view to have the default on_error call client.on_error or so
I did some monkey patching for it to work
Client.on_error sucks because it doesn't even have an arg for the exception
typ, error, trackback = sys.exc_info()? lol
yeah but it doesn't match the other error handlers that explicitly pass the exception
True
Pls do it !
hey all ! I was wondering, what's the best way to add a has_role() over all a cog ? I know I could just add @has_role() to each of my commands. but I feel like this open the way to forgetting to add it and have some misuse of certain commands. (I was maybe thinking checks but I don't thinks they adapt well with decorators or the function under the @has_role decorator)
make your own version of the slashcommand decorator that adds it to every command its used on
https://docs.pycord.dev/en/v2.6.1/api/cogs.html#discord.Cog.cog_check and do the role check yourself
oh thats useful
Cogs have a lot of stuff that is rarely used
thank u
Is it commands.has_role for slash too?
If so, you can call the built check manually in cog_check too:
has_role = await commands.has_role(xxx).predicate(ctx)
Oh there are no lib checks for slash
because ideally those are handled in discords ui
I'll try that thank you !
all checks in ext work with slash
they just don't apply on discord's end
got bored and slipped it into cv2 teehee https://github.com/Pycord-Development/pycord/pull/2707/commits/097a60f9cfb727837bb12ecbfb738875a896c900
refactored ctx.command -> interaction.command, added interaction.view and interaction.modal, new events on_view_error and on_modal_error; these are called by default if you did not define View.on_error and Modal.on_error
Thanks :)
Does anyone know the rate limit for the fetch_invite() function or its underlying endpoint?
Specifically, how many invite links can be checked within a certain time frame?
why does discord do this? im using member.mention in the join event and sometimes (especially on mobile client) it shows the mention as unknown member, even tho they didnt even leave
yea then no
discord explicitly changed the client to stop rendering users you don't have cached
wait doesn't it fetch them on mention?
no
but it used to do that right
i thinkkkkkkk so but i can't remember
never worked in embeds, worked in normal text until a couple months back
Rate limits in discord are dynamic and intentionally undocumented.
ahh, thanks 🥳
Fell free to just try it
Also sometime on re-edit you can find some info
i was bulk checking 3k invite links and got rate limited 💔
even tho i was using 0.5s delay
No but like you do a script to understand after how many you are rate limit and for how long etc
Bulk anything is going to get you ratelimited
So after that you know what number/tome you can use
rate limit is based on ip ?
oke, i will experiment it
There is also by bot, guild, etc
Also if ur checking ur guilds invite etc you could use guild.invites, might be better
do you really need to fetch them?
yes, I've to check them if they are expired or not
But from where are you getting them ?
Guild where ur bot is not in ?
I run a bot called Dank Alert, which acts as a Dank Memer assistant. I use Dank Memer's Discovery API to fetch and store all server invite links. Recently, I added a feature that checks whether those stored invite links are still valid or have expired
I've saved 3.3k+ invite links on production
Ok I understand now
I’ll try to think about it
sure, but it's working if i fetch 20± invite links (already got banned for 24h, only on invite endpoint)
what is this even for
user can join those discovery server and fish for limited time rare fish
https://dankmemer.lol/discovery this page to discord cmd
and why do you save them
.


