#Basic Pycord Help
1 messages · Page 69 of 1
i'll just throw out some example then
I have figured out autocomplete
discord has no way of selecting multiple options in 1 arg
so instead of using a list of then, you make a separate bool arg for every spec
and have them all as default=False
it's kinda finicky, but that's more or less the only way
how does one make bool arguments again? just like uhh CPU=bool?
OH WAIT
@option("CPU", bool, default=False)
@option("GPU", bool, default=False)```etc. etc.
ya, I just noticed
got it
how do you define multiple embeds in discord.embeds?
or is it just discord.embed() x5 for me
send/respond have an option for a list of embeds
up to 10, maximum 6000 characters across your entire message
ohhh wait so
embed1 = discord.Embed(...)
embed2 = discord.Embed(...)
...
embeds=[embed1, embed2, embed3, embed4, embed5]
yep
got it
uuuuuuh, stupid question: how do you define color?
just throw in the hex code for it and call it a day?
discord.Embed(..., color=)
ya, but what to put inside of color
color=e62929 gets yellow underlined, color=#e62929 makes the rest of the code a comment
use 0x instead of #
ooooh, ty
0x is how you do hexadecimal in python yeah
otherwise the discord.Color class also supports RGB and HSV values
I have a question. I was experimenting with slash commands, but according to the official guide, in slash commands instead of using ctx.send () a ctx.respond is used. I would like to know if there is any difference, because apparently you can also use the ctx.send.
iirc .respond works for both undeffered and deffered
.respond responds to the actual interaction received by discord
.send sends a plain message to the channel. it doesn't count towards responding the interaction
is there an easy way to only allow the user who called the function to use the buttons on a view? i know i can use ephemeral but want everyone to still see it
yeah so something like this?
if interaction.user.id != self.user_id:
# Optionally, you can send a message or disable the button
await interaction.response.send_message("You're not authorized to interact with these buttons.", ephemeral=True)
return
was wondering if there was just an out of box decorator
there could be, but im not aware of any
yes like that
max_messages when you create Bot or Client
default is 1000
how would i delete the message?
interaction.delete_original_response
await interaction.delete_original_response() ?
gives discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook
ultimatley what i am trying to do is give use a view that is ephmeral, then when they click the button update it but have it go public... is taht possible or is approach to delete and respond with new message?
defer first, then delete
delete_original_response only works if you've already responded - defering counts as a response
interaction.defer() ?
hmm something not right
i first have this
@rps.command(name="unranked")
async def rps_new(self, ctx):
"""Start a new unranked Rock-Paper-Scissors game."""
view = RPSGameView(self, game_id=None, league="unranked", tip=None)
await ctx.respond(view=view, embed=view.get_embed(), ephemeral=True)
so am doing ctx.respond with the view
then in the view
class RPSGameView(View):
def __init__(self, rps_cog: RPS, game_id: int, league: str = None, tip: float = None):
super().__init__(timeout=None)
self.rps_cog = rps_cog
self.game_id = game_id
self.league = league
self.tip = tip
self.embed = discord.Embed(title=f"Choose your Move!", color=discord.Color.blue())
# Add each detail as a separate field, with Game ID first
self.embed.add_field(name="Game ID", value=f"{self.game_id or 'New'}", inline=True)
self.embed.add_field(name="League", value=self.league.lower() if self.league else "None", inline=True)
self.embed.add_field(name="Tip", value=f"💰 {self.tip if self.tip else 'No tip'}", inline=True)
# Add the choices (buttons) to the view
choices = [("🪨", "rock"), ("📄", "paper"), ("✂️", "scissors")]
for emoji, choice in choices:
button = Button(label=choice.capitalize(), style=discord.ButtonStyle.primary, emoji=emoji)
button.callback = lambda interaction, choice=choice: self.handle_choice(interaction, choice)
self.add_item(button)
async def handle_choice(self, interaction: discord.Interaction, choice: str):
"""Handles user's game move choice."""
await interaction.response.defer()
await interaction.delete_original_response()
discord.errors.InteractionResponded: This interaction has already been responded to before
the delete actually seems to work but then the send message later doesnt
how can i send a message to the interaction after i delete it?
eh
what function are you using
interaction.respond normally handles it
await interaction.response.defer()
await interaction.delete_original_response()
await interaction.response.send_message(embed=self.embed, view=self)
then yeah just change it to interaction.respond, it chooses the appropriate function
(which is interaction.followup.send, the main point is convenience)
Yeah no but you can't block a user from going to the discord shop thing and subscribing to a tier
Like one way around it's easy
The other way I don't see how one would do it
idk skill issue
I mean I don't really care cause the payment developer terms don't apply to me anyways
It would be weird to create a test entitlements for everyone that subscribes through your website
how to auto accept these kind of requests? when someone try to join
why would you want to auto accept them
their sole purpose is to be manually reviewed and accepted / rejected
I dont think join applications have been added to the API yet
Also it is unclear how they will change (or if they will exist) when guilds are discontinued
When I release premium features I want to give the first x servers that purchase it an additional month free. Is there any way to do this without telling the user to make sure their membership doesn’t renew? I was planning on giving them a test entitlement after the first month has passed
Wait guilds are already going away lmao
Yeah, I don't think you can do it without telling the user not to renew
Monetization is still very simple
The experiment is being killed in favour of the features being added as regular server features
and good riddance imo
yes they've been
those are member application forms that were used for clans
just, for normal guilds
Do you have a link for this? I am not finding any reference to them
i know because i've made a clans pr for dpy and i had to do objects for it
just to clarify when I said "added to the API" I meant the documented bot accessible API
what the fuck is that link
for the userdoccers, unofficial community discord docs
This endpoint and the 2 endpoints below it might be of interest.
https://docs.discord.sex/resources/guild#action-guild-join-request
Note that these are unofficial docs so that stuff is not guaranteed to work.
Also it will not be implemented into pycord until it is added to the official docs (which some things may not)
is this intended ?
💥┆Exception: can't subtract offset-naive and offset-aware datetimes
days_in_guild = (datetime.datetime.utcnow() - member.joined_at).days
days_account_age = (datetime.datetime.utcnow() - member.created_at).days
shouldnt they both be the same ?
do both cause that error
nah, the joined_at only
thats why im a bit surprise, why would they be different
probably because one is from user and one from member
and joined_at says its an aware datetime object
created_at doesnt
yes i know but why
i dont really see why one would ned to be aware and the other naive
This is what is seems like is happening. Discord is sending a timezone aware string for one of the fields but not the other. It is probably best to just get the UTC time of whatever is returned
oversight, created_at uses utils.snowflake_time while joined_at uses utils.parse_time
which is prefered? Snowflake time I assume?
well snowflake_time is for converting snowflakes, parse_time is for time strings
i.e. created_at just converts the user ID
parse_time uses fromisoformat which calculates the timezone from the included offset
-remindme 1d fix this datetime thing
Set a reminder in 1 day from now (<t:1740694004:f>)
View reminders with the reminders command
ironic that it sends a datetime to fix a datetime
Yeah
trying to fix for 1h a bug when there is no bug, you just forget that you fucking set a forbidden role and mandatry role features......
oh yeah that makes sense, I was not thinking
use discord.utils.utcnow()
Also, datetime.utcnow() is deprecated and removed in 3.13(?)
its just .now() now
it is deprecated
from datetime import datetime, UTC
datetime.now(tz=UTC)
still deprecated in 3.13?
Ah, deprecated since 3.12; I thought it was earlier. https://docs.python.org/3/library/datetime.html#datetime.datetime.utcnow
Both cause the error for me, and the issue is not on pycord's side afaik. It is datetime.utcnow() that is naive, not created_at or joined_at. You should use datetime.now(tz=UTC) as I exemplified above.
-reminders clear
Your reminders in this server:
113661592: #1132206148309749830: 'fix this datetime thing' - in 13 hours and 51 minutes from now (<t:1740694004:f>)
Remove a reminder with delreminder/rmreminder (id) where id is the first number for each reminder above.
To clear all reminders, use delreminder with the -a switch.
-delreminder -a
Cleared 1 reminders
Yep I already did that, but did u check nelo’s message ?
I though he said 2 différents méthodes where used
Yeah but it makes sense
Like
joined at is most likely returned as an iso time string from discord's api
while joined at is not returned, it is the time embedded into the user id
Ok I see
I am a bit confused, when I do this
async def reminder_cmd(self,
inter: discord.ApplicationContext,
name: str = discord.Option(input_type=str, required=True, description="The name of the reminder.", name="name"),
time: str = discord.Option(input_type=str, required=True, description="The time of the reminder, for better description use `/help time_formats`", name="time"),
description: str = discord.Option(input_type=str, required=False, description="The description of the reminder.", name="description"),
file: discord.Attachment = discord.Option(input_type=discord.Attachment, required=False, description="Any file", name="file"),
):
the file looks like this (screenshot 1)
when I do this
file: discord.Attachment = discord.Attachment,
attachment works correctly, but it is said that description is not provided, so I think it is possible to do. And Attachment is a valid argument for the input_type parameter in Option() so I am confused what I am doing wrong
I can just use decorators, but maybe I made a silly mistake somewhere here
do you know how python works lol
Your issue is that you need to typehint the options, not set them as defaults
you are doing var = discord.Option(...) but you need to do var: discord.Option(...)
regardless i'd recommend using the decorator variant of defining options, personally
its much cleaner in the code, and less prone to errors imo
also, the first argument should be ctx, not inter (kind of conventional in pycord)
@sour widget
why is there a = and not a : ?
thats exactly the issue i just explained lol
also, just a tip, required is True by default, and you dont need to pass the name if its the same as the argument name (this is only true for the typehint version tho)
-# I dont know if it works for all types but I am pretty sure that arg = Option(...) is valid
it shouldn't be for all I know
Is there any way to detect if the user's sent message is a forwarded msg or not? If yes, then how to fetch it's metadata?
Checked discord api docs, ig this is what I found?
https://discord.com/developers/docs/resources/message#message-reference-types
There is a flag and stuff, but pycord doesn't support any of that yet
https://github.com/Pycord-Development/pycord/pull/2598
Summary
Implements message forwarding, alongside some small cleanups for other message features.
Information
This PR fixes an issue.
This PR adds something new (e.g. new method or parameters).
...
discord is having any issue with connection?
no
Ye I saw that
but wasn't able to find that
find what
To check if the message is a forwarded msg or not
Discord API provides the endpoint
(read the docs)
"but pycord doesnt support any of that yet"
Currently in pycord if you fetch msg.content in a forwarded msg, just like pure embed msgs it returns "" / None
¯_(ツ)_/¯
that's what I meant
I am make a feature for my bot
i figured
So the feature is somewhat like this. I am making a quotes channel setting, when someone forwards the msg (if it's a forwarded msg) it will fetch the msg metadata and will make a ss out of it by using Pillow
yea thats great and all but pycord doesnt support it
Yep ik, that's just reply for ur q "but like what do you want lol"
that was me asking what you're asking of us lol
try print(message.flags.value << 14)
if that works for a forwarded message tell me
ok let's assume I got the status of the msg
how will I fetch the metadata?
the forwarded msgs' content, author data, time etc...
Only stress-free and possible way is to wait till pycord implements it. Or I gonna make pr
PR already exists. here.
and no, you wont be able to unless you make a raw api request i think
if message.flags.value & (1 << 14):
# Message was forwarded
else:
# Message wasn't forwarded
@wheat tiger ^^
I want metadata too so..
I just need to wait ¯_(ツ)_/¯
if you're comfortable with working with raw metadata, you can do py data = await bot.http.get_message(channel_id, message_id)
the forwarded message's data will be under the message_snapshots key
next release is not too far off, after which it'll be under message.snapshots
(and it will also include Message._raw_data if you ever need that in future; you could also add this yourself by updating message.py if you don't want to fetch every time)
why is it called snapshot?
because it's a snapshot of the message at the time it was forwarded
hello! is it acessible?
only the first one
how to use options with custom options for every server?
like "operator" for
server 1: add, remove
server 2: multiplicate, divide
What
You mean the option displays different choices for each server?
yes!
How do you determine such options for the server
To use options with custom choices for every server, the bot fetches options dynamically from an API (api.example.com/options?serverID=123) When a user runs the command, the bot makes an HTTP request to the API to retrieve the specific options for that server. These options are then displayed using dynamic autocomplete or a dropdown.
I should have thought about it first. I completely forgot, but after thinking it through (my bad), I remembered how it works. lol
nevermind
Wait we can do this too, raw http req 
Hmm I can use it 
You were always able to send http requests by yourself
Ye?
But using pycord, I didn't notice doing that
Yes...
Ig till next release I can do this way 
How would the library make the api requests
I though they using asyncio or requests when they need to fetch data 
That's what the library does...
.http is just the module that handles all the requests
Ye ik (that the only way to make request) but never figured out they made some util functions
I'm confused
See, what I thought it, when they need to make some request they must be using the request module or asyncio module in that specific function, but I never realised that they made a unified class containing methods using which we can do http requests
Hope you understood 
I was just lazy enough to dig in the package 
It still uses aiohttp to make the request
You're just seeing the abstraction of the request
.request is a method of the HTTPClient, if you dig through it, you will see it handles the request and uses aiohttp
discord%2Fhttp.py lines 288 to 291
try:
async with self.__session.request(
method, url, **kwargs
) as response:```
self.__session being an aiohttp.ClientSession
TQSM for you help 
allgood
Using message_snapshots I can even check if it's forwarded msg or not
when not forwarded it returns None
else it returns the metadata
pretty much yeah
is ctx.user or ctx.author the dominant ?
They're the same
I'd say user just becaue both are a shortcut for Interaction.user
but it's more a preference than anyhting
ctx.author is because it came from ctx.message.author, while interaction has user instead; hence both exist
✨ evolution✨
ok thanks you
backwards compatibility kinda
Is the only way to determine if an entitlement is a test one, is to try to delete it?
I think both purchased and test entitlements have the application_subscription EntitlementType
@bot.slash_command(description="blablabla")
@option("choice", description="blabla", autocomplete=True)
async def choose(ctx: discord.ApplicationContext, product: str):
await ctx.respond(f"you choose: {product}")
@choice.autocomplete("choice")
async def product_autocomplete(interaction: discord.Interaction, current: str):
base_url = "https://api.example.com/"
getshop_url = f"{base_url}?method=getlist"
shop_response = await fetch_url(getshop_url)
choices = []
if shop_response is None or type(shop_response) is not list:
return choices
for item in shop_response:
if current.lower() in item.lower():
choices.append(discord.app_commands.Choice(name=item, value=item))
return choices
Traceback (most recent call last):
File "test.py", line 2891, in <module>
@chooice.autocomplete("choose")
AttributeError: 'SlashCommand' object has no attribute 'autocomplete'
Hm
That's not how it uh works
hmmmm
Remove the decorator on the autocomplete func
Pass the function to the choice
autocomplete=product_autocomplete
lemme try
I've seen this syntax several times now
where do people get this from
and also, autocomplete takes AutoCompleteContext, not Interaction, and no other parameters
and the thing at the bottom with discord.app_commands Blabla, that's discord.py. This is pycord.
@nocturne jewel
your ide should've told you that that doesn't exist in Pycord
Probably AI combining codes of multiple libs since it doesn't know better
Copilot autocomplete :(
It gave me the idea
I also use discord.py and pycord in 2 different environments so it's a bit confusing
you really shouldn't do that
for your own sake
hello, i have a task that's supposed to go off at 4:20pm but it's 4min early
eastern = pytz.timezone('US/Eastern')
...
@tasks.loop(time=time(hour=16, minute=20, tzinfo=eastern))
...
system time is right. i don't know what it could be
what if you print time.now() in the task and check which time exactly the timestamp resolves to
2025-03-02 16:36:28,422 - cogs.four_twenty - INFO - 2025-03-02 16:36:28.422396
looks right to me
hm
are you sure your system time is correct? Does it show as 4:16 for others as well?
@tasks.loop(time=time(hour=16, minute=42, tzinfo=eastern))
check whether your system time is right on https://time.is/ just to rule that out completely
date
Sun Mar 2 16:41:53 EST 2025
vps is headless.
it is
so python's time module seems to have the correct time based on this
your system time is right
and you say your VPS time is right (which i suppose it has to be if you matched it to your PC time)
hm..
it worked when I did it in utc. switched to eastern to handle daylight savings better
@tasks.loop(time=time(hour=20, minute=20, tzinfo=timezone.utc))
I think the timezone implementation is wrong
https://stackoverflow.com/questions/1398674/display-the-time-in-a-different-time-zone/63628816#63628816
this seems to be a better solution
thanks. i'll try it later
yeah pytz is not recommended to be used for python 3.9+
wth LOL
would not be supprised if it had something to do with leap days/minutes/seconds/etc
if i want to create a group of commands, for example /game trivia and /game akinator, but have the code of each command in a different file, what would be the best way to do it?
There is no "best way", but you can use multicog
.tag multicog
Tag not found.
pycord in itself does not support what you want, you need that extension
Or you'd do it manually but yeah
don't think that's easy
Yeah no it's not easy
it would be if you disable syncing
i.e. if you subvert the library's command system, you can just setup interaction listeners
but you're actively fighting against the lib at that point
skipping leap years is crazy 💀
is there an event for on guild boost?
afaik this
on_guild_update
but i'm not 100% cretain one would have to test
or wait for smbd else to confirm
Hello,
does anyone have any idea how long the Discord server-side cache lasts?
When I embed an image into an embed via URL, the image is cached with the URL from Discord. When I upload another image to the same URL, the old image is still displayed instead of the new one. The new one is only displayed when the URL changes.
Has anyone had any experience with this or knows how long the cache lasts? Or is there any way to delete or reset the cache?
Idk how long it last but last time it was for a very very long time
A leap year is just a year with a leap day isn't it?
There's something with additional hours or minutes idk I forgot
Okay, thanks. There's no way around that or anything, is there?
not really I believe, maybe if you add www to the url it makes a new cache item or smth
just add a random query string to the end
imagecdn/image?wefhreuighkrejn
Since reloading slash commands doesn't change the behavior of the command function (vs text commands), how do you guys structure your Cogs? Do your slash command do nothing but respond, and you have some other function/layer that actually does whatever magic needed (including building the response e.g. embeds)?
It does
If you reload a cog and then sync command the change will be reflected
meh. is there an atomic sync, or do I have to sync everything?
My commands contain all code they need unless its very unrelated to the command, duplicated, or stuff like DB handling
When developing, I might have to refresh things several times since there's often no way to simulate things without actually doing them
You can sync the only command
As long as u sync it
why do you need to reload the cog tho, a restart is painless
Maybe for your bot. But not mine, which does a ton of stuff at startup
Only issue is if ur edit the bot class or u need to add a shard
It takes a lonnnng time
What do you mean by this? How can I sync the single command I changed? You're saying sync_commands (or whatever it is) does this for me, or do I need to pass it some variable
Hm. Looks like I had this commented out.
@commands.command(name='reload', hidden=True)
@commands.is_owner()
async def owner_cog_reload(self, ctx, *, cog: str):
"""Command which Reloads a Module.
Remember to use dot path. e.g: cogs.owner"""
try:
self.bot.reload_extension(cog)
# await asyncio.sleep(1)
# await self.bot.sync_commands(force=True)
except Exception as e:
await ctx.send(f'**`ERROR:`** {type(e).__name__} - {e}')
else:
await ctx.message.add_reaction('👍')
Maybe it was broken in a previous version of pycord
Yeah you can just sync it like since
But I feel like an update command which would reload all cog + sync command would be more efficient
Because you rarely edit only 1 command
i think you rarely edit more than one command at once lol
Idk I have a test bot where k do all the change and then I merge it to the prod bot
So always some big update
When I'm iterating on a single task, yes I do.
For context, I was talking about reloading the cogs for the test bot. I don't mind restarting a prod bot for larger changesets.
then do as you previsouly did
hi everyone, can we send a dm to someone with await bot.fetch_user() ?
Sure? As long as they share a server with the bot or have it installed to their profile
and they have DMs for that server turned on
Are you sure cog reloading does not update the code? I thought it did, it just does not reflect any changes to the app command on discords side unless you sync
Only if you explicitly sync commands, as Luma said. Otherwise, if I make any modifications, they are indeed not reflected.
afaik syncing commands has no effect on the actual callback of the command
But i trust you, it is probably a bug
The suck part for my current task is that when I reload my cog, this Web Client that I have loses its authentication for some reason. It calls out for the handshake and I never get a cookie the second time around. (Completely not Pycord related, just venting)
Does anyone know why when I call a bot.get_all_members then sort through member nick names the nicknames are missing on several people who indeed have nicknames on the server?
Never seen anyone use that function before 😅
Assuming it follows convention get_x returns cached things. So if the members nick changed after it was cached and the bot never received this update then it will be the old value
When we use stop_recording() where does it save it?
in the arg that you pass inside the start recording
can embeds have image and thumbnail at the same time?
yes
i attached two files with different names, and passed the arg files=[file1, file2] but it seems like file1 overwrites file2
can you show that snippet of your code please
async def finished_callback(sink, *args):
text_channel = bot.get_channel(123)
if text_channel is None:
try:
text_channel = await bot.fetch_channel(123)
except Exception as e:
print(f"Error: {e}")
return
recorded_users = [f"<@{user_id}>" for user_id in sink.audio_data.keys()]
await sink.vc.disconnect()
files = [
discord.File(audio.file, f"{user_id}.{sink.encoding}")
for user_id, audio in sink.audio_data.items()
]
await text_channel.send(files=files)
@bot.event
async def on_voice_state_update(member, before, after):
if member.bot:
return
if after.channel is not None and after.channel.category is not None:
if after.channel.category.id == 123456:
if member.guild.id not in connections:
vc = await after.channel.connect()
connections[member.guild.id] = vc
sink_instance = discord.sinks.MP3Sink()
vc.start_recording(sink_instance, finished_callback)
print(f"Started recording in '{after.channel.name}'")
else:
vc = connections.get(member.guild.id)
if vc.channel.id != after.channel.id:
await vc.move_to(after.channel)
#pass
if before.channel is not None and before.channel.category is not None:
if before.channel.category.id == 123456:
vc = connections.get(member.guild.id)
if vc is not None and vc.channel.id == before.channel.id:
await asyncio.sleep(1)
non_bot_members = [m for m in vc.channel.members if not m.bot]
if len(non_bot_members) == 0:
vc.stop_recording()
del connections[member.guild.id]
print(f"Stopped recording in '{before.channel.name}'.")
Exception in thread Thread-43 (recv_audio): Traceback (most recent call last): File "/usr/lib/python3.10/threading.py", line 1016, in _bootstrap_inner self.run() File "/usr/lib/python3.10/threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "/usr/local/lib/python3.10/dist-packages/discord/voice_client.py", line 863, in recv_audio self.unpack_audio(data) File "/usr/local/lib/python3.10/dist-packages/discord/voice_client.py", line 740, in unpack_audio data = RawData(data, self) File "/usr/local/lib/python3.10/dist-packages/discord/sinks/core.py", line 115, in __init__ self.decrypted_data = getattr(self.client, f"_decrypt_{self.client.mode}")( File "/usr/local/lib/python3.10/dist-packages/discord/voice_client.py", line 611, in _decrypt_xsalsa20_poly1305_lite return self.strip_header_ext(box.decrypt(bytes(data), bytes(nonce))) File "/usr/local/lib/python3.10/dist-packages/discord/voice_client.py", line 615, in strip_header_ext if data[0] == 0xBE and data[1] == 0xDE and len(data) > 4: IndexError: index out of range
is that normal?
i was trying to record a voice channel when for 10-20 seconds records it works, for longer like 2 minutes not
Anyone know a way to jig it so that sending a voice channel invite to a user not already in the guild allows you to update overwrites for this user before they open the invite?
no, best you could do is have a member_join listener (or use bot.wait_for) to update it after they join
This is really strange because it means discord is sending an empty packet (other than the nonce)
I guess the fix could be to just have the length check as the first of the 3 conditions but that would have to be something that is fixed on pycords side
Thanks for the suggestion! I will try tomorrow
uhh isn't it because we didn't merge the encryption changes
Oh, there's any dev build I can try?
It should not get that far if that were the case. The mode selection would error out
The new system should work as an alternative but not actually fix this problem from what I can tell
I put 500k here but still the bot doesn’t log even 15 minute old messages which is deleted
😅
are you using on_message_delete ?
it doesn't log past messages, only new messages from when the bot is started
Yes
Yeah I'm referring to the time the bot started
Uptime being 3 days+ but still failing to log 15 min old messages being deleted by a moderator manually (not purged)
and on_message works?
does MessageType.application_command always have webhook id?
when using member.add_roles() , how do I use the snowflake feature to put multiple roles as parameters ?
def gives_necessary_roles(guild: Guild, member: Member):
role1 : RoleTags|None = discord.utils.get(guild.roles, name="role1")
role2 : RoleTags|None = discord.utils.get(guild.roles, name="role2")
member.add_roles(???) #how to add both roles at once ?
await member.add_roles(role1, role2)
but getting roles by name is bad practice
if you already know the specific roles you want, just hardcode the IDs into the add_roles command
thank you
also about the role name I understand role ids are better, I'll switch to that soon
and then you should use guild.get_role
thank you for those better practice
Yes
On message works perfectly, I have intents.all enabled
and what if you send a message then delete it
I used pip install py-cord[voice] but cant seem to access anything from discord.sinks. Even in the example
from discord.sinks import MP3Sink```
I get
Exception has occurred: ModuleNotFoundError
No module named 'discord.sinks'
File "/home/mojobojo/dev/discoword/voice-recorder-test/vr.py", line 4, in <module>
from discord.sinks import MP3Sink
ModuleNotFoundError: No module named 'discord.sinks'```
Anyone have an idea why that could be?
can you make sure you have no other discord bot libraries installed. If you do uninstall them and reinstall pycord
@bot.group()
async def afk():
pass
@afk.command()
async def set():
...
@afk.command()
async def remove():
...```
How to do this with ```python
@bot.slash_command```?
My instinct is telling me no, but you might want to ask in #api-chat on the discord developers server
Unfortunately slash commands do not allow this behavior.
An alternative could be to use /afk info or /afk show instead
Another alternative is to have set/remove as choices in an option instead of seperate commands if that works for your usecase
thank you
Hello
is there a way to make the listener, on_application_command execute and finish before the application command start ?
I made a listener so I can see who invoked a command and what command they used
@discord.Cog.listener()
async def on_application_command(self, ctx: commands.Context):
log.debug(f"Received command: {ctx.command} was invoked by {ctx.author}")
and any command like :
@commands.slash_command(name="ping", description="Check if the bot is alive.")
async def ping(self, ctx: discord.ApplicationContext):
log.info(f"LOGGING A MESSAGE")
await ctx.respond(f"Pong! thanks for checking on me {ctx.author.mention} !")
when a user call the /ping command I get:
DATE TIME | INFO | LOGGING A MESSAGE
DATE TIME | DEBUG | Received command: pong was invoked by user
but it feels like its behaving as if I was using on_application_command_completion since this message always appears after a command completion.
if you want it to absolutely run before every time, you could make a global check
there might also be a before_application_command method
https://docs.pycord.dev/en/master/api/clients.html#discord.Bot.before_invoke
I believe this will do it globally
got it, tyvm
i mean, it definitely runs before ```py
self._bot.dispatch("application_command", ctx)
try:
...
await ctx.command.invoke(ctx)
...
except DiscordException as exc:
await ctx.command.dispatch_error(ctx, exc)
else:
self._bot.dispatch("application_command_completion", ctx)
(ironically, before_invoke is after on_application_command)
it might feel like the other way round because before_invoke and similar functions have to finish before the command runs, but the event doesn't
dispatch is async
runs out of order
yeah i mean that was my point, the event is dispatched before invoke but it's possible to finish after unlike the other methods that actually block
It logs
Simple messages with just message content
It’s only not working when the message is like 15 mins old
It works sometimes but it’s unreliable
can confirm, no other discord libraries are installed. unless the remnants of one still exist in my virtual enviornment. I can try making a new one.
yep, so was just a messed up virtual environment. dunno why I didnt think of that. thanks for putting my brain in the right space.
halas it doesn't seem to
how would you do this please ?
I can't figure out how to do it globally
This should still work even with the new changes?
https://github.com/fs86/discord-ext-ipc
Bots: Attributes activity, allowed_mentions, application_flags, application_id, auto_sync_commands, cached_messages, cogs, debug_guilds, default_command_contexts, default_command_integration_types,...
Make sure to always return True, else the command wont run.
will try that rn !
works like a charm thank you so much !
if anyone ever needs the same feature here is my code
class Events(commands.Cog):
def __init__(self, bot: discord:Bot):
self.bot = bot
self.bot.add_check(self.__log_command_call)
async def __log_command_call(self, ctx: ApplicationContext):
log.debug(f"Command {ctx.command} called by {ctx.author} in {ctx.guild}.")
return True
.
Saw that you got an answer!
what new changes?
This seems really weird
does it ?
Why are you not using an event like on_command, on_command_completion etc
does it work even if I'm using application commands ?
aren't commands and slash commands different ?
If you use on_application_command it will work
as I've said here it doesn't
on applicaiton command shows after my command has been executed
so what about on_command
Does this not do it globally or does it not do it "in time"?
It’s not likely to be after
It’s fire at the same time I think
yes
Because completion is the one after
at the same time
Or is it after and completion is only if there is no error
but I would rather have my log be always printed before the command is executed which makes the stack more readable
does it even matter lol
well to me it does ^^
as I've stated it's more of a time issue
I understand the point for the logging
.
So why are you not using bot.before invoke
Will be the same, still not fire before
sorry, I was talking about the bot.before_invoke. I am just curious what went wrong when you tried that
is on command sure to be called before the execution of the command ? I may have mis understood the difference between a command and an application command ? I thought application command = slash command and command is the hold <PREFIX> command
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...
read and try
i cant tell you more than that
It will not wait for the listener to be done before invoking the command
^
So if the thing takes more time it will likely break
for the bot before_invoke, I feel like I miss coded it, does it also requires to have a return True at the end ? cause that might have been my mistake
its one line of non async code..
I don’t think so it’s just a Coro that is run before
I'll try all the solutions and let you know
According to his exemple it was not working
And dispatch is async
So it might run out of order and so after the command has been invoked
class Events(commands.Cog):
def __init__(self, bot: discord.Bot):
self.bot = bot
self.bot.add_check(self.__log_every_command)
async def __log_every_command(self, ctx: ApplicationContext):
log.trace(f"Command {ctx.command} called by {ctx.author}. ADD_CHECK_METHOD")
return True
@discord.Cog.listener()
async def on_command(self, ctx: ApplicationContext):
log.trace(f"Command {ctx.command} called by {ctx.author}. ON_COMMAND")
@discord.Cog.listener()
async def on_application_command(self, ctx: ApplicationContext):
log.trace(f"Command {ctx.command} completed by {ctx.author}. ON_APPLICATION_COMMAND")
# gives me : Extension 'cogs.events' raised an error: AttributeError: module 'discord.bot' has no attribute 'before_invoke'
# @discord.bot.before_invoke
# async def before_invoke(self, ctx: ApplicationContext):
# log.trace(f"Command {ctx.command} called by {ctx.author}. BEFORE_INVOKE")
...
class Fun(commands.Cog):
def __init__(self, bot: discord.Bot):
self.bot = bot
@commands.slash_command(name="ping", description="Check if the bot is alive.")
async def ping(self, ctx: ApplicationContext):
log.info("Pong!")
await ctx.respond(f"Pong! thanks for checking on me {ctx.author.mention} !")
09/03/2025 15:52:44:44 | TRACE | Command ping called by lolozen (ZEN). ADD_CHECK_METHOD
09/03/2025 15:52:44:44 | INFO | Pong!
09/03/2025 15:52:44:44 | TRACE | Command ping completed by lolozen (ZEN). ON_APPLICATION_COMMAND
so before invoke doesn't work, but I assume I'm not using it right
my slash command isn't considered as a command of on_command()
and on_applicaiton_command shows up after my log aeverytime (might be because it's ran in parallel)
hm
Bots: Attributes activity, allowed_mentions, application_flags, application_id, auto_sync_commands, cached_messages, cogs, debug_guilds, default_command_contexts, default_command_integration_types,...
it's in my exemple right above I commented it, it gives me an error but it might be because I'm not using it correctly
yea lol
you need to use your botvar, not the discord.bot module lol
discord.bot just refers to the bot.py file inside pycord
hooo I need to use it like I did with the add_check ?
yes, i think so
trying it rn, but just out of curiosity, why is it better than add check ?
just
@bot.before_invoke()
async def logging(...):
must be in your main bot file i believe
because logging isnt a check, you're kinda just abusing the checks feature for logging
before invoke is for all kinds of tasks that have to run before a command is invoked
well this works perfectly
thank you
I didn't put it in my main since I like to keep it in my event cog but it works perfectly still
yea i wasnt sure if you can use self.bot in the decorators in a cog
show how you did it
class Events(commands.Cog):
def __init__(self, bot: discord.Bot):
self.bot = bot
self.bot.before_invoke(self.__log_every_command)
async def __log_every_command(self, ctx: ApplicationContext):
log.trace(f"Command {ctx.command} called by {ctx.author}. BEFORE_INVOKE")
when my cog is initiated it sets the before invoke to the bot
also you shouldn't put a double underscore infront of it, single underscore is convention for private stuff
isn't one underscore for protected ?
repalcing all my double underscore ^^
we aren't in java lol
dunder methods are things like obj.__string__
okay thank you 🙂
and those are afaik the only methods that should use double underscores
alringt !
did a gloabl replacement ^^
well thank you all for your reactivity and for your help !
np
__ only in front is used in some non-dunder places, idk that much tho
I think all a decorator is is a function that takes a function as the first argument
I'll dig in and make research, but will stick to simple underscore for private from now on
yea true name mangling
but thats kind of a weird thing
Ah yeah, forgot about that it feels so gross I dont know why you would ever use it
Shouldn’t it be only async def before_invoke() ?
Without anything else ?
Mb didn’t saw that, if it’s working it’s good
Perfect
also just a note, unless im wrong, this will still log every command globally
not sure if you want that or not but thats what'll happen
ho yes you're right
for now it's okay caus emy bot will onyl be on one server
but I will have to think about a guild filter
2.7. It hasn't been updated dor 3 years.
is it possible to make a bot which can be added to a user profile using pycord?
yes
Here's the slash users example.
is it any different from developing a normal guild-installed bot?
you get a lot less info in slash commands, like basically no guild attribute access etc
oh so i added this bot I made to my profile but I can't use any of its slash commands in dms?
did you look at this?
yeah I think I just overlooked the fact you need to set the integration types
Coding wise it is not that much different, but like toothy said you just get a lot less information sent by discord
bump :p
Hi! is it possible for a bot to upload emojis to a guild? If so, how do you do it in py-cord because I only see create_sticker while the argument is called emoji so it's a bit confusing
That argument refers to the emoji linked to the sticker
use this
tysm
np
is Attachment.to_file().fp a byte-like object?
what does your IDE say?
I use vscode so nothing 0-0
discord.Asset
discord.Asset.is_animated
discord.Asset.key
discord.Asset.read
discord.Asset.replace
discord.Asset.save
discord.Asset.url
discord.Asset.with_format
discord.Asset.with_size
discord.Asset.with_static_format
discord.asset.Asset
discord.Activity.assets
discord.RawMessageDeleteEvent
discord.RawMessageDeleteEvent.cached_message
discord.RawMessageDeleteEvent.channel_id
discord.Attachment
discord.Attachment.content_type
discord.Attachment.description
discord.Attachment.duration_secs
discord.Attachment.ephemeral
discord.Attachment.expires_at
discord.Attachment.filename
discord.Attachment.flags
discord.Attachment.height
discord.Attachment.hm
discord.Attachment.id
discord.Attachment.is_spoiler
discord.Attachment.issued_at
discord.Attachment.proxy_url
discord.Attachment.read
btw it's await
so
(await attachment.to_file).fp
vscode can do that too.
wait, thats valid syntax?
That's the only way to do such things in one line
because if not for the brackets you would await the .attr
Python moment
no, completely logical
One thing I wish python had was bot?.user?.id which I think just returns None if bot or user are None instead of throwing a NoneType error
Is the ? even an operator in python?
As in, would adding this overlap with any current functionality?
bot.user.id if bot and bot.user and bot.user.id else none ;)
make so much sens ;)
that was proposed in PEP 505 , but it's a pretty controversial topic amongst the maintainers and ended up being deferred
yeah I just found that now
so redundant though
yeah i was joking
oh
Or just bot and bot.user and bot.user.id lol
Hi py-cord friends. Is there a way to access a guild member's signals as it's displayed in the discord members window? I want to notify myself when a member's suspicious behavior or excessive DMs signals go up.
I thought it might be some undocumented bit in the public_flags field but that doesn't seem to always be the case
There are undocumented fields on the Member object that discord doesn't want bots to use iirc yes
Undocumented fields that make it to py-cord's Member representation?
No, libraries usually don't add undocumented fields as they can be unstable
I'm not sure, I don't think on 2.6.1 but maybe there was a pr that did it on master
Hello, I have an issue with my bot that is in 1 guild with 350k members. I want to receive on member join event only. I enabled intents.members however this makes my bot's RAM usage jump from ~50MB to almost 500MB. Disabling cache with bot = discord.Bot(intents = intents, member_cache_flags = discord.MemberCacheFlags.none()) didn't decrease the ram usage. Any help?
Just enabling it ? Or there is a function which use this intents ?
Or else it can just be normal, if you have to receive intents from 300k members that’s a lot
member intents can use a lot of RAM
could you try setting chunk_guilds_at_startup=False in your Bot
yes
but only the spammer flag
you can still access it.
is the spammer flag the "excessive DMs" signal?
yes
Ah til
Not pycord-specific, but I've always been curious about this. What's the "correct" way to define a property on your class without the ide whining that you typed it but it's initially None?
It's not really optional, I just have to pre-define before it actually gets used it so I don't get errors when I do.
I just dont until it is set and leave a typehint at the class level
class A:
hi: int
def set(self, h: int):
self.hi = h
a1 = A()
a1.hi # This returns an attribute error
a1.set(4)
a1.hi
Yeah it's stupid that you can typehint it with no value but IDE thinks it's not defined.
i haven't opened pycharm like a year, all my pycord work is done on github.dev (vsc) with basic autocomplete and my bot work is in my server's web panel (lol)
Just hi: int = None # type: ignore 
it technically isn't defined. Without a value it's just an annotation that's added to the dict (cls.__annotations__)
class Foo:
_hi: int | None = None
@property
def hi(self) -> int:
if self._hi is None:
raise AttributeError("bleh")
return self._hi
def set(self, v: int) -> None:
self._hi = v
smth like that
That's how not-lazy people do it yeah
hi could have a setter instead of the separate method but eh
yeah I did that at first
but then saw Wolfy's example with set
so I wanted it to be similar
Ah
I have like a dozen props that need to be added this way; I’m not defining getters for them all, that’s silly
It’s stupid that you must define properties in init, and yet throw a warning if you assign to None initially because it’ll be updated later
Do you perhaps want a dataclass
How exactly is that stupid?
What if the value is never assigned? The type checker would be lying atp
And a: int = None being invalid makes sense too
None is NOT an integer
Because it makes sense that not every property will be assigned at init. For instance a response from an api that the runtime of the class relies on
It doesn't need to be assigned at the init
It can be in a method too that's called by you
The type checker will know that
But it does because if you set it outside of init, that’s technically wrong because it doesn’t exist. At least according to PyCharm
Plus I need to know it if it’s referenced in other classes. I imagine dynamic setting wouldn’t autocomplete
Well yeah defining it outside without a value means it doesn't exist at runtime
Sounds like you want a dataclass
dataclasses
dataclasses.Field
dataclasses.FrozenInstanceError
dataclasses.KW_ONLY
dataclasses.MISSING
dataclasses.__post_init__
dataclasses.asdict
dataclasses.astuple
dataclasses.dataclass
dataclasses.field
dataclasses.fields
dataclasses.is_dataclass
dataclasses.make_dataclass
dataclasses.replace
label:dataclasses
You can assign the attrs all in the class and it will assign them when you construct the class
But I don’t? In my cogs, I want to be able to reference self.bot.object_from_api. There are several of them, and they’re collected at different times (or at least need to be accessible before others are set)
Oh god
class E:
hi: int
Is pycharm that stupid
Idk I use basedpyright so I don't really know
Does that take over the built in checker?
yes
Well that’s a class var rather than an instance var. is that what I need to change?
what happens if you do that ?
Oh pog
I think that works (not at my computer). It’s when I define self.hi in init that it complains
what does it say ?
from typing import reveal_type
class Foo:
bar: int # Instance variable "bar" is not initialized in the class body or __init__ method (reportUninitializedInstanceVariable)
foo = Foo()
reveal_type(foo.bar) # Type of "foo.bar" is "int"
this is w/ basedpyright link
If I self.hi: int = None it complains on type. If I self.hi: int, then it acts like it’s not an available instance var when you try to reference it
well that's really pycharm doing weird stuff imo
cause it shouldn't
When I’m back at my computer I’ll write out a test class with all the different ways
self.hi: int isn't valid and complaining about assigning int to None makes sense tho?
Oh not available
How is it not valid? wtf
I think if you don't assign a value to a classvar pycharm will ignore it that's the thing here
thing.thing: T isn't valid, at least with pyright
yeah no that no
x: T = thing.thing is
nah py @hi.setter def hi(self, v)to do property assignment
(func name doesn't matter)
(i did not read the rest but idk why you would bother doing .set instead of overloading)
I wouldn't, I changed it before sending to match Wolfy's example
But that's what my original example did
Whatever
Weird. If I set a simple class
class TestClass:
def __init__(self):
self.b: int
def test(self):
self.b = 2
There doesn't seem to be any issue with defining it this way; Pycharm does not complain.
But it treats my actual code differently...
class MyBot(commands.Bot):
def __init__(self):
self.http_session: aiohttp.ClientSession
....
async def set_http_clients():
self.http_session = aiohttp.ClientSession(...)
Setting it whines Instance attribute http_session defined outside __init__ . It doesn't if I make it a class attribute, but I admit I don't really understand where you'd use one or the other.
I think class attributes apply globally to the entire class and all of it's objects
Which for the bot would only be once, so I assume that shouldn't matter in this specific case.
But I still don't get why instance properties are being treated differently here. In my TestClass I can reference it fine outside of init, but not in the bot
because the bot class uses slots, i think
I need some help, when I do a guild.members, some user on my server are not listed, does anyone have any idea where this might come from ?
cache stuff doing weird things
but no idea
is there a way for me to go around that ?
Fetch the users
I should use guild.chunk() then ?
Sorry if I'm not getting this correctly I want to fetch all the user from the guild
I don't get their id in the first place
generally everyone should be in cache already
how long after startup is this
just restarted it
give it like a minute or two
no i mean try that, im not sure if thats the issue
I'll try to sync it ig
very strange
how many members are we talking
this:
@commands.Cog.listener()
async def on_ready(self):
"""
Event that is called when the bot is ready.
Returns:
"""
self.bot.main_guild = self.bot.guilds[0]
members = await self.bot.main_guild.fetch_members(limit=None).flatten()
user1 = self.bot.main_guild.get_member(48<...>00)
user2 = self.bot.main_guild.get_member(33<...>25)
user3 = self.bot.main_guild.get_member(82<...>72)
user4 = self.bot.main_guild.get_member(69<...>58)
loguru.logger.debug(f"{user1} | {user2} | {user3} | {user4}")
gives me:
11/03/2025 21:33:21:56 | DEBUG | None | None | None | None
4
i mean in the entire guild
on a server of less than 50
hm
I can't find something in common between all of them
my bot is also administrator
and I gave it : discord.Intents.all()
(yes not best practice its for the tests)
fetch_members doesn't fill cache so it's pointless there, but if you have all intents it should cache all members at startup anyway
(unless you disabled it in your Bot class)
doesn't feel like I did
that's what is making me really lost
if you really want, await guild.chunk() should fill your cache
but if even that isn't working discord might just be really weird about it...?
do the missing members appear in your fetch_members list
are yo u sure that's the right guild ?
yup it's only in one
might check twice still
yeah I mean I trust you but who knows atp
...
oh
sorry to ahve bothered you all
LOL
[redacted but there was two servers]
BUT
WAIT
ITS NOT APPEARING IN THE FIRST SERVER WTF
burn him at the stake
maybe doesn't have the perms to show up ?
in the online tab ?
uhhh don't think a bot would need them
I'm pretty sure if @ everyone disbles view channels and the bot doesn't have that in its default role it doens't show up
/kick <bot_id> should work
code-wise, you can kick any member with guild.kick(discord.Object(user_id))
(or fetch the user if you really want)
nah all good LOL
nw and feel free to ask if there's anything
i know im awesome, ty
Does anyone know how to start a task that's in a cog when the bot starts up?
erm actually there's no await
true
didn't seem to work but i'll check again
Also add a await self.bot.wait_until_ready() to the first line at the task function
damn zervy typed faster
Im at my phone ;3
that's probably it
i was held back by pycharm loading
Curious if starting in a once=True on_ready is also good
theoretically yeah
well
you generallyyyy don't need to add once to on_ready, but i guess you can
yup that was it
thx
I do it casue I saw some people doing it but yeah make sense
fairfair
ah I see, sorry. if anybody has any tips for advertising a bot feel free to dm me
its a 2 seconds google search
which is why you chose the several-minute path that this is
I have the following problem, somehow I get all members who are on the server at member_ids and not only from the specific channel and no these are not admins or so
async def user_callback(self, select, interaction):
users_ids = [user.id for user in select.values]
print(users_ids)
users = []
users_errors = []
channel = interaction.channel
print(channel)
member_ids = [member.id for member in channel.members]
print(member_ids)
print(len(member_ids))```
and the channel prints the right channel
thats normal
why?
because thats how user selectors work
Ah nonono
oh yes
you cant limit user selects to only show specific people
it always shows everyone afaik
and if you mean this, that should work if the docs are right
So i want to make a suer select and there are all users inside that works and is correct but i want now wnen i can make the dropdown in a private only a lsite of all suer who are in the channel
class UserSysAddUser(discord.ui.View):
@discord.ui.user_select(placeholder="Wähle einen user aus", min_values=1,max_values=3)
async def user_callback(self, select, interaction):
# Get the user IDs from the select
users_ids = [user.id for user in select.values]
print(users_ids)
users = []
users_errors = []
# Get the channel where the dropdown was used
channel = interaction.channel
print(channel)
# Get all users who are in the channel where the dropdown was used
member_ids = [member.id for member in channel.members]
print(member_ids)
print(len(member_ids))```
i added coms.
I'm sure user selects only show relevant users who can see the channel.
no XD
No, they show all
I have a dropdown with all users, this is right
all user selectors work like that, in slash commands as well
BUT
I dont think there's an easy way to achieve what you want
Well then create the dropdown yourself
but then you are limited to 25? options
You don't understand that
You won't believe it: multiple selects. Boom.
It's ugly?
Everything is ok with the userselector
but after i have selected one or more users i would like to get all users who are in the channel in a list
well again the docs do say channel.members returns only members who can see the channel
so
if the docs lie no clue
but i don't get the users from the channel but everyone who is on the whole server
I get a site with 28 users but in the channel only 10 people are authorised to see and read it
make sure they dont have read messages in that channel
deny them that specifically
that should fix it
It's really a dumb way of checking it not gonna lie
but i become all members with this
member_ids = [member.id for member in channel.members]
what did i just say?
look no body can see this
that isn't the permission that matters as i just showed
.
.
i have desable all perms but i become all suers 😦
In the channel overrides, does @ everyone have X for read messages?
Okay yea looking at the library code again I saw that my assumption was wrong, but now I have even less of a clue why your stuff doesnt work
and this is my code to create this channelpy permissions = { interaction.user: discord.PermissionOverwrite(send_messages=True, read_messages=True, view_channel=True), interaction.guild.default_role: discord.PermissionOverwrite(view_channel=False, read_messages=False) }
can you do print("Test " + len(channel.members))
and show the output
just to make sure its what i expect
print("Test " + len(channel.members)) ~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~ TypeError: can only concatenate str (not "int") to str
bruh then do an f string
ah XD
god python is so dumb sometimes
print("test", len(channel.members))?
I choose to disagree with that syntax
Python doesn't
Looking at it but might be too tired to do a full repro, rn can't repro
i become 28 😦
and how many members do you see in the members list
9
also its "get", just to clear out confusion
become means something different
Then can you try this
for member in channel.members:
print(channel.permissions_for(member).read_messages)
It's weird, it works for me
2 v 1 then lol
and i have to agree i dont see anywhere this could go wrong, the internal code seems solid
Can you show a full screen recording of the entire process as well
I think we're missing something
@lethal loom just to be clear, you create a channel with that code, and its .members returns members that aren't in the membvers list ?
yes
Oh
.
yeah wait
wat
oh neat
But I'm not sur if it applies here
I don't use master and it works for me
yeah but who knows atp
this seems an issue with your backend code tho? lol
like where do you print that "already in the ticket"
the logic deciding that is busted
this is my complet funcvtion
class UserSysAddUser(discord.ui.View):
@discord.ui.user_select(placeholder="Wähle einen user aus", min_values=1,max_values=3)
async def user_callback(self, select, interaction):
# Get the user IDs from the select
users_ids = [user.id for user in select.values]
print(users_ids)
users = []
users_errors = []
# Get the channel where the dropdown was used
channel = interaction.channel
print(len(channel.members))
print(channel)
for member in channel.members:
print(channel.permissions_for(member).read_messages)
# Get all users who are in the channel where the dropdown was used
member_ids = [member.id for member in channel.members]
print(member_ids)
print(len(member_ids))
for u in users_ids:
user = interaction.guild.get_member(int(u))
if user is None:
users_errors.append(f"\n - <@{u}> `Invaid User`")
continue
elif user.id == interaction.user.id:
users_errors.append(f"\n - <@{u}> `Du kannst dich nicht selber zu dem Ticket hinzufügen`")
continue
elif user.id in member_ids:
users_errors.append(f"\n - <@{u}> `der Nutzer ist schon im Ticket vorhanden`")
continue
overwrite = discord.PermissionOverwrite()
overwrite.read_messages = True
await channel.set_permissions(user, overwrite=overwrite)
users.append(f"<@{u}>")
user_string = ", ".join(users)
users_errors_string = ", ".join(users_errors)
await interaction.response.defer()
embed = discord.Embed(description=f"{interaction.user.mention} hat {user_string} zum Ticket hinzugefügt",color=TICKET_COLOR_GREEN)
embed_error = discord.Embed(description=f"Folgende User konnten nicht hinzugefügt werden: {users_errors_string}", color=TICKET_COLOR_RED)
if len(user_string) == 0:
await channel.send(embed=embed_error)
elif len(users_errors_string) == 0:
await channel.send(embed=embed)
else:
await channel.send(embeds=[embed, embed_error])```
i have to admit i have no clue why you're extracting the IDs from the full objects, then later you need to jump through hoops because of that
Long ass callback
yea a lot going on lol
yeah but why channel.members give me 28 😭
idk if it's that or smth
i was just intently looking at the "interaction.channel" line
lmao
yea please try on master branch
@lethal loom try with master
.tag master
pip install -U git+https://github.com/Pycord-Development/pycord
-# Note: The Master Branch May Have The Newest Features But It May Also Have More Bugs
its that 100%
cause
member_ids = [member.id for member in channel.members]
channel.members uses permission_for
which was broken
Yeah
the code itself looks fine, but i heavily recommend splitting it up into several functions
and importantly, from the full user and member objects you get, you just extract the ID. Then later you construct a mention manually beacuse, well, you only have the ID. What's the point of reducing the objects to their ID?
Summary permissions_for returning wrong permissions Reproduction Steps When you use channel.permissions_for, and you remove the "View Channel" permission, it still returns true. NOTE: Cod...
with master its work 😦
alright there we go
yeah thx for all helpers 🙂
because we wasted a long time on an issue outside of our control, which should have gone into a stable version ages ago
that fucking PR was merged 2 years ago
what
wait
my pr ?
well nevermind that, we need 2.7 now seriously
the issue btw
InteractionPayload["channel"] is partial, thus, when creating a GuildChannel object from it, some attributes were missing/incorrectly set. With this pr, InteractionPayload["channel"] is used only in the following cases:
- When the interaction happens in private channels.
- When the channel is missing from the bot's cache.
In all other cases, it uses the full channel object from the cache.
ill pretend i understand
Basically with every interaction discord sends a channel object so we tought it was a good idea to use it instead of the cached one but that one was missing permissions
whatever
gn chat
For slash command interactions, how would i get the supplied values of the command arguments?
It works exactly the same way. You just use the function arguments you set.
You should have it setup like arguments to the callback function
@bot.slash_command()
async def warn(ctx, user, reason):
...
/warn user:@Ice Wolfy reason:bad :3
OK wolfy beat me with the example
Oh i guess i wasnt clear, apologies, i meant if i have the interaction object of a command that was executed
just like how i would get the command's name with interaction.command.name
dont forget the ctx
You can access the raw data of in interaction in the Interaction.data property.
To make it more friendly I think you could turn the interaction into ApplicationContext
context = discord.ApplicationContext(bot, my_interaction)
This should work, but I have never done it myself
Actually, this might not work
AttributeError: 'ApplicationContext' object has no attribute 'data'
oh, you already have an application context object, not interaction
Slash commands receive an ApplicationContext, not a "plain" interaction object like discord.py
Then you can just access with ctx.command ctx.selected_options
So if you have ctx, it'd just be ctx.command which is the SlashCommand object (and the ctx.selected_options as Wolfy mentions)
command.options only returned the args it has, not values that were supplied
^ selected options includes the user provided values
Yep! thank you for your help
hullo... i tried searching first, but i couldn't find an answer for my question...
i am running a bot that maintains a set of threads for different work issues; we use Jira which posts an event to our bot on every issue update, then the bot checks to see if that issue should have a Discord thread and if so creates/updates it. we are hitting this rate limit after three or four updates in a minute or so:
[2025-03-13 20:27:13] [WARNING ] discord.http: We are being rate limited. PATCH https://discord.com/api/v10/channels/1349184233557590076 responded with 429. Retrying in 518.31 seconds.
i am trying to figure out which rate limit we are hitting (global? that endpoint? some grouping of endpoints?) and what the limit is. i know from the docs some of that is available in the http response headers, but i don't know how to get at those using discord.py. does anyone have any advice? ty in advance!
Are you ever renaming the channel
oh no do threads have the same limits now nvm that's a channel url
Also note that this is the support server for py-cord not discord.py
right sorry, i meant py-cord. 🙂
yes that happens fairly often.
renaming channel has an extremely low rate limit
i bet that's it, ty!
channel edit name/topic has a ratelimit of 2 changes per 10 mins, discord does not want you to use channels as some sort of counters of stuff
yea prolly
will do, thank you so much.
Can an event listener be added for when entitlements are cancelled and expire?
.rtfm on_entitlement
Target not found, try again and make sure to check your spelling.
You listen to the update event
Ah so how do I know if the entitlement is being renewed or cancelled
Per the Discord docs:
The start of a subscription is determined by its ID. When the subscription renews, its current period is updated.
If the user cancels the subscription, the subscription will enter the ENDING status and the canceled_at timestamp will reflect the time of the cancellation.
Oh, sweet. Do you also know how I can tell a test entitlement apart from a purchased one? They both have the application_subscription EntitlementType
uhh
not really, i have never worked with entitlements
but they should differ somehow, check the discord docs themselves
hey so when i try to install pycord it comes up with this
remove the $
Where are you running this?...
where tf i get that lmao
You open a Command Prompt
yeah
or simply type cmd in the search bar of your apps
yeah i got it up
ok now install the library
consider learning python before trying to create a discord bot
just need it for a account gen lol
a what?
No, it does matter, because if it breaks the ToS, I won't help you and remove you from here.
"account gen"
so idk what u on about
What
Following the Discord ToS is common sense
you dont need to read it in a rules channel
💀
noone finna read discord tos
ibsr
Not reading it does not make you excempt from it.
It's funny when people who don't even understand that Windows is not for development are trying to do stupid shit like auto-generating accounts.
Hello !
is it possible to know if a timestamp is sent in a message ? like a mention I mean.
f.e a message containing a mention will have <@someID> but also message.mentions, is it possible to get the same information for the <t:123:F> ?
if not, I will fetch it manually using a regex
You need to regex it yourself yes
okay thanks, it will not difficult but if discord provided the information 🤷♂️
There might be something in discord.utils