#Basic Pycord Help
1 messages ยท Page 76 of 1
thats the method i constantly say should be removed. its stupid, abuses how python is supposed to work, and just causes issues
.rtfm Role.mention
Il pretty sure it should not be = but :
we also do it for avoiding the channel limit, we have reached the limit of channels already
there's a limit??
500 iirc
with 50 per category
how can an option name be None ?
shouldnt it be by default the parameter name ?
name: :class:`str`
The name of this option visible in the UI.
Inherits from the variable name if not provided as a parameter.
so here option.name shouldnt only be type str ? since if its not the option name it should be the parameter name
probably set later
not even (for what i can see)
well it has to get set somewhere
when i look for self.name = , there is only this line
so i dont really know from where else it can be set
SlashCommand._parse_options
so it will never be None but its typehint as None because its set in the parse option which first create the option and then set the var if None
it will be never be None after the Option's parent SlashCommand is initalized
strictly speaking, you could just make an Option at random that never has name set
looking at the code for option its a bit spaghetti imo, lets see how its gonna be in v3
most of v2 command stuff is pretty spaghetti yeah
btw does on_application_command runs after the command is finished/before/while the command is running?
i assume on_application_command won't block the command function from responding right?
on_application_command -> when triggered
on_application_command_complete -> when successfully finished
on_application_command_error -> when unsuccessfully finished
so they run at the same time, if i have a bunch of code in on_application_command, will it affect the responding time of my command?
they run in parallel
so it does not wait for any of those
only check and before will run before
^ events are scheduled and called as async tasks
If you override the actual event to do the stuff, then it will affect
It's best to use a listener which runs in parallel
on_application_command is a listener no?
If you use @bot.event, you're overriding the one from the library
and if for instance I'm adding await asyncio.sleep(1000) in the on_application_command, it will affect the command running too?
no
If its a listener, then no
@bot.event is a listener wdym
do @bot.listen(
bot.event will overwrite the default one, while the other one will not
im asking about the performance, because my bot is thinking a lot before the commamd responds
you can use
@bot.listen
async def on_application_command
and make sure you have no blocking code usage, like pillow, sync database etc
if you want me to check for any blocking code, feel free to share it
.tag paste
it's alr my bot have too much stuff going on
as you want
but if your bot is not answer at all for some time its usally blocking cod
it's fast sometimes and slow sometimes
then it should be blocking code
because when a blocking code is running it makes all ur bot stop
yeah ive made all image manipulation function run in executor
maybe you have somthing else
do you open any file ?
no just image file
or use sqlit3
just as a note, running stuff in an executor won't make it any faster
async motor for mongodb
at least it won't block my code
no time.sleep too ?
nah ofc not lol
yea but so you're saying even "light" commands take long?
nope, light commands are fast
Tag not found.
then I don't see the issue
.tag mongodb
MongoDB is a NoSQL database that stores data as documents in BSON format. In general, NoSQL databases are not recommended as most of Discord data you are storing is relational (e.g. economy things) while mongodb is for non-relational data, hence there is no reason to use NoSQL over SQL to store relational data.
-# Motor, the previous async driver has been deprecated in favor of PyMongo
Nevertheless, if you still want to use mongodb within your asynchronous code, use PyMongo for the async driver. Keep in mind that odds of you getting mongo support here are low as it is not a common topic.
- Official MongoDB Website
- Get Started With PyMongo
- Check Out The PyMongo Async Tutorial
well it can come from 1000 reasons if its blocking code
you could make a blocking code detector
my bot works fine with mongodb
I've done research beforehand
and check from here in which frame the loop is stopped
MongoDB is removing Motor
you're still using an outdated thing
i used it in 2020 what do you expect
i mean i coded the bot in 2020
but yea what exactly is the issue then if light commands are fast and others are slower
reading db is slow i guess
yea i agree read and write with motor mongodb is kinda slow
uh, I added everytime ctx.defer if I have to connect to my MongoDB
same
is pymongo faster than motor?
mongo is nosql..
sql***
I'll be having issues exporting data from nosql to sql lol
how many servers is your bot in
no im asking about the performance difference
I know how to read the docs wtf
1 sec.
900 now
you should be able to make a script for the migration (they might even be tools for that)
Are you running the db on the same server
wdym
yea but it's a pain
are you using a hoster or is it on the VPS you run the bot on
mongodb have their own servers
i mean if you only have to do it once and then you sure everything gonna be fine

do you only have 512 mb of stockage ?
mb
yeah i saw it
512 is enough for a db for some time
yea but not at 900 server
i have about 2k documents and it's only taking around 4mb rn lmfao
oh
2k users
btw, are you keeping the connection to the db open or do you keep re-establishing it whenever you need to access the db
you severely underestimate DBs
so technically i can survive up to 200k users
and nosql is space inefficient compared to sql
obviously keeping it lmao
connecting takes more than 5 seconds
wtf
no, 5 seconds is so long
and how long does an operation take
and everything said mongodb is faster than sql databases
find one usually takes 200ms to 1000ms uh
that depends on a lot of factors
200 ms average i think
since you can have ur sql locally and not mongo db, at the end of the day it will be faster
You usually have to work with indexes if you have quite a lot of documents.
you can
Search can be inefficient in non sql dbs
I host my MongoDB locally
sigh
i thought it was only on server, that's mb then
If only people only shared info they were certain about
how do you host it locally
establishing connection with the db isn't establishing it with the db servers?
what
on Amazon
lol
like aren't the db servers located at the company business location
dude you download the db server and run it lol
wtf
If you use atlas, yes
You're storing stuff in their servers
at the end its all the same, but just local
what's the difference
depending on where the servers are compared to your VPS it'll save you a lot of time
you need internet for the other one xd
one is hosted by a company, one on your server..
yea so should i switch to sql database or nah
it's really not that complicated lol
because online saying nosql is much faster
host it locally at your server and not online
let's just say the overwhelming majority of the world runs on SQL dbs
does it take more ram if i host the db myself?
my bot is already taking 2-3gb ram and i still couldn't locate the memory leakage smh
doesn't have to be a memory leak necessarily
There are more factors to consider when choosing a DB.
how about the performance tho
the lack of ping will make it much faster now matter how shit your server is
oh so that's the reason
200ms seems super much to me
on a local SQL server I get sub millisecond execution times
yea im tired of shit taking 0.2 seconds to search something in merely 2k documents
oh, at the online version you have a ratelimit
right
yea I mean search will always be slower with nosql
SQL is just better if you have structured and regular data
then why is everyone saying nosql is faster than sql
sigh
google is feeding me false info
let me guess, the AI summary?
no
Choosing a DB depends on many factors
im reading stack exchange
Toothy is right about having structured data, you should use sql
You also get some other advantages like integrity
apart from the user data, other data i have are non relational
like what
like two pieces data having their fields completely unrelated
that's normal lol
look unless you are storing VERY different pieces of data in every single row, or your DB schema changes regularly, you should use SQL
mongodb is overhyped and overused
ooo yes this
No
schema changes quite regularly
why / how
because that'll be easier to read when im reading the database from the mongodb app
what
im not home rn
Do you know what toothy means by schema?..
but i came up with the conclusion that the less work and most efficient solution is to switch online db servers to host it locally
yea the document structure
that's the least efficient method kekw
i mean u literally said it removes the ping factor
Then how the hell are you changing the schema that regularly
hosting it LOCALLY
does that
not on some fuck ass servers thousands of kilometres away
oh nvm I misread your message
my bad
not hosting it on the same vps im hosting with my bot?
you're confusing me now
that's what local means lol
Hosting it on your vps equals local
.
im not home rn
if you have the same data fields every time, or mostly anyway, mongo is unnecessary
most data fields are same yeah
but im too lazy to switch from nosql to sql when i can just remove the ping factor
that is completely unrelated
wtf
you can also host mongo locally, its just that mongo has zero benefits for your case then
the thing is im lazy to switch to sql as the effort:efficiency ratio is not that big of a difference
then have fun with 1s write times
and switching from online db to local hosting db can remove the ping factor literally making it sub milliseconds like you said
1s write time is too exaggerated lol
you said that
no i said read time
so.. write is even slower? 
๐ญ ๐ญ ๐ญ ๐ญ ๐ญ ๐ญ ๐ญ ๐ญ ๐ญ
I need to upload them in real time
My bot is like 15 files written in pycord I'm not switching to discord.py now๐ญ
Just to confirm there is no way yet to upload application emojis, only guild emojis, right?
not via the library no
Use the API
lol
on it ๐ญ
yea I think there's some way to make a raw API request using the library so you don't need to worry about authorisation and all that
but I really don't know about that
There's a PR for application emojis, isn't there?
mayhaps
seems like its merged
So if you install using the master branch, you should be able to.
.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
@discord.ui.button(label="English", emoji=":flag_us:", style=discord.ButtonStyle.secondary)
async def english_button(self, interaction: discord.Interaction, button: discord.ui.Button):
# Create a copy of the embed with the server name
embed_copy = discord.Embed(
title=english_terms_embed.title.replace("SERVER", interaction.guild.name),
color=english_terms_embed.color
)
error:
^^^^^^^^^^^^^^^^^
AttributeError: 'Button' object has no attribute 'guild'
why i get this error?
the order of interaction and button is different
really?
yes
since when
always?
it has to be always button first and after that the interaction, you also have to add both or else it is not gonna work
if im not mistaken, it's flipped around in d.py; pycord's order is button, interaction
What is the best way to translate my discord bot into another language (English)? There should be a setup command with which an admin can specify which language the bot should have on the server
localisation file, and then just change every string to currently_selected_language.stringname
the currently selected language is a bot attribute ideally
I find it hard to imagine how all this is supposed to work ... I mean, loading into each file and then also with the variables in the interaction responses. Are there any examples of this?
not really
its not really that hard tho
fetch the selected language from the db and load the appropriate set of strings, then just do selected_language.thisEmbedTitle or whatever
Is there any difference between using discord.Cog.listener() and discord.ext.commands.Cog.listener() ?
Both seem to work fine, but the official guide uses the latter
its just a shortcut
Yeah but the ext one has some overriden methods and I was wondering if they change anything important
The ext one overrides some commands methods, but I guess it doesn't really matter for event listening?
hm, weird
idk
even with this light code the response time is about 600ms, is this normal?
async def ping(self, ctx):
before = time.monotonic()
botlatency = round(self.bot.latency * 1000)
await ctx.respond("Pong!")
msg = await ctx.interaction.original_response()
await msg.edit(content=f'Pong! In **{botlatency}ms**')
await msg.edit(content=f'Pong! In **{botlatency}ms** Response time in **{round((time.monotonic() - before) * 1000)}ms**')
Sounds about right
Whats the bot latency?
And where is it hosted, country wise?
erm.. why do you use time.monotonic() and not time.now()
Makes 0 difference
600 ms seems a bit high
since you told me previously you were in the us
57ms
still seems like blocking code
im not rn
luma you are obsessed with blocking code
Thats fine
Look at the code please
what can make a bot quadruple the response time
I dont see any blocking code
could come from a check etc
dont necessary need to be inside a command
Well most people dont modify 90% of their library
well he did had a previous issue with check so
there's two db reads in my bot.check
if there is nothing blocking, the check should not matter
so it might be normal since rn ur not inside the us
i mean you are basically measuring 3 api calls
respond > original response > edit
reduce that
200ms per call would be more normal
Your expected network latency with the current setup would be 4*botlatency
- Initial interaction
- Pong
- Edit
- Edit 2
4*60=240ms
So that leaves 360ms "processing" time
This easily accounts for the majority of the those 360ms
The only thing that really matters is the time till the pong interaction reaches discord
Anything under 1s is fine
alr
you are forgetting the discord gateway slowness
which is usually around 130ms
True
how you got that name?
its from the 6+ years of nitro?
its a boost perk of this server
oh wow
This is a new one
discord.errors.ConnectionClosed: Shard ID None WebSocket closed with 1000
DeprecationWarning: parameter 'timeout' of type 'float' is deprecated, please use 'timeout=ClientWSTimeout(ws_close=...)'
Could you share the full traceback?
are you on 2.6.1
Not much else to it.. I've been getting the reconnect every so often, this is the first time I've seen the float warning
ERROR:discord.client:Attempting a reconnect in 0.16s
Traceback (most recent call last):
File ".../site-packages/discord/client.py", line 617, in connect
await self.ws.poll_event()
File ".../site-packages/discord/gateway.py", line 630, in poll_event
raise ConnectionClosed(
discord.errors.ConnectionClosed: Shard ID None WebSocket closed with 1000
.../site-packages/discord/http.py:216: DeprecationWarning: parameter 'timeout' of type 'float' is deprecated, please use 'timeout=ClientWSTimeout(ws_close=...)'
return await self.__session.ws_connect(url, **kwargs)
yes
It is probably from this line in pycord
msg = await self.socket.receive(timeout=self._max_heartbeat_timeout)
The aiohttp docs do not make it clear that using timeout like that is deprecated tho. Because that method calls the method in the error, it is not the method in the error.
you have the idea but not quite, it's as the error says; line 216 in http.py ```py
async def ws_connect(self, url: str, *, compress: int = 0) -> Any:
kwargs = {
...
"timeout": 30.0,
...
}
return await self.__session.ws_connect(url, **kwargs)
basically just needs a PR to change it to ClientWSTimeout instead
well, might need a version check
ahhh. version fun
wdym
the PR that deprecated float timeout is the same PR they added the new class for it; pycord still works with older versions of aiohttp than that, so you have to include both implementations
update aiohttp?
aiohttp is not a builtin module
I'm aware, but pycord isn't very strict on the version
Like my master bot I'm testing cv2 on uses aiohttp 3.8
just update to use the new method and raise the dependency version
almost as upsetting as people still using python 3.9 or 3.8
3.10 is thin ice
My assumption was that aiohttp versions itself to match Python versions but I didn't look too far into it
nah the newest is either 3.11 or 3.15
3.11.18 stable
actually no they just released 3.12
is components v2 in the git version?
Not yet, just the PR
nah ok
although it probably should be merged and 2.7 released
Do you know how long this may take? Invalid server list
No, also what does "Invalid server list" mean?
how can member.joined_at be None ?
self.joined_at: datetime.datetime | None = utils.parse_time(
data.get("joined_at")
)
uhm, without member intents?
The API does not mark it as optional so...
you do realize at the current pace v3 will never actually release right
be released on pypi maybe not
but it looks like its gonna be done before 2.8 ;)
Idk when exactly but Member.joined_at can definitely be None
guest members will have it set to None
(there's a docs pr for this but it's stuck in draft hell)
Very minor, but on mobile it shows the command still thinking even though itโs finished (very bottom of image). On PC, it doesn't show it.
After deferring, Iโve tried ctx.respond and ctx.followup.send for the embed and both show the same thing.
Am I able to remove that or am I missing something? Iโve tried searching, but canโt find anything about it.
Itโs just a straight reply. No buttons, menus, etc.
TBH this looks a bit like a discord bug because of how squished the loading dots are
known client bug
Awesome thank you guys. I just updated my app as well and it no longer shows. Should have done that in the first place
Whatโs guest member ? Is it smth new ?
been a thing for a few years, on invite creation click edit -> temporary membership
And like they can be in a guild for some hour and then they get ยซย kickย ยป ?
no, they're kicked after disconnecting from VC if they weren't granted any roles
Ok, itโs like a kind of application member but old fashioned
Good to know
well... not particularly? just try it
Under what conditions is discord.Thread.parent None?
you don't have the parent channel cached
is it the same for view.message ?
or if we send a view inside a slash command its not considered as a message so view.message is None ?
Is there any reason why User doesnt inherit from Member?
What?
A member is a special user
any member is also a user, but not every user has an associated member object
it does afaik?
it just has a _user attr

it setattr's the user functions' and properties
pycord internals are a bit weird
you can just use it as if it inherits straight from user
I just spent quite some time debugging an issue where the User was implicit converted to a Member, while the type remained a User, breaking isinstance checks
how does that happen lol
Slash command input
Fun fact
you can put ANY user ID into a slash command member option
are you typing it as : User or : Member
how is that expected
if it inherited from User? sure.
but since it doesnt, it doesnt make sense to implicit convert
It does effectively, even if it looks like it doesn't
well tell that to isinstance
yeah much more pythonic solution
or if member in guild.members
many roads lead to rome
I also dislike that you cant disable people entering non-member IDs, which isn't your exact issue but kinda related
so if I have an input typed as User, it would return a Member in a guild context but a User in a dm?
yes
...
remember, what you type it as doesn't matter to python
it's just a type_hint_
not a type_force_
which the library uses to know what input to expect
Nope
If you use the option decorator for example, and pass discord.User or discord.Member, what gets passed to the Discord API is essentially just "any user"
And after that the library gives a rats ass about what comes back
it's from dpy and IIRC it's faster to not inherit from it
This must be it. From member object discord docs.
The field
userwon't be included in the member object attached toMESSAGE_CREATEandMESSAGE_UPDATEgateway events.
So you can create a user if you only have some of the info
hello! sorry if this is off-topic, im using aiosqlite. is it good to use WAL?
whats that
I donโt really see the point of it except if you have a really big bot, but else except needed more space there is not big change
Instead of editing directly the db, it will first append each commit in a file and then it will be merge to the db
So it can help with concurrency especially with sqlit since you can only have 1 connection
it has almost the same size as the main one, which is kind of eating up my vps storage
i want to turn it off, but it might cut some of my processing
or idk
Then if you donโt have a lot of place in ur vps you should not use it
Stop all process, check with the checkpoint to be sure and then delete ,
ok, thanks!
Do I have to add a view on each Guild in the on_ready method to make it persistent or is it enough if I just do self.bot.add_view(view)?
Or do I have to do:
for guild in self.bot.guilds:
self.bot.add_view(view)```
Why would you need to iterate over the guilds lol
You're not even using the guild object in the method
I go through each Guild because I pass the language of the Guild to the view to create it.
rn ur not doing it
but self.bot.add_view(view) is enough to make the view persistent inside ur whole bot
no need to do it guild by guild
But how should I do it if I pass the Guild Local when creating the view?
Then I have to pass it again when persisting so that I don't get an error?
then you pass it again
for guild in self.bot.guilds:
self.bot.add_view(MyView(guild=guild))
Okay thanks
I have been doing that for year without any issue
Maybe itโs not how itโs supposed to be done but it works
im doing like so for example
and it does add the view correctly and also keep each option correctly, but maybe you can also just pass None and its gonna work (dont remember if it works with None)
me when people actually read their code
is there a way to display a role but dont mention it? because role Role.mention, ofc mention it
discord.TextChannel.send_message(
content=role.mention,
allowed_mentions=discord.AllowedMentions(roles=False)
)
allowed_mentions=discord.AllowedMentions(roles=False)
alright thanks!
is it possible to check if a message is sent from a thread? smth like
if message.channel.type == "private_thread"
if isinstance(message.channel, discord.Thread) and message.channel.is_private():
...
thank you!!
gosh this syntax needs a change
wouldnt be necessary if the lib was more strictly typed
It's also just ugly like that imo
feel free to suggest better solutions
smth like if message.channel.type is ChannelType.PRIVATE_THREAD or smth idk
that doesnt type narrow it
also why is is_private a method ?!
all methods
yeah ik that was a rethoric question
true oops
well
just make a class PrivateThread etc... and all inherit from a common thing
but do it actually correctly
cause rn it's a mess
there's not clear inheritance path
Also, make Member inherit from User ๐
I'm not sure about that one
message.author is always included
which is a full user object
Its also not typehinted as optional
how would that help?
not possible as you heard before
My last 4 messages describe why it is
not really
It can return a full or partial user
how would typing make it easier?
No need for pointless isinstance checks
Heavy use of generics by the lib
So a type checker would know that message.channel is a discord.Thread
That is not how it worksโฆ
did you get infected by luma with his typing virus?
Prolly
This is the minimal solution. It doesn't matter if its typed or not.
You can have a helper function typed as a TypeIs[MessageSubclass] return type
yea but you will always need an isinstance
class PrivChannel(discord.Message):
channel: discord.Thread
def is_priv_thread(ch) -> typing.TypeIs[PrivChannel]:
return isinstance(ch, discord.Thread) and ch.is_private()
Yes, but makes it more readable
And still does that type thing
has nothing to do with how the lib is typed tho
So maybe they like it more
akos is just infected by lumas typing virus
Didnโt doubt it
just tired of having to do shit like this
didnt know about TypeIs, thanks.
Oh interesting I only knew TypeGuard
dont lose ur mask, you could be infected soon too
how can InteractionChannel be a category ?
yeah i saw that, but how is it even possible
is it just a mistake or is it really somth that i dont know about discord
I guess the official docs didnt bother with it
I dont think it can actually ever be that
Yeah because it is the recommended one, but it is way too unsafe
https://rednafi.com/python/typeguard_vs_typeis interesting
The handful of times Iโve reached for typing.TypeGuard in Python, Iโve always been
confused by its behavior and ended up ditching it with a # type: ignore comment.
For the uninitiated, TypeGuard allows you to apply custom type narrowing1. For example,
letโs say you have a function named pretty_print that accepts a few different types and
p...
there are probably even cleaner ways to do this
how am i supposed to pass a list of snowflakes into the role edit ?
should the list of role id already be a list of snowflak ?
just do roles=[r.id for r in roles]
same, it asks for a list of snowflake and not int, i moght just cast it then
Snowflake is literally just str | int
so this doesnt work here, it looks more for a list of object
there are two snowflake types?
no, i worry about important things
That is in types, not the protocol
true
And how would the lib know what type to return the interaction.channel without it having bunchs of if statements
cant that be possible with typevar ?
Yes, but still the lib would need bunch of if statements per channels
Typevars canโt magically guess the type of a channel
Unless explicitly stated
the luma virus
if its inside the library and not on the user side its better dont you think ?
No
i legit dont see the issue with the current solution
Which of all lol
i dont know what is his issue so
but for example the rework of the get or fetch using the typevar is really nice
overloads...... we.. are.. in python..
The API docs don't specify that it can't be.
:)
a nice thing i would love to see implemented is a better support for custom context, for example using typevar and so being able to pass our context too
like so :
Context[MyContext],
this is just an idea, i have no idea how can or if its even possible to implement this
use Object
What
You can do that
Just override your get_(application_)context method to default to a custom subclass and use that custom context annotation instead of the default one
to use it yes, for the typehint not really
Why not
You can just typehint it as your custom class
even strict type checkers will allow it
not really, or i dont understand how
Error is self explanatory
Tbh
You trying to override a converter to return Emoji but expects a Role
im talking about the above one (other one is a typo)
And when you using commands.Context is expecting to be a LumabotContext type or any that subclasses it
Why annotate it like commands.Context
so im doing like this to pass the context, but its telling me its not
so i did try to do
commands.Context[LumabotContext] (which is not possible since its about using Bot etc
for a bit more clarity using a known class, here also an example with bridge ext context
and so it leads also to some issue here
so if its possible as you said, could you give me some pointers ? because im a bit lost tbh
All the red error at the right side ;3
mainly because of overrides
(rn i have to fix 800 errors inside 1 file) mainly untyped dict
No, it is a (private-ish) superclass of Bot.
I'm using bridge commands but doesn't seem to work in DMs, any way to solve this?
The slash commands are not working? And when you say "in DMs" do you mean DMs with the bot or DMs with other people?
They simply don't show up in conversations with other people
Is your bot user installed?
Yep I can use it in different servers which it's not in but not DMs
Have you set the contexts?
Here's the slash users example.
This example shows how to set the contexts if you have not
Cancel that, it seems that it's only showing in servers the bot is in
I'm using bridge commands not normal slash
No problem, then you need to also set the integration types as shown in the example as well.
I think it should still work for bridge
For each command?
You can set it bot wide as well
@bot.bridge_command(integration_types={discord.IntegrationType.user_install})
async def embed(ctx: bridge.BridgeContext, *, url: str):
"""Uploads a video to Catbox and returns an embeddable link."""
Completely empty
In my other bot that uses normal slash commands, I didn't need to do any of this
https://docs.pycord.dev/en/stable/api/clients.html#discord.Bot.default_command_contexts Here is the link to the place that you can set the defaults for the bot (bridge.Bot inherits from this so it should still work)
Have you refreshed discord client cache with ctrl+r?
Try setting the contexts as well. I just skimmed the internal code and it looks like bridge should work with contexts and such
*, url: str not so sure that this syntax works with bridge commands
but that is secondary to the current problem
Yes even restarted it
Seems to be working fine in the server
This seems to have worked
bot = bridge.Bot(command_prefix="!", intents=intents, case_insensitive=True, default_command_contexts = {InteractionContextType.private_channel}, default_command_integration_types = {IntegrationType.user_install})
Just making sure you are aware ๐
Thank you
hello!
is_booster = True
if not isinstance(ctx.author, discord.Member) or not ctx.author.premium_since:
is_booster = False
this only checks if the user is a booster. what about checking if the user boosted in a specific guild...?
You should check whether the user avatar is animated, they have a banner also, because they maybe have nitro but have not boosted any server your bot is in
oop you are right!
Member objects are already tied to a specific guild
Hello, i trying to do stuff with some variables when i close the modal without sending it, but not luck trying with on_timeout() or _dispatch_timeout(), gemini says on_timeout would me enough to do what i want, but dont trigger when i close it. ยฟideas?
This is because Modals have no timeout by default
So they never really time out
And discord does not let the apps know when someone closes a modal without sending it
thats bad, because thats exactly what i need, i dont want the modal to timeout, just know when a user haves or not the modal open
unfortunately it's impossible to know if a model is currently open
your bot can ONLY know 1) when a modal is first opened and 2) when a modal is submitted
shame, i will try to find another way to do what i want. thanks for the replies! ๐
but the user still bypassed it idk why
please help

I feel like I've asked this before, but choices loaded when the bot loads, right? There's no way to change that list without reloading?
the command needs to be synced again
Mm. Which is somewwhat broken in pycord currently iirc. Isn't that what Wolfy was working on
its working
maybe not as optimized as possible
they might also be some issue of commands not being remove when cog is unload or somth like that, but if you sync again it works
As far as I can tell it just syncs more commands then it should. Like luma said it is more of an optimization fix.
hello pycord discord server. I am intending to make a bot that does an action at 8:00AM every day. I saw tasks in the guide that could help me.
I saw that the task can take either a time interval or a sequence of datetimes. I have two questions:
- is there a way to tell the task to start looping at a certain datetime.time, and then loop with a time interval of hours=24
- can I provide an infinite generator object that yields datetime.time's as the time parameter (now that i type this out, it feels like a bad idea)
you can have an inner sleep until that time, then start the loop
when starting the loop, there will always be one iteration the time it gets started
something like:
@tasks.loop(hours=24)
async def task():
...
when_to_start = datetime....
await discord.utils.sleep_until(when_to_start)
task.start()
you're one of the greatest aint no debating on it
I do think there is a better way using the time arg
@tasks.loop(time=datetime.time(hour=8)
with this is will run everyday at 8am (depending on ur timezone)
(and so you dont need all the when to start and sleep
(i might have not understand everything you ask but this seems more logical imo)
They want to wait till X timestamp to start the 24h loop
I thought this X timestamp was the 8am, so then it can turn every 24h
If not then I misunderstood their message
which is exactly what Lumas thing achieves.
One thing is wait till X time, ie waiting for 8 am, no specific day / month, other for a timestamp
If they meant the first, they should use Lumaโs suggestion
Why do I get this error? Although I've accessed is_finished attribute anywhere in my code.
Send the code please
@echo wraith Congo dude, ur exams finished ๐ฅณ
Thank you ! ๐
Finally ๐ญ
when you do a search in all of ur files about is_finished do you have any result ?
I'm on my phone I'm gonna take a look in 5 mins
Nope
strange because by looking at the pycord code, they are never using it before checking if view is not None
are you on master ?
yes
can you show us the full traceback ?
it occurs only after running that command, so that's what it gets printed in terminal
No but like the full error
inside ur error handle print the traceback
๐
error.__traceback__
if u do print(error.with_traceback(error.traceback)) it shows this only
maybe you need to use error.original
try to do
error = error.original
and then ur thing
and last option is just remove the on_application_error for a moment
if you have an error error has no attribut original then you dont need it
and so just try to remove ur error handler
the view you pass is wrongly pass from what i understood
ass ๐
it seems that its None
please
@errant trout could you add this inside your v2 pr ? or should i make one ?
basically in the async py it check if the view is not missing but not if its None, its also the only place where it does that
i dont know if its intentional but i dont think it is
@fresh sierra Is there any way to get the tracebak from error handler too?
but should it not handle by itself if a view is None ?
then if its intended no need for a change
i already told you how to
Is this correct, it doesn't throw err now...
@commands.Cog.listener()
async def on_application_command_error(self, ctx: discord.ApplicationContext, error: discord.DiscordException):
error = getattr(error, "original", None) or error
print(error.with_traceback(error.__traceback__))
i understand it's not the most intuitive but that's how MISSING operates and i'm not gonna make an exception specifically for view - you simply shouldn't pass it at all
yeah this works
But we pass view=None while editing messages and it remove the whole view....
it was logical for me that the respond could also have None for view since the edit for example also have None
yeah that's in edit, not send
i never really noticed that the send cannot have view = None tbh
ye same here
that's not specific to view, generally if something is typed as MISSING it's because None has a different purpose
but this isn't always the case, for the most part MISSING is just legacy design
changing it is a larger scale thing that i'm not addressing in this pr
we do get the usecase of missing, but because we were used to view=None in edit we got induce in error for this send too
Doesn't send the full traceback
show me ur code
ye
maybe try like this :
tb_str = "".join(traceback.format_exception(type(error), error, error.traceback))
it does work on my end so i dont really know why it doesnt for you, (maybe different python version)
what send the ss
?
elif await check.is_dev(ctx):
error = getattr(error, "original", None) or error
tb_str = "".join(traceback.format_exception(type(error), error, error.__traceback__))
error_em.description = (
f"{emoji.error} An unexpected error occurred: **`{error.__class__.__name__}`**\n"
f"\```py\n{tb_str}\```"
)
this works
it's literally the same exact result
Another thing I discovered ๐. For file= too u need to pass discord.MISSING instead of None (None throws error).
but different concepts
yea, one is using a workaround for no reason, the other uses the intended way
So ig this is where I ask this lol, I was redoing my cog loader yesterday and I somehow broke it to the point where I'm not sure how to fix it. I'm getting the object list can't be in await when trying to load cogs and my cogs are setup using async def setup(bot) then await bot.load_cog(mycog(cog))
And my loader using await bot.load_extension(module)
Any ideas or suggestions would be appreciated
Wym?
In Pycord when loading an extension or adding a Cog it is not async, you are probably using discord.py
Oh I see now, I probably confused the too when watching a YouTube tutorial thanks
I don't recommend YT, many videos are not updated with the current discord API
See the documentation
I presume that would be in the cog section of the docs
Cogs, often known as modules or extensions, are used to organize commands into groups. This is useful
Thank u kindly!
This is so cool
that's not even the start of what you can do regarding task timing
did you never check the docs on tasks?
Is it now?
Check the docs
on master it can afaik
Ig 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
Oky
Bots: Attributes activity, allowed_mentions, app_emojis, application_flags, application_id, auto_sync_commands, cached_messages, cogs, debug_guilds, default_command_contexts, default_command_integr...
here
Tyty
Is there a plan to put the user tag into the discord.User object? Currently I'm querying the day like this:
result = requests.get(f"https://discord.com/api/guilds/{MAIN_GUILD}/members/{member.id}", headers={"Authorization": f"Bot {TOKEN}"})
if result.status_code == 200:
data = result.json()
user = data.get("user")
if user:
primary_guild = user.get("primary_guild")
if primary_guild is None:
log("ERROR", f"Member {member.name} ({member.id}) has no primary guild set.")
continue
if primary_guild.get("identity_guild_id") == str(MAIN_GUILD):
if TAG_SUPPORTER_ROLE not in [role.id for role in member.roles]:
await member.add_roles(tag_role)
await channel.send(f"Added `{tag_role.name}` role to {member.mention} ({member.id})")
Not until its officially documented.
It's not worth adding not documented stuff because they're subject to change at any time.
Too bad
You can also use the http module from the lib to get the raw json
You dont need to make the raw request all by yourself
How do I do that?
raw = await bot.http.get_user(member.id)```
Then you can access it normally as a you would with dictionaries
Does this also include rate limits?
๐
Can I delete ephemeral messages with a button interaction?
delete_original_response
why is py-cord sending multiple on_ready signals?
that is why I changed it to .listen(once=True) instead of the event
ah
reconnects to DC
had 2 of them too some minutes ago
oh i see
why would i be getting this error with a view?:
Ignoring exception in view <UserSettingsView timeout=600 children=5> for item <Button style=<ButtonStyle.primary: 1> url=None disabled=False label='Edit Template' emoji=None sku_id=None row=None>:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.9/site-packages/discord/ui/view.py", line 426, in _scheduled_task
await item.callback(interaction)
File "/home/container/cogs/settings.py", line 26, in edit_template_callback
await view.initalize(interaction=interaction, followup=True)
File "/home/container/core/utils.py", line 261, in initalize
raise e
File "/home/container/core/utils.py", line 259, in initalize
self.main_message = await destination(embed=embed, content=content, view=view)
File "/home/container/.local/lib/python3.9/site-packages/discord/webhook/async_.py", line 1812, in send
if view is not MISSING and not view.is_finished():
AttributeError: 'NoneType' object has no attribute 'is_finished'
function source:
change default view value to MISSING, or do not pass it at all
But I get spammed
Bot was on since a day
but this happened today at 4:00am
on_ready can fire many times due to how the discord gateway works
but I didn't even restart my bot that time
it was up like always
Yes, on_ready is not a one time event. It is normally for it to trigger once every few hours/days. Discord was having some issues so it fired more often for a bit
hello pycord discord server. is the following issue normal? i am making my bot able to join and leave voice channels with these two methods. it joins just fine, but attempting to call play on the ctx.voice_client while it's connected to my channel gives me a ClientException: Not connected to voice.
The bot leaves the voice channel after a minute, but ctx.voice_client still exists after it leaves, and trying to call join will say it's Already connected to a voice channel.
the leave command doesn't seem to do anything to the voice client. the bot doesn't leave the channel when I call /leave.
what did i do wrong? prob something simple, i just can't find it
maybe i'm misunderstanding what ctx.voice_client actually gives me, let me check the docs again
ctx.voice_client
it says a shortcut to Guild.voice_client
Guild.voice_client
it says it "returns the VoiceClient associated with this guild, if any."
I assumed the VoiceClient I get is something I can then call .play() or .disconnect() on, am I right? that it is the voiceclient that would return from my await voice_channel.connect()
...
it started working
okay well... maybe my computer bad
ok with no edits it stopped working
ima go to sleep.
hello again! some people can't let a homie enjoy learning a cool thing without telling them they should have already known cool thing. they have to question said homie's competence. I appreciate you and the others opening my eyes to pycord's functionality but I don't need to be asked if I never read the docs when my original question was literally asking about it. the phrasing was a little discouraging, that's all.
you seem nice though, and pycord is still cool to me
what you're doing is assuming
class MyView(discord.ui.View):discord.ui.View
@discord.ui.button(label="(0) Vote", style=discord.ButtonStyle.success)
async def button_callback(self, button:discord.ui.Button, interaction, timeout=None):
``` why does the button still time out? (Im assuming after 180 seconds since last interaction since the docs say thats the default)
its not inside the callback
Timeout is something you pass to the view constructor not the button arguments
Do you have an __init__ anywhere? If so you should then you can call super().__init__(timeout=None)
class MyView(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(label="(0) Vote", style=discord.ButtonStyle.success)
async def button_callback(self, button: discord.ui.Button, interaction: discord.Interaction):
okay that makes sense, thanks
i woke up again and it still is not working, does anyone have an idea of how to make it more consistent? could it be my machine
Voice is fucked up
You have to install a pr if you want it to work
โ
ohh ok
i'll look into it
also, does anyone know how to make bytesio work with a discord.File? saved_img contains the right contents when i try to reopen it with PIL.Image.open(saved_img).show() but the discord.File gives me wack
should I be using a different io class?
oh i fixed it by adding saved_img.seek(0) before my send from stackoverflow
@fresh sierra in the docs it says that the listener cog_unload() must not be a coroutine
Itโs just a function
def cog-unload
but if I do
@commands.Cog.listener()
def cog_unload(self):
self.lavalink._event_hooks.clear()
it throws error
ok
You should first use this
.tag rie
You can run blocking code (such as PIL/Pillow) in an executor to run it in a separate thread:
def my_blocking_func(*args):
...
@bot.command()
async def test_command(ctx):
ret = await bot.loop.run_in_executor(None, my_blocking_func, 'put', 'args', 'here')
See the python documentation for more info.
Else it will block ur whole bot
we are so back
@fresh sierra Have used Lavalink?
yeah, i will do it now
so you fixed the other issue
im using wavlink with lavalink
so whats the official way to use bridgeoption since option is depreciated for bridge commands
@bridge.bridge_option()
AHHH thank u
if my command has awaits in it, am i able to turn it into a blocking function, or should i like segment away the parts that are blocking
actually disregard
actually regard
actually disregard
nope
if there is blocking code, even tho its inside an await function it will still block ur code
what..
oh dang
that's why you run it inside a separate thread aka rie this ensure that it doesnt block the first thread
i understand it now
hallalujah
do you know where i can find this?
i swear you're the goat or my name isn't akash
whats the proper way to fetch global slash commands when ur using bridge.bot
wdym? what for?
basically i have an api cog that checks various things one of them is slash command desync and i was using py self.bot.tree.fetch_global_commands()
but tree dont exsist lol
that is not py-cord, that is discord.py
does pycord have such a thing?
it technically does, but to be completely honest pycord's command fetching functions are implemented in a pretty convoluted way
oh boy
let's see
For what do you even need that?
personal use of the api breaking my slash commands ig?
?
if you're fine with raw data you can run bot.http.get_global_commands(bot.user.id)
ahh i see thank u
Hey, guys. Anyone familiar with this error?
Join failed: Shard ID None WebSocket closed with 4006
I have a bot that's meant to join voice channels, but recently, I notice that I get this error a lot and it simply crashes. The bot will work when I join a fresh channel after a long time, but then when I try to move it or use it in any channel I've already been to, it breaks.
Any help on why my bot (working for years just fine) connects to a voice channel but fails on the vc.play() command? Error is not connected to voice for some reason
we have the same issue stew
check this out
i haven't installed it yet but yeah
Currently I am initializing the lavalink client on_ready event
this works but every time I need to access self.client.lavalink ourside of this function I won't get type annotations
lavalink.py docs (examples) says to do like this
But when the cog is loaded the client isn't ready due to which we can't access the client.id, thus throws error
Any fix for this?
add it to ur bot custom class
if you want to have it on ur bot attr
on my side i dont really do that, i just have a function get player that vie me the current player
Same here too dude
it was the lavalink node initialization
where add a node
@fresh sierra?
ye
Show code
I too did the same
but
when u run the function for the player
du get the typehints?
Yes, because I typehint it as a wavelink player
Also using cast
for every player?
I only have 1 player at a time
I donโt get many player
Is there any way to change the view emoji from here?
And then edit the message with the new view?
@fresh sierra?
Like some .emoji = "<>"
Edit the view maybe
First you get the view
Then you get the item you want
then
You should maybe cast this into the item it is and then you will be able to
Like
item = view.get_item(ยซpauseย ยป)
button = cast(discord.ui.Button, item)
button.emoji = โฆ
message.edit(view=view)
that makes no sense
we're not in java, you dont have to cast stuff
If he wants the typehint he will have to
Its showing type hints, like disabling, callback etc...
but not title/emoji
i think you need to replace it with a new button and edit the view
Because item have all of that, but not emoji by default
it gives discord.Item type
Since for example view does not have a emoji attribute, so by casting it it will typehint it as a button
And so you should have then the emoji showing
not necessary and also doesnt solve the issue
Tell me another way to have the typehint of emoji without casting it or using isinstance ?
either you can edit it directly with .emoji(whatever) and edit the message with the same view or you do this
there is no need to
and why does that matter? it doesnt
he also wants the typehint, by doing ur thing he will not have it
@wheat tiger do you want to also have the autocomplete for emoji ?
i might have misunderstandood ur requests
just obtaining the item and setting the attribute works
no need to replace on the view
oh wait they never sent the view they're editing it before sending
yea then its easy
even if sent they don't need to replace it lol
^ just edit the message afterwards
yea but they'd need to at least edit the message with the then changed view
This works
if you get_item and then edit the item it will automatically update the message ?
not the message, but the reference on the view
you still need to manually edit the message
type hint ๐
i wish people stop crying for everything
yea, like useless type stuff

