#Basic Pycord Help
1 messages ยท Page 67 of 1
User apps are simply for sending interaction responses, and their ephemeral state depends on where you use them and the permissions.
What you want is to run a bot on an account and receive all events, etc.[Those things that are against the ToS](<https://support.discordapp.com/hc/en-us/articles/115002192352-Automated-user-accounts-self-bots-)
yes im aware that self botting is against tos, im not doing any of it.
i just asked if i could receive an event if a bot message in a dm channel or similar was deleted by the person that used the command
I'm pretty sure they can't delete the bots message but might be wrong
They can delete their own messages
Yes they can when it's an interaction reply
Yes, but that doesn't mean they have the full functionality of a "normal" bot
I don't remember if message delete is sent out dm channel, you can try that but I'm pretty sure it may not be sent.
#1130595287078015027 message
For reference
okay okay
Try also the raw one maybe
thanks
Receiving events by just having users install your app is weird and privacy invasing
Like think about it.. you install a bot to your profile and it can suddenly read your dms etc
The dms with the bot, but all of them
That's not what they're saying tho
They specifically said userapps#1132206148309749830 message
Yeah but it's already something

Where does this imply that the userapp can read your dms?
If the bot has an event if a command was ran, it should have an event if the message of that command was deleted
Receiving events = on_message, on_message_delete = events
Why would it? What's so special about deleting the command response
That would make it possible for the dev to get the message content from a PRIVATE message
Yea but the bot sent the message in the first place so i dont really know where you get private from here
Doesn't matter. It was sent in a private conversation.
mb then
@ionic wasp would you mind sharing more about your use case ? Maybe we can find an alternative solution
i have a few games with the limitation of 1 active game per user, the game stops being marked as active if it ends or the view times out, id like it to also stop marking it as active if the message was deleted
okay, that's actually a good usecase
Hmm. I wonder if you can fetch a message the bot sent, even if it's in a dm
Is it possible to use a smaller timeout? The timeout resets on interaction ofc, so it would be easier to detect inactivity maybe?
That way when a user creates a new game you can check if the user deleted the message. Only problem would be it could start making lots of requests to the api
Even with that you would still have to painfully wait around for it to timeout if the message was deleted
And gets annoying if the opposing player doesnt instantly respond to it, or vice versa
Ah true
Yea i generally want to avoid doing many requests, thats why i asked for a event
Another option could be to tell the user that they already have a game ongoing, and send the info again. And or have a command/button to end the game.
True i could add a button to the "you already have an active game" message that ends the previous game
It not be possible to resend the ongoing game?
Or I guess the user could just delete that again and again lol
Thats also possible, but that would require a ton more internal code and changes
thanks regardless, ill find a good solution
Ah 
turned out to be an issue with mongodb
for some reason my userid stored as a collection in mongo keeps on rounding
maybe its cuz when I open it in vscode it converts to json?
Is it maybe because of 32 vs 64 bit ?
Yeah
Make sure the data type is a Long https://www.mongodb.com/docs/mongodb-shell/reference/data-types/
Discord snowflakes are 64 bit integers
you can also just store it as string
I think that's it I'll test it out
does json require this as well, or is it to do with the fact it's stored as a bson?
Json rounds too when stored as int iirc
yes
Is it possible to add a persistent view with parameters
only if you save those to a db
You get to initialize the view when you add it with add_view()
So you can accept custom args to the init. Like toothy said you would have to save the parameters somewhere so that you could fetch them when your bot restarts
I used the Int64() function but it didn't work
await studentdata.insert_one({"name": self.fullname, "email": self.email, "discord_id": Int64(interaction.user.id)})
Make sure the column is of the correct type/length as well
what do you mean by that
Oh you are using mongo, It might have a different structure than I am used to.
But it changed my value and roundd it
oh nvm i store mine as strings 
but i did used to send just the int
and it automatically converted
yea you should store it as string
how do i limit commands to a specific guild / channelid?
for guild, set a list of guild_ids in your command decorator
for channel... either filter by ctx.channel.id in the command, or if you're an admin in the guild you can set permissions in settings -> integrations
thanks
if anyone has the same problem in future, mongodb doesn't actually round the value automatically, it handles it
but when viewing it in vscode, it opened up as a json and misrepresented it even though the actual value stored was unchanged
Wow, that's not hard to debug at all (joke ๐คฃ)
Tf
VSC cursed
How do you get the jump_url of the response of an application command
response = await ctx.respond(...)
response.message.jump_url
can dc bots have different pfps in different servers or is that ridiculous?
is it intentional for pages.Paginator(pages=pageGroups) to error without show_menu=True
no, they cant
error how
if sum(pg.default is True for pg in self.page_groups) > 1:
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: 'NoneType' object is not iterable
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: 'NoneType' object is not iterable```
sorry if this is a noob question but i cant find anything on the docs
when loading a cog is it possible to reference a class in that cog? something like this:
main file ```py
bot.load_extension('cogs.views')
...
@bot.slash_command(name="hello", description="test")
async def button(ctx: discord.ApplicationContext):
await ctx.respond("", view=Views.ViewMain(), ephemeral=True) # also tried ViewMain()
**cog "views"** ```py
class Views(commands.Cog):
def __init__(self, bot):
self.bot = bot
class ViewMain(discord.ui.View):
@discord.ui.select(
placeholder = "menu",
min_values = 1,
max_values = 1,
options = [
discord.SelectOption(label = "1", description="test")
]
)
async def select_callback(self, select, interaction):
interaction.response.send_message(...)
print(select.values)
def setup(bot):
bot.add_cog(Views(bot))
i tried sending ViewMain() and Views.ViewMain() with no luck
import it
this is basic python, cogs arent some crazy construct, cogs are just classes
also dont put your views into a cog
serves no purpose, only just saw you did that
@hallow osprey
why
ok
and it makes them harder to import
Really it just makes your code cleaner
That does not look intentional
is it possible to add custom emojis to buttons?
yes, just pass emoji to the button
i mean external emojis
Like server ones? should work
Does your bot have access to the server

okay it works

Someone please tell me why this doesn't work: ```py
Wait for user response
def check(m):
return m.author == ctx.author and m.channel == ctx.channel and m.clean_content.lower() == "yes"
print("waiting for user response")
await self.bot.wait_for("message", check=check)
print("user responded")
I'm very clearly typing yes. If i remove the yes condition it works (with whatever message I send)
Maybe print clean_content in the check to see what you're comparing to
Lmao
Does your bot have access to message contents
ah
im dumb
always intents
that catch me out
intents can be annoying sometimes - it works now thx
sorry if im annoying or something, i suck at coding
what could be wrong here?
Traceback (most recent call last):
File "...\bot.py", line 60, in <module>
class ViewRemote(discord.ui.view):
TypeError: module() takes at most 2 arguments (3 given)
this is the third view btw if that affects in any way
you should post the code in question
yeah but its just a bunch of buttons
i will try anyways
what was the paste service sorry
paste
Please copy and paste your code here. This makes it easier for everyone helping you.
View* btw
capitalize the V
Sorry to come back to this, but I can't get it to work. When I have a command like so:
@bot_group.command(name="reload", description="Reloads cogs", guild_ids=[9621##############])
I can still see it on other servers. Does it matter that it's in a SlashCommandGroup at all? ex:
bot_group = bot.create_group(
name = "bot",
description = "Bot related commands",
integration_types = {discord.IntegrationType.guild_install}
)
I even tried making a subgroup that restricts based on what I saw on the documentation, but this doesn't work at all (people in other servers with no roles can still see it)
dev_subgroup = bot_group.create_subgroup(
name = 'dev',
description = 'Developer commands',
guild_ids = [9621##############],
default_member_permissions = discord.Permissions(permissions = 0, administrator = True)
)
Thank you!
subcommands dont count as individual commands
they inherit everything from the main command
including guild ids
Ohh my god thank you!!
Hey guys noob question - how can i set up a task to run at a specific time (i.e. cron) ? Trying to have something run every 3 days at 12p for example
Concept
I dont think we support the "Every x duration at y time"
oh yea i missed that mb
That should be a fairly simple thing to add I would think.
Allow the user to set next_iteration
I guess you could do something funky with change_interval
Start it with a time
Change the interval to every 3.5 days
When it runs check if it is close to the time if so, change the interval back to the time
(Or allow passing seconds, minutes or hours with time)
Wait the duration then wait until the time?
Yeah
It starts the loop every X duration
And then waits until Y time and runs
And like that continuously
Or maybe other param but 
Yah makes sense
Something like recurrent events on loops would heavily improve them lol
If I have time in the next few days I will look at tasks and see if there are some more features I can add.
I was also noticing that there is no way to have it wait until X to start the loop.
Maybe using dateutil.rrule could help on tasks
Like, it would allow more flexibility on options for how they work
Plus it wouldnot make the code harder to read
This worked beautifully btw
Is there any graceful way to have different commands from the same group have different visibility, e.g. /mod kick only seen by people with kick_members permission, but /mod ban with ban_members?
no
No, discord did not entirely think subcommands through
Okay thank you!!
sorry guys i didnt follow these suggestions... are we saying its not supported or can be done with work around?
What is the proper way to be passing a time object?
@tasks.loop(time=datetime.time(hour=12, minute=0, second=0))
doesnt seem to like this
discord.ext.tasks.Loop
discord.ext.tasks.Loop.__call__
discord.ext.tasks.Loop.add_exception_type
discord.ext.tasks.Loop.after_loop
discord.ext.tasks.Loop.before_loop
discord.ext.tasks.Loop.cancel
discord.ext.tasks.Loop.change_interval
discord.ext.tasks.Loop.clear_exception_types
discord.ext.tasks.Loop.current_loop
discord.ext.tasks.Loop.error
discord.ext.tasks.Loop.failed
discord.ext.tasks.Loop.get_task
discord.ext.tasks.Loop.hours
discord.ext.tasks.Loop.is_being_cancelled
discord.ext.tasks.Loop.is_running
Can you elaborate on that is not working? Also make sure you are thinking about timezones. (Just use UTC to make things easier)
This seems right to me
from datetime import UTC fyi
Traceback (most recent call last):
File "/Users/ethan/PythonProjects/EliteSweeps/main.py", line 21, in <module>
bot.load_extension(f"cogs.{cog}")
File "/Users/ethan/PythonProjects/EliteSweeps/venv/lib/python3.12/site-packages/discord/cog.py", line 918, in load_extension
self._load_from_module_spec(spec, name)
File "/Users/ethan/PythonProjects/EliteSweeps/venv/lib/python3.12/site-packages/discord/cog.py", line 787, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.errors.ExtensionFailed: Extension 'cogs.casino' raised an error: TypeError: unbound method datetime.time() needs an argument
how do you import datetime ?
from datetime import datetime, timezone, timedelta
You need to use datetime.time, with that import I think you are using datetime.datetime.time
yes
from datetime import time
np
I use datetime.datetime.datetime.datetime.time
you can pass it directly without wrapping it in a time object
p sure
literally every project i do i feel like this
datetime.timedate.date.dimeddate.datedtime.dt.tdate.time
how can you remove attachment from bot response
pass files=[] to the edit
how do i sleep after sending an interaction response message
sleep how
time sleep
just asyncio.sleep
"doesnt work" gives no info about your actual problem
users: list[discord.Member]
there's no way to get a list of users on the command? a select or something? this is giving me error. I checked on the on the docs about the discord.Option and there's only discord.Member as a type visible. A discord limitation or am i missing something?
Options cannot accept multiple things, discord limitation
Some solutions
- Use a user select menu
- Create an autocomplete function that you can use
,as a seperator between user names - Create multiple options
How can I import a cog method like send_death_message to another module?
I've tried importing the MoneyGame cog class entirely but the import failed
don't import, use bot.get_cog to get the active instance
e.g. ```py
cog = self.bot.get_cog(COG_CLASS_NAME)
await cog.some_cog_function(...)
(you can also do this to directly run commands in other cogs)
Thanks ๐
Is there any way to get list of active events on server? I want to let admins (or automatic) set boosts (for exp and etc.) during some events
no idea
thank you!
Is there a subgroup before invoke ?
Like there is in prefix command ?
(bump)
wah?
Add audioop-lts; python_version >= "3.13" to your requirements.txt file
.tag audiooop
Tag not found.
Did you mean...
audioop
audioop-lts
.tag audioop-lts
Pycord 2.6.1 may work with Python 3.13, however it is not officially supported currently and can cause various issues. Until it is supported, it is recommended to use a previous version.
You might need to run pip install audioop-lts for voice features until Pycord 2.7 includes a Python-based audioop implementation.
oh ty
ah wait, how do you set up slash commands to work as a member app rather than a guild app?
you mean a user app ?
ya
Here's the slash users example.
ty
@bot.slash_command(integration_types={discord.IntegrationType.user_install}, name="ping", description="ping the bot!")
async def ping(ctx: discord.ApplicationContext):
await ctx.respond("๐ Pong!")
@bot.slash_command(
integration_types={discord.IntegrationType.user_install},
)
async def greet(ctx: discord.ApplicationContext, user: discord.User):
await ctx.respond(f"Hello, {user}!")
I've got both of these, and none of them seem to even show up?
.tag slashnoshow
Application Commands Not Showing Up?
- Refresh Discord by restarting or pressing
Ctrl+R(orCommand โ + R) - Uninstall libraries that conflict with the
discordnamespace (e.g.discord.py). - Invite your bot with the
application.commandsscope. - Load cogs before
bot.run()(e.g. not inon_ready). - Do not override
on_connect. - Update to the newest version of
py-cord(see?tag install). - Turn off
User Settings > Accessibility > Chat Input > Use legacy chat input. - Share your code and errors.
oh shit right I forgot about the application.commands scope
thank you
I haven't done this for over a year, apologies
is your bot purely a user bot
np lmk if anything
also you should typehint your user var as discord.Member
Hi, how do you get the message author in this case?
@discord.slash_command()
async def shop(self, ctx):
'''Buy some items.'''
user = MoneyUser(ctx.user.id)
view = ShopView()
view.message = await ctx.respond(embed=ShopEmbed(user), view=view)
ShopView()
class ShopView(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
self.sender = self.message.author
self.user = MoneyUser(self.sender.id) # not to be confused with discord.User!!
AttributeError: 'NoneType' object has no attribute 'author'
you can pass it into the view
with ctx.author
Yeah but the message returns None since ctx.respond returns an Interaction
can't, I'm making that a persistent view so I can't pass any parameters
Persistent views only work for a single message?
No
Still confused on how persistent views work
that was a C+V directly from an example
Would you mind sharing what example ?
I wanna make a small debug command with a few choices,
@bot.slash_command(integration_types={discord.IntegrationType.user_install}, name="debug", description="various debug things")
@discord.option("Debug Option", type=str)
async def debug(ctx: discord.ApplicationContext, choice: type):
if type == "text file test":
textfile = "debug.txt"
with open(textfile, "r") as file:
filecontent = file.read()
ctx.respond(f"{filecontent}")
else:
ctx.respond("oops")
this is what I got so far, and I don't know how to make the selector, any help?
You can pass choices: list[str] to option
thy
huh?
discord.Option
discord.Option.autocomplete
discord.Option.channel_types
discord.Option.choices
discord.Option.default
discord.Option.description
discord.Option.description_localizations
discord.Option.input_type
discord.Option.max_length
discord.Option.max_value
discord.Option.min_length
discord.Option.min_value
discord.Option.name
discord.Option.name_localizations
discord.Option.required
It's bc of the decorator. You can use discord.option("...", choices=["a", "b", "c"])
No bc user command
It is correct to use discord.User
Because it's with a user command
ah fair
anyhow, I'm still... slightly confused?
oh that's the decorator text nvm I'm stupid
that doesn't show up at all?
(the command does just not the choice thing)
Please show the full command signature
?
.tag slashnoshow
Application Commands Not Showing Up?
- Refresh Discord by restarting or pressing
Ctrl+R(orCommand โ + R) - Uninstall libraries that conflict with the
discordnamespace (e.g.discord.py). - Invite your bot with the
application.commandsscope. - Load cogs before
bot.run()(e.g. not inon_ready). - Do not override
on_connect. - Update to the newest version of
py-cord(see?tag install). - Turn off
User Settings > Accessibility > Chat Input > Use legacy chat input. - Share your code and errors.
try restarting discord after making changes to commands metadata
You have to add it to the command signature too
How else would you access it inside the command
async def ...(ctx, debug_option: str)
then that example is wrong
No. You still get a member object.
Many things aren't filled in, but it's still a member object
The example is correct because of contexts={discord.InteractionContextType.private_channel}
But yeah in that case it was indeed correct to use discord.Member and not discord.User
oh right I forgot to hit ctrl+R on my web app
async def get_animal_types(ctx: discord.AutocompleteContext):
"""
Here we will check if 'ctx.options['animal_type']' is a marine or land animal and return respective option choices
"""
animal_type = ctx.options['animal_type']
if animal_type == 'Marine':
return ['Whale', 'Shark', 'Fish', 'Octopus', 'Turtle']
else: # is land animal
return ['Snake', 'Wolf', 'Lizard', 'Lion', 'Bird']
@bot.slash_command(name="animal")
async def animal_command(
ctx: discord.ApplicationContext,
animal_type: discord.Option(str, choices=['Marine', 'Land']),
animal: discord.Option(str, autocomplete=discord.utils.basic_autocomplete(get_animal_types))
):
await ctx.respond(f'You picked an animal type of `{animal_type}` that led you to pick `{animal}`!')
is this an old example or something? pasting it in to understand the code behind it errors out and doesn't show the slash command at all
Looks fine for me
refresh your client ctrl + r
I did, twice
The discord client?
What are the best useful libraries for Pycord bots? I found for example DiscordUtils (for Tracking Invite and music), but I don't think it's a good idea since it's abandoned. In addition, I would look for something that allows you to make welcome/level images easily.
If you know other librairies that facilitate other tasks, you can tell me too
people usually use PIL/pillow/python image library to create images
TBH there are not really libraries that you would use. If you are looking for premade stuff it would be better to find the codesnipets somewhere (such as github) and copy-paste it into your own code.
Paillat made this https://github.com/nicebots-xyz/botkit
And there is something called ezcord but I am not sure how good it is
God forbid ezcord
Okay thanks !
Okay I would try all this
they are the same thing
how is this replicable, when sending a command with a attachment arg
still need help with this
This is just a VS code thing. It should not effect the actual functionality of your bot.
to ignore those you can put # type: ignore after the line where that warning occurs iirc
or use the decorator version to do options
how do you get autocomplete with a decorator?
same way as with the typehint
they're 95% the exact same
check the docs and you'll see
Hi there!
Am I the only one for whom change_presence no longer works?
The status or the activity?
There's some issue with activities if it hasn't been fixed yet
if you're going to use "whom," use it correctly. "for which" instead of "for whom" would be proper /j
squid no scolding users about grammar in the help channels 
You've been using too much grammarly
grammarly doesn't care for relative pronouns
Pretty sure squid made grammerly with how much they know about grammar
@slash_command()
async def add_reaction(self,ctx:discord.ApplicationContext,emoji: str):
"""test_reaction"""
try:
await ctx.response.defer()
message = await ctx.channel.fetch_message(1302520347651739668)
await message.add_reaction(emoji)
await ctx.respond("done")
except Exception as e:
await ctx.respond(e)
When I use the command for the first time, it can add a reaction. But when I use it the second time, it gets stuck at the add_reaction line and keeps loading. Why does this happen? Did I do something wrong?
You arent responding to the interaction within 3 seconds
You should defer the interaction, which extends this window to 15 minutes.
Speaking from experience, if your command defers the interaction, its probably something with your host's network
Is this a public or private bot?
public, and works perfectly after a restart
maybe it just had a quick lapse in compute resources or smth - its on a quite small vps
Do all of the interactions fail or only a few?
theyre all fine now, i cant make it crash it only happened once in months
Probably just a network blip then.
This shouldnt crash the bot though.
First line in the log
Discord wants to control everything so 
it's just a discord sided error. it doesn't involve the bot at all. so it makes no sense for the bot to intervene in some way
I have a really bad issue reading docs, I learn way better seeing examples
and I don't see an example of a decorator autocomplete?
?
Command Permission Decorators: Commands: Shortcut Decorators: Objects: Attributes full_parent_name, qualified_id, qualified_name. Methods@ after_invoke,@ before_invoke,@ error, def get_cooldown_ret...
all in the guide and docs
just gotta look for it
and you just pass the autocomplete in there just like you already do
wait, so instead I should do
@discord.option("autocomplete hint here", type=discord.AutocompleteContext)
?
Reading docs is definitely a skill. With practice you will get better at it. But it is a important part of development. You should try not to dismiss it as "I dont know how to read docs"
yeah fair, I just... really badly struggle to see how the different things fall together
like autocomplete thing right now is a good example of it lmao
In the example listed above "first" is the name of the argument
no.. what
autocomplete=autocompletefunction()
To convert from typehint to decorator options you just need to copy paste what you had in the Option(...)
And put it in the decorator version. @discord.option(...) and then add the name of the argument as the first argument of the decorator.
oh wait, like this?
ooooooooooh wait, okay I get it now I think?
yea but just pass the type positionally, and just pass str
you really don't need the slashcommandoptiontype stuff it's kinda unnecessary
and no, the first string is the name of the option
Does Pycord already have support for Python 2.13?
I wouldn't hope so
Python 2 is pretty old ;3
:> as for 3.13, not quite but it works if you install audioop-lts
A lol Sorry it was 3
xd
So I'm still at 3.12 for now.
And do you know if there are more problems?
not to my knowledge
just don't use 3.13.1
3.13.0 works, but .1 is just not working with some really weird error
Some people had issues. I didn't try, but in general I avoid being on the last version because some dependencies I need can not work
There are some other minor issues, something with flags for prefix commands
async def debug_options(ctx: discord.AutocompleteContext):
animal_type = ctx.options['debug']
if animal_type == 'Marine':
return ['Whale', 'Shark', 'Fish', 'Octopus', 'Turtle']
else: # is land animal
return ['Snake', 'Wolf', 'Lizard', 'Lion', 'Bird']
@bot.slash_command(integration_types={discord.IntegrationType.user_install}, name="debug", description="various debug things")
@discord.option("pick the debug option", type=str, autocomplete=discord.utils.basic_autocomplete("text file debug"))
async def debug(ctx: discord.ApplicationContext, debug=["text file debug", "no debug"]):
if debug == "text file test":
textfile = "debug.txt"
with open(textfile, "r") as file:
filecontent = file.read()
await ctx.respond(f"{filecontent}")
else:
await ctx.respond("oops")
trying to weave that example function into my code to see how it works, but it just doesn't appear to?
you ignored what I said
the first parameter of the option decorator is the option name, which should match the name of the argument in the function def
and don't do debug=(this) in the function def, just typehint it as str there
Are you planning on adding dynamic options to the command or will you only ever have text file debug and no debug?
I am planning to, yeah
also uh, if you want to limit it to a certain amount - yea what Wolfy said
wait so wdym?
I mean exactly what I said
yeah and what you said means nothing to me rn
what part
wdym by the first argument is a name, what do I do then?
change it to the name of the option
also, what's typehinting
In this example you can see that the arguments for the command are ctx, first, second and the options first arguement is first the argument of the function and the first argument of the option have to match
e.g. debug in your case
that's the other thing I said, but you need to change it in the option decorator
that is part of the solution
so, like this, yes?
No, you are confusing the actual name of the argument with the description
and you can remove the type= before str to pass the type argument positionally, saves you a few characters
?
๐
so now, how to add autocomplete onto this?
you already had it here lol
well
you gotta put your real function there but that's how
if you use the discord utils autocomplete thingy you need to pass the function name of your autocomplete there, NOT as string, and NOT with () after it
it does the matching on its own
if you plan to handle that in your own function it's enough to put your command name in autocomple=, that time WITH ()
might be confusing but if you read it slowly, twice, it'll make sense
I only plan to have a few debug options to test out features myself, and it's just so I don't have to look at code to remember every single one,
also, can you explain what passing the function means?
if you do autocomplete=discord.utils.basic_autocomplete(functionname) the library will automatically only match the values that start with what the user already typed, i think
if you do autocomplete=functionname() all values shown to the user depend on what you return from your autocomplete function
so wait, if I want to do autocomplete=functionname() I can do:
async def debug_options(ctx: discord.AutocompleteContext):
return "option1"
return "option2"
...
?
thats not how python works lol
if you look at the docs, you'll see that it expects either a list of strings, floats or ints, or to be passed a function name directly (never saw that used though)
async def debug_options(ctx: discord.AutocompleteContext):
return ["option1", "option2", "option3"]
instead?
yea
smh toothy 
mrow
still works for me!
that'll be a job for another day probably tbh
unless... hold on
hey guys I'm getting this error many times
Exception occured:
File "/home/luxkatana/pyenv/lib/python3.11/site-packages/discord/client.py", line 443, in _run_event
await coro(*args, **kwargs)
File "/home/luxkatana/cautious-computing-machine/main.py", line 191, in on_ready
mainloop.start()
File "/home/luxkatana/pyenv/lib/python3.11/site-packages/discord/ext/tasks/__init__.py", line 327, in start
raise RuntimeError("Task is already launched and is not completed.")
RuntimeError: Task is already launched and is not completed.
while running my bot for a long time
mainloop is a task
on_ready can fire multiple times
You should add a check or add a once listener instead of using the event
once listener?
.rtfm listener
discord.StageChannel.listeners
discord.Bot.add_listener
discord.Bot.remove_listener
discord.Cog.get_listeners
discord.Cog.listener
discord.AutoShardedBot.add_listener
discord.AutoShardedBot.remove_listener
discord.ext.bridge.Bot.add_listener
discord.ext.bridge.Bot.remove_listener
discord.ext.commands.Bot.add_listener
discord.ext.commands.Bot.remove_listener
discord.ext.commands.Cog.get_listeners
discord.ext.commands.Cog.listener
discord.ext.bridge.AutoShardedBot.add_listener
discord.ext.bridge.AutoShardedBot.remove_listener
discord.ext.commands.AutoShardedBot.add_listener
discord.ext.commands.AutoShardedBot.remove_listener
You can add in a cog
just a simple cog with one listener?
@commands.Cog.listener(once=True)
async def on_ready(self):
await mainloop.start()
Or if you don't wanna waste time just to make a cog for a listener
Just add a check
why does on_ready get then triggered many times?
This library implements reconnection logic and thus will end up calling this event whenever a RESUME request fails.
if i just create one cog with only that listener would that be fine?
honestly just create a boolean and change it to true if on ready already ran, and then only start the task in on ready if that var is false
so if "some" flag attribute doesn't exist on the bot object, then I should define the flag attribute?
i think just putting it in your main file should work fine
oh globally
thats not global tho
(why people just dont use cogs in general is still beyond me but oh well)
because my project only consists of a main loop
and maybe one or two slash commands :p
Why did you overcomplicate it lol
var = False
on_ready
if not var:
start task
var = true
yeah ill just add a globally one
fired = False
@bot.event
async def on_ready():
if not fired:
await mainloop.start()
fired = True
toothy still at being a goat
since when does main.loop() have to be awaited
oh alright
that explains but thanks guys
!!
too lazy to write a commit message
brh
this is kinda stupid and i can prolly answer this question by just double checking the docs but... how do i make an optional text thingie as in
use options
Learn all about Slash Commands and how to implement them into your Discord Bot with Pycord!
and i recommend the decorator version
yeah i dont think i used this correctly
well just for my two cents, its a lot more chaotic and messy than decorators
oh well
it shows up as a required option though
oops
look at the docs
yup, found it, thank you
use_default_buttons=False, custom_buttons=[], show_disabled=False fail to hide default buttons on default pagegroup
how to get application emojis
they are not supported yet
It is on master!
Wen 2.7

hey guys, how do i place a channel at a specific index inside of a category like
cat
- channel 1
- channel 2
- channel 3
and i want to place a new channel, channel 4 at where channel 1 is
everytime i access discord.ApplicationContext.command.id it is not the commands actual ID and I have no idea where the number is being pulled from. what is happening here?
this has been an issue for literally weeks and 5 minutes ago i was legit like "what if somehow the data is wrong in the context?" and it is... for some reason
looking through the docs has led me to be further confused because.. shouldnt it be the correct command ID?
very lost rn
please @ me if you have anything to say
Is this a command group?
no, slash command
i may have figured out where its coming from... but im still very confused on why..
discord>my server>settings>integrations>my bot>commands>copy command id>
: 1013672725501448272
command id in my database: 1013672725501448272
id from ctx : 1333583531024318562
id from cog.command.id : 1333583531024318562
A slash command group?
no, for this example im literally using my help command
no groups
i dont use groups
groups suck
at least rn
this is on the development bot of mine, but it works fine on production
the only difference I can think of now that im really thinking is maybe its because my development bot has the command limited to 3 servers?
is the command ID different if you limit it to a set number of servers?
like
class Help(commands.Cog):
def __init__(self, client : commands.Bot):
self.client = client
@commands.slash_command(
guild_ids = ALL_SERVERS,
name = data.commands.help.name,
description = data.commands.help.description
)
@cooldown(
1,
data.commands.help.cooldown,
BucketType.user
)
async def cb_help(
self,
ctx : discord.ApplicationContext
):
...
print(f"INTERNAL1: {data.commands.help.id()}")
print(f"EXTERNAL1: {ctx.command.id}")
print(f"INTERNAL2: {self.cb_help.id}")
...
def setup(client : commands.Bot):
client.add_cog(Help(client))
when run:
CONSOLE:
INTERNAL1: 1013672725501448272
EXTERNAL1: 1333583531024318562
INTERNAL2: 1333583531024318562
the ALL_SERVERS is a list of IDs for my dev bot and null for the prod bot
it works fine there so im guessing thats the issue
ill see if i can just use these weird new IDs
I believe so, I think each server gets its own command and ID
Ideally you should not be working with the ID because the name of the command needs to be unique anyways and is more reliable.
I dont think it is possible to change the name without changing the ID either so essentially the name is the non-changing ID
well that sucks
ID literally becomes meaningless then
isnt the purpose of ID to IDentify
Yeah, but it sounds like in your case you can just use the command name as the ID. Because that will also identify the command.
Ever since the Discord patch on Feb 3 with the re-written Media Proxy (not sure if this is even related)
My bots been responding very slowly (30sec+) when sending images as files, does anyone know how to fix this?
embed = discord.Embed(title=embed_title, color=appctx.author.color, footer=discord.EmbedFooter(page_range))
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: module 'discord' has no attribute 'EmbedFooter'
what may cause this? running on synology nas container manager, py3.11.4 py-cord 2.6.1, no install any other discord related packages. i can see EmbedFooter at embeds.py on my computer
i've run this code around 1.5 years age, it's no problem at that time
it's fine if i use set_footer, just curious
got it
that's in my computer XD, it's 3.11.4 in container, i know it can't run in 3.13 now, cus of the audioo(somethin like this) problem
EmbedFooter is fine in 3.12.9, another version on my computer, so maybe some problem with contaner's version, but i don't use alpine version
this seems really dumb but uh are you actually able to do this?? (where on_message is registered normally)
for message in messages:
await on_message(message)
?
what are you doing
so im doing some processing in on_message to like update to a db, and im just making a helper function to bulk-process a bunch of messages at once
in case the bot is offlien or smth
i mean sure, try it
if it doesnt work (not sure how listeners work exactly) just put all your on_message code into a seperate function you can then call normally
Why wouldn't it work, It's still a normal python function
for future reference: no it doesn't work
Any errors?
pretty sure its the decorator
nah
All the decorator does it add it to an internal dict and return the function
i'll update you when i fix it
no :3
thats also why you cant directly call slash command functions
the decorator changes the attribute to be a SlashCommand object
We're talking about listeners tho
i doubt its any different for listeners
What would it return?
A Listener object? Commands return the object to allow setting an error handler etc
slash commands could implement __call__ to somewhat keep the original behaviour lol
there's something like that
they do
Ohh, nice!
reloading extensions is not working for me. ill run client.reload_extension after saving a file and.. it wont reflect changes made in the cog file
please @ me
reloading cogs with slash commands isn't really working properly iirc
You will need to sync command after the reloading
wdym

sometimes it works fine but lik 70% of the time im left there like 
await bot.sync_commands
doesnt this.. only do things on discord's side? im talking about, for example, changing the color of a command's embed from red to orange and it not working (unless i restart the bot)
This will update the command
But I understand your thing now so yeah itโs not about discord slash command
Can you pls show the code, itโs gonna help us understand
ima just listen to Toothy and trust that its not working for whatever reason
i was talking about slash commands not properly resyncing
code changes itself should work, although im not sure if unchanged slash commands even load properly again
if you really wanna test this, make a cog that only has a prefix command and try the same thing there
because of my typo so py-cord version in requirements.txt is 2.4.1 lmao, it fixed now
Hello !
why does the user.mutual_guilds do not return all mutual guilds but only some ?
to get the user info, I used get_or_fetch_user method
Cache
It relies on guilds and members cache:
[g for g in bot.guilds if g.get_member(user.id)]
Also it only gets the servers they share with your bot, not you.
Is it possible to use modals without making a class?
Technically yeah, you just have to set m.callback manually
can you please giv4e a short example snippet because when i do that it doesnt close the modal popup and says "Something went wrong." (its from a button btw)
usually you didnt respond to it with await interaction.response.send_message()
Yeah, that sounds like a problem with your code. Can you show what you tried
Is the new monetization by Discord still only required in US ?
supported* yes
I think maybe UK too but nowhere else afaik
ooh what is the differences ?
oh wait
no they just worded it dumbly
bruh
also I think for some reason bot monetisation is different to server monetisation regarding which countries it works in
that is confusing ๐
for the link I found it here
But is it safe to assume if my country is not there that I donโt have to do it ?
why would you have to do anything lol
otherwise they terminate my app ahahaha
because you have premium stuff already?
I just needed to verify on stripe and send valid gouvernement id to stripe
Yeah I have premium, but not throught discord
yeah the fees are now 15 % for growth tier instead of 2.9% + 0.3 ahaha
for use the stripe in both ways
instead of having 2 $ fees for lifetime, I will notw have 11 $ ๐
async def modal_callback(interaction):
modal = Modal(title="Enter Your Player's Name")
modal.add_item(InputText(label="Player Name", placeholder="Enter player name", min_length=4, style=InputStyle.singleline))
await interaction.response.send_modal(modal)
await modal.wait()
player_name = modal.children[0].value.strip() # Extract the input text
select.options = get_player_options(player_name)
select.disabled = False
player_embed.description = f"Selected Player: **{player_name}**\nChoose from the list below!"
await interaction.message.edit(embed=player_embed, view=view)
You are not ever responding to the modals interaction. You should move everything after .wait into the modals callback. And then respond to the interaction with an edit message instead of editing the message separately. Then you can remove the modal.wait.
This would be a bit simpler if you just sub classed the modals.
Hi ! I'm working on a realtime transcription of voice calls bot. To reduce latency, I want to start transcribing the audio as soon as possible and not once everything have been saved. I see there is a connect_websocket in the Voice client implementation but there is no documentation. Does anybody knows how it works ? Or maybe any other way than waiting for the callback function of start_recording so I can start the transcription while the audio is being recorded ? Thanks in advance !
Best that I can say is good luck, I know there have been other users that have done (or tried to) in the past.
I might be able to look into a bit more later but no guarantees.
I believe there's something about transcription in #creations
These threads may be of use
https://canary.discord.com/channels/881207955029110855/1136741604783308940
#1251938693950996500 message
#creations message
Nice thanks ! ๐
async def delete_slot_autocomplete(self, ctx: discord.AutocompleteContext):
slotsdb = SlotsDB()
slots_channels = []
for slot in slotsdb.get_all_slots():
channel = slot.get("slot_id")
if channel is not None:
slots_channels.append(discord.utils.get(ctx.interaction.guild.channels, id=channel))
return slots_channels```
ive got this autocomplete, but what input_type should i set for Option, doing discord.TextChannels seems to override the autocomplete, i only want it to show the autocompletes text channels
I change to using a venv, and now im getting this error?
Traceback (most recent call last):
File "/home/stigstille/Bots/BurgyBot/discordBot.py", line 1, in <module>
import discord, pygsheets
File "/home/stigstille/Bots/BurgyBot/burgybot/lib/python3.13/site-packages/discord/__init__.py", line 27, in <module>
from . import abc, opus, sinks, ui, utils
File "/home/stigstille/Bots/BurgyBot/burgybot/lib/python3.13/site-packages/discord/abc.py", line 58, in <module>
from .voice_client import VoiceClient, VoiceProtocol
File "/home/stigstille/Bots/BurgyBot/burgybot/lib/python3.13/site-packages/discord/voice_client.py", line 55, in <module>
from .player import AudioPlayer, AudioSource
File "/home/stigstille/Bots/BurgyBot/burgybot/lib/python3.13/site-packages/discord/player.py", line 29, in <module>
import audioop
ModuleNotFoundError: No module named 'audioop'
i dont even use any VC things
.tag audioop
Pycord 2.6.1 may work with Python 3.13, however it is not officially supported currently and can cause various issues. Until it is supported, it is recommended to use a previous version.
You might need to run pip install audioop-lts for voice features until Pycord 2.7 includes a Python-based audioop implementation.
Auto complete only supports
STRING, INTEGER, NUMBER
On discords side.
is there a Python Library for Top.gg that works with py-cord ? The official one is with discord.py
Huh?
A simple API wrapper for top.gg written in Python. Contribute to Top-gg-Community/python-sdk development by creating an account on GitHub.
It doesn't mention discord.py anywhere
You can simply uninstall d.py or ignore the dependency when using pip install
Weird cause their github repo only shows aiohttp as a req
yeah it is dumb, not everyone uses discord.py
maybe I jsut copy paste the code I want ahaha
I just want to update the server count
๐
not that complicated
I mean you could also just send a raw request by yourself
fwiw you can make any arbitrary request on a bot using bot.http.get_from_cdn(url)
I believe the master branch does not require d.py they just have not released a version.
Yeah it doesn't seem to use anything from dpy or any package other than aiohttp anymore
I just did it manually, when I used to use topgg. Their python sdk sucks
Ooh right! Thank you !
Will probably call the endpoint directly
``AttributeError: 'Bot' object has no attribute 'add_command'. Did you mean: 'all_commands'?
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\pbris\PycharmProjects\PythonProject\zeusbot2.0\main.py", line 13, in <module>
bot.load_extension('cogs.Moderation')
File "C:\Users\pbris\PycharmProjects\PythonProject\zeusbot2.0.venv\Lib\site-packages\discord\cog.py", line 918, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Users\pbris\PycharmProjects\PythonProject\zeusbot2.0.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 'cogs.Moderation' raised an error: AttributeError: 'Bot' object has no attribute 'add_command'`` Could anybody, by chance, lend me some of their knowledge to understand what may be causing this? I can post the code as well but don't want to flood this text channel if it's more complex and needs to be posted in it's own ticket.
can you show the code in your cog
Yes, all of it?
you didnt show the initial error so i can only assume you are using bot.add_command
``class Moderation(commands.Cog):
def init(self, bot):
self.bot = bot
print('added cog')
@commands.command(name='kick', description='Kicks a user from the server.')
async def kick(self, ctx: discord.ApplicationContext, member: discord.Member, reason: str):
await member.kick(reason=reason)
await ctx.respond(f'Kicked {member.name}: {reason}!')
@commands.command(name='ban', description='Bans a user from the server.')
async def ban(self, ctx: discord.ApplicationContext, member: discord.Member, reason: str):
await member.ban(reason=reason)
await ctx.respond(f'Banned {member.name}: {reason}!')
@commands.command(name='unban', description='Unbans a user from the server.')
async def unban(self, ctx: discord.ApplicationContext, member: discord.Member, reason: str):
await member.unban(reason=reason)
await ctx.respond(f'Unbanned {member.name}: {reason}!')
@commands.command(name='timeout', description='Timeout for a user from the server.')
async def timeout(self, ctx: discord.ApplicationContext, member: discord.Member, duration: int, reason: str):
if duration >= 0:
await ctx.respond(f'Please choose a time greater than 0.')
await asyncio.sleep(duration)
duration = timedelta(minutes=duration)
await member.timeout_for(duration)
await ctx.respond(f'{member.name} timed out for {duration} minutes. Reason : {reason}!')
def setup(bot):
bot.add_cog(Moderation(bot))``
what's your pycord version first of all
also can you show the error above this one
2.6.1
Yes! Sorry
Traceback (most recent call last): File "C:\Users\pbris\PycharmProjects\PythonProject\zeusbot2.0\.venv\Lib\site-packages\discord\cog.py", line 796, in _load_from_module_spec setup(self) File "C:\Users\pbris\PycharmProjects\PythonProject\zeusbot2.0\cogs\Moderation.py", line 37, in setup bot.add_cog(Moderation(bot)) File "C:\Users\pbris\PycharmProjects\PythonProject\zeusbot2.0\.venv\Lib\site-packages\discord\cog.py", line 666, in add_cog cog = cog._inject(self) ^^^^^^^^^^^^^^^^^ File "C:\Users\pbris\PycharmProjects\PythonProject\zeusbot2.0\.venv\Lib\site-packages\discord\cog.py", line 574, in _inject raise e File "C:\Users\pbris\PycharmProjects\PythonProject\zeusbot2.0\.venv\Lib\site-packages\discord\cog.py", line 568, in _inject bot.add_command(command) ^^^^^^^^^^^^^^^
uninstall and reinstall pycord
does it work?
Still recieving same error...
The commands all worked prior to moving them to a cog so that's where I am lost
are you using discord.Bot in your bot definition?
Yes
bot = discord.Bot(debug_guilds=[-])
i think commands.command is only prefix
I have a guild just removed for this
?
Referring to the debug_guilds sorry
Ohhh ok thank you! will try this now
You rock man! That did it, thank you so much!
Can I make .utils.get() case insensitive?
is it possible to return something that was written in modal to another view?
like
View A -> button triggers Modal -> user types in modal -> Modal returns to View A
modal = MyModal()
await interaction.response.send_modal(modal)
await modal.wait()
print(modal.children[0].value)
Something like that
The library has helpers to help create component-based UIs. Shortcut decorators: Objects: Attributes children, disable_on_timeout, message, parent, timeout. Methods cls View.from_message, def add_i...
ty, I'll try it
Pls still add a interaction.response.send_message at still
yeah, I did a await interaction.response.defer()
That is not a message
You have to send a message
dang it, I'll add an message to it
Just do a Hidden message
Defer is to extend the time to send a message
Do you mean in the modal callback?
yeah ik, what do you mean with "hidden msg"?
Yea
No but you can use .find
# discord.utils.get(users, name="lol")
discord.utils.find(lambda u: u.name.lower() == "lol", users)
is it possible to have two subcommands with the same name but different command group?
/hello world
/goodbye world
Do you mean like this?
yes
and also /world /hello world
Yes to both.
You just can't have
/hello AND /hello world
but how should i call them manually if both functions have the same name?
What do you mean?
if for some reason i need to call any of the function individually how should i do it
Name the functions different things and do name="buy" in the decorator
what even are you doing inside of the commands lmao
ah thanks
lol different features
game shop and trading market
what even is _import_
it's a python built-in method
yea duh but what does it do
same as typing import slash at the top of your file
why aren't you importing it normally tho
fancy 
ah yes
Thanks for the confirmation. This is what I ended up doing after looking through the code.
Is it possible to listen to audit log event creation ?
Target not found, try again and make sure to check your spelling.
This section outlines the different types of events listened by Client. There are 3 ways to register an event, the first way is through the use of Client.event(). The second way is through subclass...
Anyone have any suggestions on a library to use for the time in a reminder system? I saw a few things from 2023 but I know things change, so it'd be greatly appreciated!:)
python-dateutil for datetime input
time-str for duration/timedelta input
These are ones that I am currently using but I have not done a lot of extensive testing yet. Overall datetime input on discord is hard. 2023 stuff is not that outdated either, no major changes in date formats so no reason to change things that work
Awesome, much appreciated!
I use dateparser.parse for relative time input (e.g. "in 3 hours"), and it of course handles direct datetime input
timefhuman is interesting, too (it handles things like "last Monday" where other libs fail, if you ever need to reference that), but using relative forward time gives a timedelta instead of a datetime instance (Which I just created a GH issue in hopes they'll fix)
still abysmal discord straight up wont release their built-in datetime picker
Yeah, at this point I might prioritize that over modal improvements
Especially because I just realized that they have it built in to both PC and mobile already for event creation
and message search
hi, why there is no guild in user object?
error: role = discord.utils.get(user.guild.roles, id=....) ^^^^^ AttributeError: 'User' object has no attribute 'guild'
async def on_raw_reaction_add(payload: discord.RawReactionActionEvent):
channel = Fake_Pompoki.get_channel(....)
user = Fake_Pompoki.get_user(payload.user_id)
guild = Fake_Pompoki.get_guild(payload.guild_id)
if payload.channel_id == channel.id:
if str(payload.emoji) == ":pmpm_hold_dice:":
role = discord.utils.get(user.guild.roles, id=....)
print(role)```
get_user
You already have the guild, so just use guild.roles or, better yet, guild.get_role(roleid)
But payload.member is also available for reaction add
You dont show enough of the error.
Although if you are on the master branch (dev branch) we removed support for python 3.8, not sure if that is related
My bots are continuing to disconnect and reconnect with Discord, I think they have problems
I'd first check if your vps has conn problems
seems more likely
also, i really wouldnt voluntarily use EOL python versions
User objects are not related to any guild
I'm trying to get a good answer about whether discord.Message.id for any given message is Universally Unique. I've read about "snowflakes" and all that, but according to Discord that's supposed to be a string because the number is too big to put into an int, but in py-cord that value is factually an int. I flat-out don't believe that, in 2025, there aren't more messages in all of Discord than there are possible values in an int!
Apart from that, lots of posts on Reddit and StackOverflow insist that each individual message in every DM and in every Guild/Channel/Thread has that ID number which is allegedly a Universally Unique Identifier in spite of fitting inside a simple int.
So while working on a bot with commands to set up event listeners, I need to ensure that the message ID stored in my database is going to catch the message which was specified from the slash-command. What am I missing here, about uniquely identifying one special message, where my brain wants me to store all of the Guild/Channel/Thread/Message snowflakes and then using that whole chain of IDs to locate the message I'm looking for?
message IDs are unique yes
I dont see why a long number wouldn't fit inside an int though
just one minor thing to keep in mind: if you start a thread from an existing message, the thread will have the same ID as the message
there isn't a universal "int size" really
but generally IDs are often treated as strings because they are long and you dont do math with them
they explain it on docs
Internally, Discord stores IDs as integer snowflakes. When we serialize IDs to JSON, we transform bigints into strings. Given that all Discord IDs are snowflakes, you should always expect a string.
...
Because Snowflake IDs are up to 64 bits in size (e.g. a uint64), they are always returned as strings in the HTTP API to prevent integer overflows in some languages.
Ah, and the int in Python3 is not limited to word-size. I just finally thought to look that part up. Thanks, @errant trout and @sage tendon
allgood
Ackthually, int sizes are indeed universally defined. The only difference is between 32 and 64 bit systems
๐ค
Gezundheit! Python 3's int is unbounded, meaning it can exceed the maximum size of a 64-bit unsigned int.
is it possible to make the bot send a message when its getting off, and on?
off is dificult, on of course
on, ok i know how
off, its dificult but possible, right?
i need to use discord.on_disconnect()?
no because then you are already disconnected lol
with webhooks it would still work
@buoyant eagle
but how i would do it when it turns off, i mean before it turns off
i tried deepseek and chatgpt and they both said on_disconnect but what you said makes more sense
i mean you can do it there, but youll have to do it a different way than just channel.send because you dont have a bot anymore really
so webhhok is the answer?
It would probably be the easiest
ok thanks
Maybe on_disconnect, you could reconnect back to send the message 
I have to assume that you're shutting down in response to a slash-command. If you were hoping to send messages in the event of a fatal error/exception then I don't think there's any recourse. Otherwise, just put your broadcast announcement in the slash-command before the disconnect or shutdown call.
I mean
You could wrap your process with another one
Or have a global catch
Or idk
But pycord should almost never crash entirely
My point is that if the bot is disconnecting for reasons you can't or didn't account for ahead of time, you're boned. If the bot is just going down because you deliberately brought it down for a restart, then all you have to do is add your message broadcast one line ahead of your shutdown call XD
Yeah but that's really only going to happen in exceptional cases
That's what I meant
Fair enough. I just wasn't sure what the context of the disconnect was, so I specified the case where my idea wouldn't work.
Hello, I have a bot that is offline after a certain time, but the script is running. However, I noticed that the processor is being used to the maximum (see image). This has been bothering me for over a year and I still can't figure out where the problem is...can someone help me?
If it helps, here is my requirements.txt:
py-cord==2.6.1
captcha
aiomysql
cryptography
I would appreciate any help! โค๏ธ
how many cores does the VPS have
because with percentages above 100%, it means that the % is relative to a single core being used
e.g. if one core is used to 100% it would show 100%
if 2/4 cores are used to 100% each it would show 200%
and while that is the case i still think constant core usage is still not good lol
what does your bot do?
only one
Well, it's a security bot (antispam, antiraid, captcha verification, mod logs and stuff like that)
that shouldnt be possible given it shows more than 100% cpu usage lolw
how many server is it in
Yeah I'm thinking about the same lmao
cca 700
might be time for a better VPS then if its at its limit lol
do you regularly run some heavier actions tho
That's the thing...it's not ๐ญ
or it shouldn't be
the most demanding thing is probably antiraid (mass channel deletion)
Is it a VPS even? 68.5MB of used space seens suspiciously low
probably just a docker container with pterodactyl
yes
Thats what im thinking
You can have a buffer on ptero
Which is why it goes above 100
I'm not sure if it's bad form to ask a separate question while the last one is still unresolved?
what does it mean?
System admins at your hosting company can set a buffer of 10%, 20% etc for both cpu and ram
Meaning that in reality, instead of 100%, you get 110%, 120% etc
Ahh, got it
On the current topic, I think it's worth mentioning that I run a real hardware debian box with a lAMP stack hosting 5 domains with multiple subdomains each, multiple python versions, firewall, SSH service, MySQL with 8 or 9 schemas and plenty of data each, and that only uses about 259MB of system RAM. So I think if you're running a VPS with a python script and consuming 300+MB of RAM, you're either caching a lot of stuff you shouldn't be or else that display about CPU/RAM/Storage is lying to you.
These things are always hard to debug. You should probably add logging to see what is being run the most
300mb really isnt that much for a discord bot
especially if its in 700 servers
my single server bot already uses 75mb
Fair enough. Just seems insanely high, even with caching like member-intents, when everything that Discord actually transmits is a UTF-8 encoded string.
Is it generally OK for folks to ask another question when there's one currently under discussion? I'm struggling with an issue that I can find nothing about via websearch and Discord search in this channel.
sure
It can't be caused by RAM, because I have 2GB free
If you are worried you can open a thread instead
My point is that I'm not convinced that the little screenshot bit you posted is accurate. I'd bet you a whole winter's worth of snow shoveling that it's your VPS Host displaying the usage for the whole system and not just for your individual VPS Instance.
Is your bot actually slow during times?
I just don't want to get off on the wrong foot with folks here XD
So when my bot is joined to any given Guild, Discord automagically creates a Role specially for that bot. The role's name can be changed and the bot can be added to additional roles, but those additional roles can also be removed. So what I want to be able to do is get a handle directly on that one super-special bot role. I just can't figure out how.
Accuracy isn't important in this case. Normally the CPU is around 0 to 5%
Nope, it works well. It just randomly turns offline.
What do you mean by handle? I believe it is like any other role other than only the bot can have it (and the bot must have it)
Does it come back by itself or do you have to restart it?
Handle is just jargon. I tend to mix and match programming terms because I program in several languages. So when I say "a handle" I just mean that I want to go through the Roles assigned to the bot and somehow identify that one special Role which is created specifically for the bot and which the bot cannot be removed from and which no other users can be added to.
I always have to restart.
did you check the logs
Are you sure something is not crashing the bot (Pycord makes it hard for the bot to crash) or your host is doing something like restarting the ssrver
You can check whether a role is a bot role via https://docs.pycord.dev/en/stable/api/models.html#discord.Role.is_bot_managed
and if a role is bot managed and your bot has it, that has to be your bot's role
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 ...
And
THANK YOU!
Ah toothy was faster ๐
Hey now, I tried to RTFM. I just didn't get out my fine-toothed beard comb and go over all the methods available on all the class instances involved XD
reading the docs involves that kind of stuff :)
Nah, rtfm isn't an insult here it is just the name of the docs command
-# at least most of the time
I know it isn't an insult because you gave me the answer before you posted it. I'm just trying to interact in a jovial manner. Failed again!
Your good, you have been very enjoyable to work with XD
I'm just using the libraries I've stated upper and the bot. Nothing more is running on the server.
did you
Oh sorry
I don't have access to them, but I'll implement logging and see what happens.
you cant see the logs of your own bot?
Or maybe I'll just contact the support
nope...
Exceptions should be visible in the console
Idk
If you can't even see print statements it might be time to switch hosts
How would I log events, commands etc.? I saw some use logging but that one catches every event from the bot
i do my own logging tbfh
Are you hosted on a system where you can SSH into the shell, or are you hosted on a system (like one I have a vague memory of from around 2016, but can't recall the name) which strictly and solely hosts Python scripts?
Im so close to use just a .csv File...
There are different levels. You might want to try the level above debug and see if that is what you want
Thats not how pterodactly works (sadly)
It opens a websocket between your browser and the docker container
So if you arent there to witness the crash, you wont have logs.
(unless you implement it yourself)
Some hosts went around this by forking pterodactyl and adding their own crash detection
It's been a long time since I have used pterodactyl, I assume it is easy to setup file based logging though
Not as a client
You have to modify the egg (the "wrapper" around the docker image)
Which can only be done from the admin side
Hmm, well that is unfortunate
Adding nothing to the earlier conversation, my bot is using 422M
Any way to get py-cord to shut down gracefully when using the run/debug-run buttons and the stop button in PyCharm? I'm seeing a couple of different options other than bot.run (which I use now), but I'm not sure I really need all the overhead of my own event loop. I've tried putting bot.close() immediately after bot.run (and I verified that this code is executing by adding an additional console-out print after close()), so it fires as soon as the blocking method exits, but I still get a bunch of runtime exceptions every time I hit that stop button.
I don't get the runtime exceptions, it usually just hangs for a bit. I just press stop (or CTRL-C, in my prod environment) twice
show
# bot = discord.Bot(intents=intents)
bot.run( DISBOT_APP_TOKEN )
asyncio.run( bot.close() )
print('bot run done')```
```D:\Development\Projects\voidCaster\Discord\Bots\serverHelper\venv\Scripts\python.exe D:\Development\Projects\voidCaster\Discord\Bots\serverHelper\bot.py
We have logged in as DEV - Server Helper Bot
bot run done
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x0000012E295DBF70>
Traceback (most recent call last):
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python39_64\lib\asyncio\proactor_events.py", line 116, in __del__
self.close()
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python39_64\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python39_64\lib\asyncio\base_events.py", line 751, in call_soon
self._check_closed()
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python39_64\lib\asyncio\base_events.py", line 515, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x0000012E295DBF70>
Traceback (most recent call last):
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python39_64\lib\asyncio\proactor_events.py", line 116, in __del__
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python39_64\lib\asyncio\proactor_events.py", line 108, in close
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python39_64\lib\asyncio\base_events.py", line 751, in call_soon
File "C:\Program Files (x86)\Microsoft Visual Studio\Shared\Python39_64\lib\asyncio\base_events.py", line 515, in _check_closed
RuntimeError: Event loop is closed
Process finished with exit code 0```
Same exceptions both with and without bot.close(), also with and without COGs loaded. It's a Win10 system with PyCharm Community.
i mean idk what to say lmao, i dont get those
you are using VISUAL STUDIO FOR PYTHON?
I use Visual Studio for work. Mostly C# and C++. I don't recall if I had to manually select to add in Python, but I don't use VS for anything but C# and C++. Frankly, I don't even use it for that, unless you count compiling with it after writing my code in EditPad XD
SAME WITH PYCHARM FRANKLY
cursed
but yea unless you want those gone you really dont need to do anything
maybe pycharm ignores console output when shutting down except for the final line
oh wait you do use pycharm
Meh. I kind of do want them gone. I've been programming long enough that every time I see Traceback I'm OCD to read it all. Wastes quite a bit of time when I'm tinkering with function signatures and auto-fill features in this particular bot.
why is your python exe in a visual studio folder
The exe is in a venv directory. It's the first line of the Traceback. I don't know why it's falling back to the original installation. Never got into studying the guts of Python execution lifecycle.
You sure it's not an issue with Python on Windows or even with PyCharm Community as opposed to wtf-ever they call their licensed version?
If I had my way I'd be using that sexy SSH-runtime feature to debug in the actual linux environment where the production bot will finally sit, but I can't have my way because I don't have the cheddar for that sweet sweet license.
That's not a thing for me, sadly.
Is it not possible to send a paginator to a channel outside the context of a slashcommand? I tried doing something like this:
await some_channel.send(view=paginator)
but nothing is sent. I added a content="test" to be sure it's not an issue with something else and it happily sends "test" to the channel, still with no paginator. The same paginator works fine when sent with await paginator.respond(ctx.interaction)
your uni doesnt need to do anything you just need to have a uni mail i think
paginator.send allows you to send to a channel other than the one where the command was invoked. Not sure if that helps or not. I think you mean you want to run a timer and send paginators randomly? Or something.
yes, i have a job scheduled that would post the paginator to a channel, without any user interaction involved. So there is no ctx for me to use
paginator.send expects a command invocation context
i thought what i did above might work because the paginator class inherits from discord.ui.View
but alas
Did you try constructing a discord.ApplicationContext from the ground up?
i haven't, i considered it, but figured that would be a very hacky thing to do, so it wasn't the first thing i tried. assuming it's even a reasonable thing to do
loans you his Gerber hatchet. It's great for hacking things!
i mean you send the paginator in response to SOMETHING right?
not in this case
when do you then
i have a scheduler that sleeps in the background and sends it at the scheduled time. no user interaction involved. I just want to have my bot post a leaderboard to a channel every friday at 4pm automatically, without me having to do the command to do it manually
okay but afaik paginators are limited to the invoking user anyway
that's the impression i got, but i don't understand why. Seems unnecessary to limit paginators that way
because it's 99% of their use case lol
you dont want other people interfering with how you navigate a menu
well nothing is stopping you from allowing that in the normal use case
i mean either you write your own custom paginator or you subclass it and change what you need to change
both might be somewhat complex tho
Pretty sure you can change that
change what?
author_check defaults to true
You can set it to false
yea okay but that doesnt fix the whole ctx being required issue lol
yes, and that's how i have it. That's already how my users interact with leaderboards
ahh
Ok, maybe I did not read the whole issue... :3
now i want to avoid having to post the leaderboard every friday at 4 manually
i figured i'd simply automate the invocation of the command, but then i realized paginators only expect a user interaction context or w/e
which seems crazy to me
niche use cases will have problems 
i'm surprised this is even considered niche. surely i can't be the first person that wants to automate the post of a paginator
first one i know of
:>
i mean the first alternative i could think of is just making a message with a "show leaderboard" button that everyone can click on when they want to, and always get the current leaderboard
but i think thats not what you want exactly
Tbh the person who made ext.pages had an abrupt disconnection from the Pycord community. It has been attempted to rework but is hard to do without breaking changes
gotta love the "this was made by one crazy guy who left and now its rendered unmaintainable"
it happens so often
yea that is not ideal. I'm really surprised my idea didn't work. I figured it would work like a view just like any other view. granted i don't know much about views
It should not be to hard to subclass and override the send method as a workaround

