#Basic Pycord Help
1 messages · Page 75 of 1
is any is getting deprecated, what is the alternative ?
executionEnvironments = [
{ root = "src/database/models", blaBluh= false }
]
@fresh sierra
in pyproject
it isn't ?
is it ?
i thought that what you said yesterday with List etc
no any isn't
that was my point
mb then
getting a bit chunky but everything for typehint ig
only 200k lines left to do
😭
do you use mysql or postgres?
mysql
ok
@fresh sierra if you used postgres there was this https://tortoise.github.io/contrib/postgres.html?h=arrayfield#tortoise.contrib.postgres.fields.ArrayField
I really think you should consider postgres given how many json / list fields you have
mysql is setup by defualt with pterodactyl i think
but its ok doing like this is enough
rn im trying to find all thing i should ignore
I mean yeah but it's rly not efficient in db
btw ignore them in pyproject like I showed above
yep that's what im looking
to see all of the thing i can do using this
btw false, not "none"
when i dont know how to typehint a dict, what should i do ?
@staticmethod
def load_yaml(file_path: str) -> dict[]:
"""Load a YAML file and return its contents."""
with open(file_path, "r", encoding="utf-8") as file:
return yaml.safe_load(file)
I assume that's a dict string to something
so probably
dict[str, Any]
Also
you should probably add
to your pyproject
typeCheckingMode = "all"
reportAny = false
reportExplicitAny = true
Also make sure you're actually using based pyright and not just pyright
rn im using pylance, i tried using basepyright but too much error, i'll see to switch when its already done with pyright
You would be better of starting with basedpyright imo
also
you could use baseline
which will ignore all your errors
and allow you to gradually type your code
but baseline is only in basedpyright
idk what is baseline, do you have some docs ?
are they better way to typehint this that this longggggg dict etc etc
do you use python what version
e.g. of baseline
im using 3.11
looks nice, i willhave to check that
ok
so you can create a type alisas
TranslationDict: TypeAlias = blah blah
thanks
well it is nice but you still have 147888 errors that you will have to fix...
im at 8k rn (using only half of my code tho
that's the pycord codebase
btw
yeah, but I just fixed 200 in 10 min :)
... v3 soon
in 3 years probably
16k
more
22k
bruh
The aliases to collections.abc like Callable and typing equivalent of classes that are now generic like list, dict, tuple are soft deprecated yes.
"Soft" because they aren't getting removed anytime soon and no plans to either.
Any has no replacement and it probably never will.
Any is not
yeah
you edited
there is any but it's completely a differen thing it wouldn't make sense to replace it with
and only 7k rn
Yeah
(but i only migrated 1/3 of my command i think)
38errors for that...
how can this masterpiece be an error
Huh I never noticed that lol
look how cool
is there a way to ignore lib errors ?
For a long time I only used r in regexes and so I thought r was for regex and only laterearnt it was raw
Lool
Up to Python 3.9, yes. Above Both Version are valid, cause it is any type but inside a tuple when you work with args and kwargs. One is less typing, the other more precise. Both are valid and accepted.
- Add your own stubs
- type it inline yourself:
respond: Callable[...] = ctx.respond - Ignore the specific warning
# pyright: ignore[reportUnknownMemberType]
I would recommend 3
- Will still cause unknown error
3 is best also imo
Not if they use a whole protocol with all the params 
Ahh
Right
- do a pr to fix that
but im gonna do 3

- Force plun to merge that not in 4months
Real
if i have a subclass of ctx, can i just change it ?
Maybe
You'll probably get incompatible override but yeah
also annoying because i do lose the docs
¯_(ツ)_/¯
Yeah cause kwarg :)
i think im gonna just give up
because if i need to "fix" also every error by pycord im not done
will there be a way for a typehint to automatically set bot.user to the ClientUser in event, commands etc since we cannot receive events if we are not logged in
Just do it yourself,
class MyBot(Bot):
user: discord.ClientUser. # type: ignore
It won't be none ever really
Does anyone know how to make these types of embeds?
components v2, not possible in pycord yet, its a PR
Is there a utils fonction to keep the doc associated with this ?
Components V2 are under development in pycord and aren't yet included in the official releases on PyPI or the master GitHub branch. However, you can access the features now by installing directly from the pull request #2707. To do this, use the following command: pip install git+https://github.com/Pycord-Development/pycord.git@refs/pull/2707/head Please be aware that this is a development version and may contain bugs, feel free to report them by adding a comment to the pull request.
Wdym? It's an attribute
You know when you hover it it does give you an explanation
Ty
it is because it is a property in the first place
and you are overriding it as an attribute, so the docs are missing
And is there an utils fonction to turn it as an attribute
If not that’s not a big issue
the utils copies the doc of a function to another, nothing else
just override it as a property
and not as an attribute
class MyBot(Bot):
@property
def user(self) -> discord.ClientUser:
return super().user # type: ignore
ok thanks !
i dont really get how im supposed to make the fix this
how can i define it
Type of "__init__" is partially unknown
Type of "__init__" is "(*items: Item[Unknown], timeout: float | None = 180, disable_on_timeout: bool = False) -> None"
-> None on your init
at some point typing is just a hindrance
Looking at venv/Lib/site-packages/discord/ui/view.py on line 164, constructing that class requires the first parameter to be of type Item. Then using PyCharm's feature to jump to the declaration for item, it takes me into venv/Lib/site-packages/discord/ui/item.py -- so maybe you're missing an import?
voidCaster missing the point, episode 5981
It's typing related, not an error at runtime haha
well i also did that but didnt really change anything
Yeah, which is why the missing import was suggested. It's an error presented by an IDE and IDEs usually check for that sort of thing. Why else is the error saying Item[Unknown] unless the IDE can't resolve that object reference?
reading comprehension is hard
uhhh then my next best guess is that you can't *args **kwargs in super
but i might be completely wrong, i don't use pyright
so tried putting nothing in it it still shows, ill investigate thanks you still
havefun
i dont import really anything since im using just args and kwargs, and maybe that can be why
the closest issue i found was https://github.com/microsoft/pyright/issues/698 explaining it to some extent, maybe read through
I tried to replicate the problem in PyCharm 2022.3.1 Community. I don't get any such errors at all. Just 2 imports.
from typing import Any
class BotView(discord.ui.View):
def __init__( self, *args: Any, **kwargs: Any) -> None:
super().__init__( *args, **kwargs )```
maybe it comes from Pylance
(also im using strict typing)
I'm wondering if maybe you have too many imports now XD Like multiple objects are resolving to Item
sigh
its pycord code
been trying to fix for 30min this error, only to find out that when using a stub file it raise this
gonna have to find out later how to be able to fix this using the sub...
How do i get label of selected option in Select, not a value?
if you want 2 differents one use label and value, by default value will be the same as label
the question is rather why you'd want the label, ever
when recieving an interaction, discord only sends value - if you want the label for some reason, you would need to retrieve the SelectOption from Select.options; you can do something like discord.utils.get(options, value=value)
(basically iterate through options for a matching value)
in my case they're different
got you, thanks
yeah i didnt understand first what you meant
does pycord have cv2 docs yet for the dev build
Components V2 are under development in pycord and aren't yet included in the official releases on PyPI or the master GitHub branch. However, you can access the features now by installing directly from the pull request #2707. To do this, use the following command: pip install git+https://github.com/Pycord-Development/pycord.git@refs/pull/2707/head Please be aware that this is a development version and may contain bugs, feel free to report them by adding a comment to the pull request.
Oh you want docs specifically
yeah
There is a way to get them via direct URL I think, give me a second
This is a list of Frequently Asked Questions regarding using Pycord and its extension modules. Feel free to suggest a new question or submit one via pull requests. Coroutines: Questions regarding c...
Thank you
FAQ page was not changed btw. Just what the link defaulted to
Hey all, I've built my bot project into an exe, however now that I've placed it onto a VPS, it is throwing this error. The bot has Admin perms in the discord, can anyone tell me why this is happening
Why?
Why what?
Why did you convert it into a exe?
To move and manage, you can use a .zip
But - I've also tried with a py file and it's complained the same way
Ill get that sorted later- but the same error appears when ran from a py file
you specified guild_ids that the bot isn't in
How can I set the slash commands only be visible at the Guild and not at the dm's?
contexts arg
@fresh sierra Is there any way to get a TypedDict return type from a Tortoise ORM Model?
So that I can get type hints?
Currently I've to manually type it
Here how I do
but that ain't typed dict ig?
I just read dict, so I showed rolesetc
Why do you need it typed as tupedict ?
for function returns
It should already show everything just by type hint it as the model
I see, why don’t you just return the GuildTable ?
that doesn't work
it is returning dict
either normal dict or TypedDict works
Wdym it doesn’t work ?
Why are you not changing ur function to say that it’s retuning the model I meant
won't get typehints
Why would it not ?
does it for u?
Ofc the model give me all the typehint
lemme try again
but i think you just use get_or_none and not firlter in this case
No I am talking about column typehints
then do like i did
here
Hmm works I don't need dict here lol, I can directly access the object
.<name>
Is there any way to make literals of the model (for param type)?
@fresh sierra
what do you mean litteral of the models ?
Literal[]
lemme see if it works 💀
I meant here
in settings param I want to get the column names
here it is
for field_name, field in StatsRoleTime._meta.fields_map.items():
no need for that
Where will I add this?
the for loop?
where you need to get the field name
Type Hints 💀
i see, idk if there is a way to show only like this
We can get the names by writing code, wish if we were able to make types like that 😔
well, you could also just pass the object with name like table_name. column.name
Why am I getting this error for autocomplete?
I don't get any autocomplete
i dont think it come from this autocomplete
How can I do global error handling for missing bot perms in slash commands?
on_application_command_error
what instance?
I mean, what instance should the error needs to be?
the isinstance() check
Well what decorator for permissions are you using
and for group slash commands, default_member_permissions
Sorry, lol I forgot, doing that doesn't show the command to unauthorized user
well I meant the permissions the bot is lacking
like if bot doesn't has manage members permissions
then it will throw error
They usually raise Forbidden
If you want to check for permissions before, you have to use the decorator
https://docs.pycord.dev/en/stable/ext/commands/api.html#discord.ext.commands.bot_has_permissions
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...
And it will raise
https://docs.pycord.dev/en/stable/ext/commands/api.html#discord.ext.commands.BotMissingPermissions
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...
Is there any way to get the permission names, without doing the bot_has_permissions() in each slash command?
Like the global exception
Is player a reserved word somewhere? I was trying to debug why my Cog commands were getting discord interaction errors, but changing it from this:
to this
player_check = discord.SlashCommandGroup('player_check', 'Player related commands.')
and the commands to @player_check.command fixed my error.
**Here is what I wrote below before I tried changing that, but I don't know why 'player' as the slash command group name would have been the cause. **
||Am I missing what is different between these two files? https://www.diffchecker.com/PFrH4C4N/
On the left-side is my original code, the right-side is the duplicated code.
With the original code, I was getting these errors if I spammed the interaction multiple times (or even with two accounts doing it once each at the same time). It would correctly respond sometimes, but the rest would error out.
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
``` and
```py
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: HTTPException: 400 Bad Request (error code: 40060): Interaction has already been acknowledged.
I made the duplicate cog file with the identical code (different group name), and it will let me spam the command with no issues or errors.||
what command were you spamming? Also what database library are you using? It could be possible that you have multiple instances of your bot running so sometimes the other instance responds first so you get the second error
Doing decks or basic_info being spammed caused the issue, and it's using postgres.
But since that you mentioned multiple instances, I checked and that was the problem. I've been stopping and running it so I didn't think of it being a problem. I checked processes running and there were multiple others running. Thank you for the help!
🎉
The reason I suspected that is because the new commands would only be on one instance not all so they would not have the same problem
?
Permissions names of what? The missing permissions?
yes
You can add a global check with https://docs.pycord.dev/en/stable/api/clients.html#discord.Bot.add_check you can use bot_has_permissions.predicate (I think this is how you do it) as the function. Then set up a global error handler to catch it. The error object has a list of permissions you are missing
Whenever i send a modal it raises an error saying the interaction has already been responded, but i have modal sends in other commands and they work fine, is there any reason causing this issue?
Also, are there timeouts for modals? if not, how can I handle timeouts to prevent memory leaks?
Modals do have timeouts you can pass them to the constructor. Modals need to be the response to an interaction not a followup. This means you cannot defer before sending a modal
@eternal kite pong
i know, i have the exact same code in two different commands and one of them just keep saying the interaction has been responded before
Can you share your code
the code doesnt work even if it's a single ctx.interaction.response.send_modal without any other stuff
so i spent a few hours debugging, and it turns out that newly registered commands are unable to send modals
see the code would really help us locate the issue
that's strange asf
well i cannot reproduce that
that's the scariest thing a developer can read
why are you using the import and not putting it directly inside the command ?
cuz it's cleaner
alr so i'll provide more clues so we can come up with a hypothesis with this weird bug
are you saying that the modal is not sent at all
because you are in fact answer 2 times to the interaction
inside the fonction that you import and inside the callback of the modal (im not sure about that idk if the interaction is renew or not)
so i have another command which also sends a modal when a user uses it, so in this code i replace the import slash function call from learn to faction_create, and i use the /learn command it works perfectly fine
i did comment it out and it didnt work
in fact, i also used the exact same modal from the learn command
in the faction create command
and it didnt work as well
if inside ur callback hre for the modal you just have a return and nothing else
do it still raise an error already response
i already tried commenting out the whole callback and it didn't work
are you also sure you dont have any group check or all which can lead to an interaction behing already answer
group check?
nah i dont think so
never knew group checks are a thing
only know bot checks
what you could do to debug is to print ctx.interaction.response.is_done() and so you can then check before the thing if its alrady done or not
like one time before the import and then inside the faction create
good approach, haven't tried that yet
i dont think there is an is_done method
there is
use typehint
and you will see it
no i've done it it raised an error
i checked the docs as well
Application Command raised an exception: AttributeError: 'Interaction' object has no attribute 'is_done'
it's interaction.response.is_done()
oh
reading the docs helps
yall need to add a reference link
soooo i've done it and it seems like the interaction has already been responded before i even call the faction_create function
Models are classes that are received from Discord and are not meant to be created by the user of the library. Attributes key, url. Methods def is_animated, async read, def replace, async save, def ...
i found this after
what i mentioned is the response didn't link to the interactionresponse
yea, happens sometimes
im puzzled rn
You definitely have some function on your bot that's deferring every interaction
Do you use the event on_interaction at your bot?
i have another command that sends modal as well but it works fine
definitely not
yeah it still returns True
soo.. i actually have another similar command that sends modal, and it works just fine, when I change the function call to faction_create, it works fine as well
i've also tried removing the slash command group and used slash_command instead, still didn't work
OKAY i think i found the issue 💀
i definitely do and idk why i have it since 2023
Hey at least you found it
Deferring everything sounds good on paper but it's not practical
Why is bot throwing this error on every autocomplete? Also the autocomplete isn't working...
(Using master branch)
I don't think we fully support 3.13 yet
yes a bot check and deferring all interactions
i think i know why i added the check literally 2 years ago lol
now that i've removed it and half of the commands aren't working
Same happens for 3.12 too
Mmm last I checked there's nothing wrong with it on master but I can't test
is it a package error, or issue from my side?
As far as I can tell from testing just now, there's no issue with the library
"Future attached to a different loop" idk what you've done on your end
@wheat tiger do you pass a custom event loop to your bot's init?
Are there still issues with Python 3.12?
Ig there maybe the issue
check this
await DB().init() does this
its forever beyond me how people overcomplicate cog loading (which can be 1 line) so hard
Just fancy terminal outputs ✨
idk about your bot but for me, loading 6 cogs takes 1 second
which DB did you use?
Tortoise ORM, Supabase (postgres ovsly)
but if you really want easy progress bars in the terminals, look into tqdm, its stupid easy
@torn barn?
These are the logs
Can you try it with python 3.11?
lemme do rq
3.11 started throwing error on start itself 💀
does ur cog actually takes time to load cog for the progress bar looks nice ?
hmm yes
looks good i have to say
this is mine, a bit more flachy
@torn barn Hmm Ig I found the fix but dk why it works, without initializing db and using client.run() works.
this was before
But doing this makes db unusable..
@fresh sierra How du use tortoise orm and start ur bot?
like so :
async def main():
try:
await init()
await bot.start(BOT_TOKEN)
finally:
await shutdown()
if not bot.is_closed():
await bot.close()
def run():
bot.loop.run_until_complete(main())
if __name__ == "__main__":
run()
Fixed my prob 🤩
asyncio.run() was the evil
yep cos its blocking
Why didn't u reply it before then? 💀
do you use an outside lib for the animation and all ?
it would've fixed my issue
i didnt know you had an issue lmao
nor u were asyncio.run
Uh Rich
I used that a lot for my Stuff
Its pretty easy to use
it might replace my pystyle
not a huge fan of this anymore
Made some stuffs from it, consider checking it out!
which proj?
for ur bot
im currently using poetry
should i change in ur opinon
and if yes why
yea sure, uv better than poetry imo
uv is actually fast tbh
much faster than poetry
also u should consider using it to manage py version (over pyenv) [if u don't use it on arm based machines]
it the usage the same or i will have to setup more thing
rn i just have my poetry and a venv, and i do like poetry run bot, poetry install lock etc
show the outdated etc
nothing more, mostly both use pyproject.toml and their .lock files
only the format differ
uv prioritizes PEP style (uses hatchling as backend) while poetry has it's own backend
ok thanks
gonna check that maybe tomorrow after exams
what does ur shutdown func do?
Close all connection to the db
with autocomplete in slash commands, does discord do their own filtering of results or something
if i type nothing i get the options
if i type something, even though i can see that OptionChoices are being returned, it shows no results
because the result doesn't start with what i've typed but i still want to return it
Did you use autocomplete or choices?
For what?
i have a list of things that have both names and IDS and i want to be searchable with both
but it only works with names
im guessing because discord is filtering out the optoins that don't start with the name
So, choices got a limit of 25 Items which dont update without a bot restart. Autocomplete does not have any limit and can always be updated
i'm just returning 1 thing at the minute
like theres just 1 thing in the list
but i just want it to return things that don't start with what the user has typed
From where did you got the information?
its just a list of [name, id]
it works if i type nothing or the name just not if i type the id
even though i can see optionchoice being returned
then just return that, lol
its fully up to you what you return to autocomplete inputs
And no, Discord doesn't filter autocomplete results, it doesnt have to start with what you are typing in the search box, it can be literally whatever
yeah that's what i hoped so something else is going on
why else would discord not show the optionchoice that i am returning
show your code, show the input you are doing in discord
async def card_searcher(ctx):
card_list = [["name", "id"]]
opts = []
for x in card_list:
if x[0].startswith(ctx.value.lower()) or x[1].startswith(ctx.value.lower()):
opts.append(discord.OptionChoice(name=f"{x[0]} ({x[1]})", value=x[1]))
print(opts)
return opts```
all 3 times it prints an OptionChoice object
and how do you pass the autocomplete to the option
@discord.option("card", autocomplete=discord.utils.basic_autocomplete(card_searcher), required=False)
yea, guess what basic_autocomplete does
oh yeah i copied it from the example thats why
whats the type of autocomplete that doesnt od that then
np
import os
import dotenv
from discord.ext import commands
dotenv.load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
bot = commands.Bot()
@bot.command(description="Sends the bot's latency.") # this decorator makes a slash command
async def ping(ctx): # a slash command will be created with the name "ping"
await ctx.respond(f"Pong! Latency is {bot.latency}")
@bot.event
async def on_ready():
print(f"Logged in as {bot.user} (ID: {bot.user.id})")
await bot.sync_commands()
print('Bot is ready')
bot.run(TOKEN)```
i am way too sleepy/stupid for this
issue: slash commands not showing
even if i have a mutual server with the bot
You're using commands.Bot, you should use discord.Bot for slash commands only
And you don't use sync_commands in on_ready
The library already syncs commands in a separate event
You don't have to do it yourself
.tag client
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
bridge.Bot # above + bridge commands (application commands and text commands in one)
Im way to slow to write stuff at my phone.. xd
Am on mobile too lolz
thanks
now it only shows in servers, im tryna make it work w/ user apps
my bad for not specifying
You have to set contexts and integration types for user apps
aight bet
thx for putting up with stupid people's bullshit, appreciate people like you
When will the new components be added?
Can't remember if you have asked before but they are available in the PR. Which I think is done so hopefully it gets merged and released soon. /Tag cv2 for more info
Components V2 are under development in pycord and aren't yet included in the official releases on PyPI or the master GitHub branch. However, you can access the features now by installing directly from the pull request #2707. To do this, use the following command: pip install git+https://github.com/Pycord-Development/pycord.git@refs/pull/2707/head Please be aware that this is a development version and may contain bugs, feel free to report them by adding a comment to the pull request.
bot, howto, application_commands, embed, a, orjson, vps
@fresh sierra
Have u every used docker to run ur bot?
(Which uses tortoise-orm and connects to DB)
When I run bot locally it run as expected
but inside docker container it throws this error (while trying to connect to postgresql DB)
[Errno 101] Network is unreachable
If I remove the connection to DB code, bot starts
Never
Does ur db accept from all connection or only local host ?
Using supabase
afaik it accepts from all connection
@fresh sierra This works
2nd one
my vm was using ipv4
but why it wasn't a prob in localhost??
How is ur db not ipv4 compatible v
supabase ¯_(ツ)_/¯
transaction pooler works
Im using Maria db and pretty nice
not direct conn
only ipv6 is wild
strange
but
direct connection works as expected in nodejs
drizzle orm
but issues in asyncpg, tortoise orm
no issues in docker only
running directly like uv run main.py works
also sad that uv doesnt support script
they will add that
any fix for the issue?
@wheat tiger
name: square
services:
bot:
build: .
container_name: "square"
restart: unless-stopped
u using supabase or sms ?
supa
FROM ghcr.io/astral-sh/uv:python3.13-bookworm
WORKDIR /square
COPY . .
RUN uv sync --locked --no-dev
CMD ["uv", "run", "main.py"]
how do you run your db ?
cuz your bot aint on the same network
probably thats the problem
But it works when I do locally
that's not my point
Check this proj
where are you running your database
like
launching the postgres thing
not in python
Supabase?
not self hosted
ts
On my local machine all works
yeah no I got that
pooler one only works in supabase, direct one won't
But that's not the issue in local machine
and wha about the "Session pooler" one
lemme check
works
cool
also in docker only
you're a discord bot
wut
But this is what direct connection says
Isnt pooled connections needed for async applications anyways?
idk, I have used supabase in nodejs using drizzle orm and gives no issue no matter direct connection or session poller
(both on docker and locally)
But
- Session Pooler
- Transaction pooler
Works on docker, local machine
and - Direct connection
only on local machine not on docker
idk what's the issue in python
because
your pc got an ipv6 and iv4
and your vm just ipv4
there's no issue in python
But in docker that happens on my pc too 🤓
what's your os
fedowa
I think docker has some shit that disables ipv6 too
try doing ts
but 🤓
in nodejs everything works without any issue
is there a reason why you using supabase
isnt supabase just postgres?
or just the ui
yes
yes
I would've said no and used local postgres if I was before 2 yrs
but
after webdev since 2 - 3yrs
mad for ui 💀
it's so much pain in ass doing that rather I will simply use postgresql
- I do self host supabase, it's hella hard but I did it 🎉 and even did it in docker swarm
- If you want a ui for postgres just use nocodb
I wish if there was a good orm like drizzle orm which provides a locally hosted ui no matter what sql, just pnpm run db:studio
PGAdmin 💪 (Pretty sure this does not apply to this situation)
It does but it's ugly
Also isn't it called adminer
True
not unless they changed it recently
Can't be beautiful than this
also for every supported sql flavour
You should try this
Dbeaver is cool
I also like beekeeper studio
But both are apps not webuis
I think this is literally what you want
drizzle works 🤓
But idk if it works
ik many other tools exist
supabase works
but for production
I prefer self host
for testing and all it comes handy fast dev
How bad it can be if u use raw .json file as storage?
Idk I stopped using supa one year ago to go to standalone postgres
Vwry
.tag nojson
JSON is a convenient and easy-to-read data storage protocol that's widely accepted by most programming languages. However, we caution against its use for storing and retrieving data in an asynchronous environment like a Discord bot. Don’t use json!
- It's a file-based data storage, which makes it vulnerable to race conditions
- You'll need to implement your own synchronization primitives to avoid corrupting data
- If you're not careful, you could accidentally wipe your entire JSON file.
Solution? Use a database. Recommended schema are SQLite, PostgreSQL, and MongoDB.
- Async libraries exist on pypi for each of these
sqlite -aiosqlite
postgresql -asyncpg
mongodb -motor - Databases organize your data into tables, and are fast at inserting, retrieving, and removing records
- You can impose uniqueness constraints to ensure against duplication
- The Python libraries enforce synchronization for you
- The query language is intuitive, you can get running with simple queries in just a few hours!
Well
@lapis dock this needs edit to replace motor
If you want to work with json, use MongoDB, its pretty easy to use
pyon when
Imagine I was using it when I was newbie
I used json for 2 years as a DB so
and proj was 4-5yo, all other stuffs were updated but json storage was as it is
last week updated to db 🤓
I used it for 3 yrs
Guys i've been making discord bots for less than 3 years
and I used txt files for like 2 months
and json never actually I went straight from txt to sqlite
tbf it really was key value pairs
and I had like 40 to store
so 40 files with inside of them one value per line
well key-list pair
💀 still never even imagined in my dreams of that shit
will tell to my friends abt this new idea
ship fast and break things they say ?
idk what will be the reaction 💀
"why not txt files?"
oh noooooo
nooooo txt files
noooooo
Anywaysss
physics exam tomorroorw
gtg study
bro gave me an idea which I never needed
i hope
couldnt find that on github, could you provide me the link?
Is there any way I can contrib my bot as a example bot for pycord?
not really a thing
except using #creations to showcase a functionality you made using pycord not really
hmm
is there any way to edit discord.Interaction (to basically set the interaction.user to member (always true in my usecase since my commands and only be triggered in guild)
goal would be to not have to put everytime MyInteraction, but be able to continue to use discord.Interaction
something like
discord.Interaction = MyInteraction
is interaction.user the user object always?
interaction.user is User in dm etc Member in guild
and None when discord is pinging the interaction (but according to nelo we dont have to deal with that its handle at the bse)
so what's the issue at hand
if your command is always in a guild it'll always be a member object
well yes but its not typed has member, so i would like to override that to its typed as it
like this in a way
goal would be to not have to put everytime MyInteraction, but be able to continue to use discord.Interaction
(idk if its even possible)
because having to change every discord.Interaction gonna be tough
I never said to change it
.
.
what do you mean ?
i dont get how to do that if you prefer for i dont have to change the discord.Interaction
just type it as User | Member it's not that big of a deal
do you mean like this ?
async def button_callback(self, interaction: discord.Interaction):
user: cast(discord.Member, interaction.user)
(my goal would be to change it once in a file and then inside my whole workspace interaction.user would appear as member
Not really
I'm just saying leave it as is
you can't really do what you're trying without a custom subclass
were you able to fix this?
if not, what arguments does the original init want?
I was, by editing the library in itself
Items should be typed item[View]
Which was not the case hee
alright
I am testing the pycord.i18n library and as far as I can see it can only do single level traversal without nested dictionaries so I have created a def to add this feature. Do you think this is a good idea or the library already has a def for it? I had also thought of implementing reddis to store the languages, but I don't know if it would be applicable.
thxx for all
the pycord i18n is not really from pycord, so you should ask @cursive swallow for that
Oh, it's true. If I have to spend another forum. Please let me know. Thanks a lot 💗
he should answer to you here, else maybe you will have more chance openning a pr on his github
Doru is not super active because they live in a place that banned discord, unfortunately.
vpn?
They are sometimes on. But their activity did have a noticeable dip after the ban
the vpn always gives me problems
try proton
is it possible to add select option in modal?
No :(
Imagine 
Its sadly still only text input only
is this a discord limitation or a feature that isn't added in pycord?
Discord limitation
Could someone help me with this?
Persistent view error
Traceback (most recent call last):
File "C:\Users\zi\Downloads\ProjectValor-main\ProjectValor-main\venv\lib\site-packages\discord\cog.py", line 796, in _load_from_module_spec
setup(self)
File "C:\Users\zi\Downloads\ProjectValor-main\ProjectValor-main\bot_files\cogs\Giveaway.py", line 110, in setup
bot.add_view(GiveawayView())
File "C:\Users\zi\Downloads\ProjectValor-main\ProjectValor-main\bot_files\cogs\Giveaway.py", line 14, in __init__
super().__init__(timeout=None)
File "C:\Users\zi\Downloads\ProjectValor-main\ProjectValor-main\venv\lib\site-packages\discord\ui\view.py", line 186, in __init__
loop = asyncio.get_running_loop()
RuntimeError: no running event loop
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\zi\Downloads\ProjectValor-main\ProjectValor-main\bot_files\valor.py", line 82, in <module>
client.load_extension(ext)
File "C:\Users\zi\Downloads\ProjectValor-main\ProjectValor-main\venv\lib\site-packages\discord\cog.py", line 918, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Users\zi\Downloads\ProjectValor-main\ProjectValor-main\venv\lib\site-packages\discord\cog.py", line 801, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.errors.ExtensionFailed: Extension 'bot_files.cogs.Giveaway' raised an error: RuntimeError: no running event loop
relevant cog code:-
def setup(bot):
bot.add_cog(Giveaway(bot))
bot.add_view(GiveawayView())
Why did you add the view at the setup of a cog?
you should use add_view after the bot has started - an on_ready listener inside the cog would work
hey guys! weird question, why does accessory required in discord.ui.Section()
like always i mean
That would be a question for discord staff
o
Because that's what a section is
up to
three Button/Thumbnail
TextDisplays
Use a TextDisplay + Separator if you don't want an accessory
The 'content' field cannot be used when using MessageFlags.IS_COMPONENTS_V2 oh wow
hope it was a bug because
ill try that! thanks
Are you using Mullvad? Use Mullvad.
is there a maximum number of commands a bot can have?
?tag cmd-limits
You can have 100 commands, and each command can have up to 25 sub-command groups. Each sub-command group can have up to 25 sub-commands.
100 x 25 x 25 = 62,500
Of course, "slash commands can have a maximum of 8000 characters for combined name, description, and value properties for each command and its subcommands and groups", so you're not likely to hit that 62.5k command limit
This can be doubled again with guild commands. (125,000)
i worry about that question
@wheat tiger how do you do to see outdated lib with uv ?
And to update branch too
Because when I do uv sync it doesn’t update the branch to the last est
The specified component exceeds the maximum width what does it mean? is the label too long?
shorten it and see if it works
That sounds like you are putting to many things in an action row.
You can have 5 buttons OR one select menu currently
Anyone elses bots continually reconnecting to the API resulting in a 429 error?
discord.errors.HTTPException: 429 Too Many Requests (error code: 30034): Max number of daily application command creates has been reached (200)
Are you syncing manually?
No
It syncs automatically when the bot reconnects
So it must be disconnecting and reconnecting repeatedly. But the network is stable..
Can you make sure you don't have multiple instances of the bot running
This should not cause a rate limit as the commands are not new
No idea how the hell I’ve done that but I’ve accidentally used the token twice. Good shout indeed!
Thank you
Thankfully this was my testing bot, so no customers bots have been affected 
Yup the 2 instances must have been fighting over what commands should be registered.
hey guys! is it possible to make paginator with the new ui component like containers? instead of embeds=[]
i feel like it too much work
Probably but you'd have to build your own system
To be clear I meant you'd have to make your own paginator system. But maybe it would work with custom views
You should try and see
uh so.. my bot is starting to become slower due to the large amount of users, is there any action i can take to reduce the amount of lag in the bot?
about 50 commands are used every second
make sure everything is async
limit usage of recursive command
it definitely is
i dont use recursive
but maybe quite a lot of for loops and while loops
but the commands are all async
try to have a vps in the us next to discord
my hosting server is in the us
because a command is async doesnt mean you dont have blocking code
how many ping do you have
opening file, pillow, sync db etc can be blocking
if your bot is open source i can take a look
it's not about my ping, it's other players reporting the issue
can be the ping
db is async, yea i do have pillow and image opening but they are all in async function
if you have 20ping or 300 that will not be the same
this will stilll be blocking
even tho its inside an async function
.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.
you should do like this
so it shows the bot is thinking... then after a few seconds all the sent commands gets loaded at the same time
if everything is blocked for second and then everything is sent its because you have blocking code
i see
which can be pillow according to what you told me
yup for loops with image opening
for image opening you should use aiofiles its async
so how can i create an asynchronous for loops
Maybe run a profiler on your code
it's too complicated to run any profiler
just do like this
but i need a returning value
aiofiles works with pillow?
try this
it will return the value
Opening a file is unrelated and can be done ouzside of pillow
you can open your file async and pass bytes into pillow
and for aiofiles you can use it the same way as normal file just add await
so my code is like
for image in image_list:
img = Image.open(f"{image}.png")
bg.paste(img, pos)
just an example
change that into a function,
def my_image_func(name: str):
img = Image.open(f"{image}.png")
bg.paste(img, pos)
for image in image_list:
return_value = await bot.loop.run_in_executor(None, my_image_func, 'image')
forexample
will there be any downside if i have too much tasks running in the executor?
nope
it prevents memory leak right?
it prevent blocking code by running it inside a separate threads
alr so instead of running it in an executor, what if i just make the whole function async
pillow cant be async
so you will have to use rie
putting code inside an async function doesnt make it async
saved me a bunch of time reading docs 
The components V2 PR does allow custom views with cv2 components.
Hi, I have just upgraded to Python 3.13 and now Pycord raises an error every time I try to run my bot. Should I revert my venv to 3.12? When will 3.13 be supported?
Not sure if 2.7 will fully support 3.13 but the core problem can be solved by...
Pycord 2.6.1 may work with Python 3.13, but it is not officially supported and can cause various issues. Until Pycord 2.7 includes official support for Python 3.13, it is recommended to use a previous version.
For voice features in Pycord versions before 2.7, you might need to run pip install audioop-lts. Some users have reported issues with voice features when using Python 3.13, so ensure that you clear the __pycache__ and .pyc files before running your bot.
Would be genuinely sad if it didn't
Especially because it only affects voice, which I'll take a wild guess the vast majority of people never use
I'm not using voice features and get an error.
I never said you do
Yeah, you can also use master to fix that issue
However, I've noticed that the error does not occur the first time I run the bot, which is explained by the __pycache__ thing.
I'm using Components V2, which is up-to-date with master
The audioop issue is fixed for 2.7 but I don't think anyone has confirmed everything else is compatible with 3.13
2.8??
Mobile typing
ah
I'm using 3.13 on my dev env as well as my server
haven't noticed any issues so far
Huh that is strange
can you send the fork link
anyways it only happens in 3.13
i cant find nelos fork rn
Components V2 are under development in pycord and aren't yet included in the official releases on PyPI or the master GitHub branch. However, you can access the features now by installing directly from the pull request #2707. To do this, use the following command: pip install git+https://github.com/Pycord-Development/pycord.git@refs/pull/2707/head Please be aware that this is a development version and may contain bugs, feel free to report them by adding a comment to the pull request.
Summary
Soon
Edit by Lala:
Temporary reference: https://github.com/Lulalaby/discord-api-docs/blob/comp_v2/docs/interactions/Message_Components.md#v2-components
Yet another edit by Lala:
Offici...
was it fixed less than a week ago? that would explain it.
https://github.com/Pycord-Development/pycord/pull/2176
This is the PR it was fixed in which was merged over a month ago
ok, so maybe I just messed up the cache
lemme retry
I wonder why Python doesn't recreate the Pycache on venv change. Shouldn't that be the whole point of virtual environments? Keeping installations separate?
the point of venvs is to have a set of packages specifically for one project
Anyways now it works, thanks for your advice!
np
quick question! does topgg still works with py-cord? or does their sdk even working
You might have to use the master branch so that it does not automatically install discord.py I assume it would still work tho
That is probably a better question for them
ok thank you!
Their library is garbage just do it manually
didnt they have some issue some time ago?
does it even work without aiohttp... 🤔
what does that even mean
i mean
?
if you mean https://github.com/Top-gg-Community/python-sdk, you can try it but it hasn't been updated in 4 years so there's a chance it breaks
and we can't really help much
you could just use their api directly by referencing their docs https://docs.top.gg/docs/API/@reference
Basics of the API
legit find it silly af that a simple website like topgg needs a wholeass SDK
especially since their API isnt all that big
from what i can tell only their rust lib is official, the rest are community efforts
so they stop maintaining their python-sdk...
(we can see how that ended up)
they have 2 endpoints and like 20 possible requests
there is no fucking need for an SDK and libraries in 50000 languages
well yeah but people will make them regardless

all in all their lib doesn't look all that complicated so just do it manually with aiohttp and you'll get by
yea i heavily agree, their API is stupid simple
oh i think they also have an event implementation for listening to vote events
ok, ill try messing around with it for abit to see! thanks
allgood
not documented = doesn't exist
:3
nah it's documented https://topggpy.readthedocs.io/en/stable/webhooks.html#examples
oh its there
btw, i'm still confused. which lib should I use, the one you sent (python-sdk), or do it manually?
just do it manually
kk!
hi guys its working with aiohttp! thanks alot :DD
allgood
Why is my code always being underlined here? It tells me it's probably because of pylance... Which packages do I need in Visual Studio Code to work with Python and program bots?
I have installed these:
- isort
- Pylance
- Python
- Python Debugger
Feel free to ignore it
because that syntax is semi abusing how python works
the proper way, imo, is to use the decorator
also, required=True is the default, you dont need to pass it
Yes, but it's annoying that it shows up as some kind of correction for every file.
okay, thanks for the info
Well someone here was trying to use it and together we found out that a maintainer for a different top.gg repo had perms for they python repo. They got hacked and someone committed malware to the master branch. Went unnoticed for at least a few days until we brought it up.
ah yea that
Sorry again for asking, but how can I change this so that it no longer displays this for every file?
use the decorator
but you dont have to pass the type if its str, and you can just pass it positionally, no need for type=
otherwise its all the same kwargs
.rtfm discord.option
Lowercase
sending modal keeps raising unknown interaction error for specific users?
im pretty sure it's discord's issue tho
it works for some users and not for the others
Are you always responding to the interaction the correct way?
Do you have blocking code?
.tag paste
i just fixed all the blocking code in my bot yesterday
this unknown interaction persisted for nearly a month
yup, ctx.interaction.response.send_modal
You can use ctx.send_modal as a shortcut, but weird
hmm
i think it has to do with the bot.check
I'll debug it when im home
but what exactly triggers the error?
unknown interaction
Not responding within 3 seconds
responding after 3 seconds
Which means the interaction token is invalidated
That could be it if it's not returning truthy fast enough for specific users
has anything changed in regards to bots and thread channels?
i host a middleman bot, and we primarily use threads over channels, mostly so that we don’t see all the channels and they’re hidden in their own little category.
recently the bot just stopped being able to make any threads whatsoever
i haven’t been home to be able to check any error logs, i tried remotely using termius but pm2 was showing no activity in its list, and it was already hard to manoeuvre the actual remote pc off my phone, the bot other than threads works just fine, all commands work no issues there
when running the bot, to create the thread you click a button, the bot will create the thread but never add the user nor send messages to said thread
not that I know
err just as a sidenote you can hide channels you dont wanna see since quite a long time now
Sorry for late resp, busy
@fresh sierra U can do uv lock -U && uv sync for that
hi so is there a way to show all categorys of a guild in an option for the user aand pass the id of the chosen category
Set the option type to discord.CategoryChannel
how to add a Button() at the right side between the TextDisplay() in cv2?
sry can u help me with that?
error: AttributeError: 'str' object has no attribute 'id'
my code: Option(type = discord.CategoryChannel)
show more of it
remove type=, input type is always first argument
oh ok
the arg is called input_type anyway, can't remember if it's forced pos
a
Use a section
typehint 
thx works
oh ye me figured it out! thanks
Buttons can be accessory yes
ok yeah forced as first arg, can't pass as kwarg
mobile you kinda just have to deal with it, they tried their best
it kinda triggered me but ok, all good!
and if i want to list the role would it be discord.Role?
yep
ok
in this code is there a way to send not the name of the role or user for example but to mention them?
@discord.slash_command(name="test")
async def test(self, ctx, testinput, category = Option(discord.CategoryChannel), role = Option(discord.Role), member = Option(discord.User)):
await ctx.respond(f"{testinput}\n{category}\n{role}\n{member}")
Role and User objects have a .mention attribute
Also god, what's that typehinting

thats okay as long as its possible
