#Basic Pycord Help
1 messages · Page 15 of 1
await bot.change_presence(activity=discord.CustomActivity(name='Custom status'), status=discord.Status.online)
?
You subclassed a paginator or crested your own?
i didn't know there was an option lol..
class PaginationView(discord.ui.View):
So you created your own
rolled my own
We have a buil-in paginator
import pages from discord.ext
And then
paginator = pages.Paginator(pages=[*list of your embeds or whatever you want to paginate])
await paginator.respond(ctx.interaction)```
that simple?
.rtfm pages.Paginator
discord.ext.pages.Paginator
discord.ext.pages.Paginator.add_button
discord.ext.pages.Paginator.add_default_buttons
discord.ext.pages.Paginator.add_item
discord.ext.pages.Paginator.add_menu
discord.ext.pages.Paginator.cancel
discord.ext.pages.Paginator.clear_items
discord.ext.pages.Paginator.disable
discord.ext.pages.Paginator.disable_all_items
discord.ext.pages.Paginator.edit
discord.ext.pages.Paginator.enable_all_items
discord.ext.pages.Paginator.from_message
discord.ext.pages.Paginator.get_item
discord.ext.pages.Paginator.get_page_content
discord.ext.pages.Paginator.get_page_group_content
discord.ext.pages.Paginator.goto_page
discord.ext.pages.Paginator.interaction_check
discord.ext.pages.Paginator.is_dispatching
discord.ext.pages.Paginator.is_finished
discord.ext.pages.Paginator.is_persistent
That simple, yes.
Handles the buttons by itself, you can add author checks, disable on timeout
https://docs.pycord.dev/en/stable/ext/pages/index.html#discord.ext.pages.Paginator has all the info
And https://guide.pycord.dev/extensions/pages/paginator-basics
This module provides an easy pagination system with buttons, page groups, and custom view support. Example usage in a cog: API Reference: Page: Attributes content, custom_view, embeds, files. Metho...
Both should work
(activity=discord.CustomActivity(name="name", status=discord.Status.online))
or
(activity=discord.CustomActivity(name="name"), status=discord.Status.online)
Didn't know customActivity had a status arg
ok so i can only pass a list of embeds or files to pages
hi
What were you looking to paginate?
@discord.slash_command(name="test",guild_ids=[967338546505609247])
async def test(self, ctx: discord.ApplicationContext):
await ctx.respond("hi")
this slash command is not showing up in the menu
its in a cog^^
Are you loading the cog
yes
Where and when
just before the bot token
the token's at the end
this is whtat i imported
the cog's name is "slash"
You're overriding on_connect
hmm?
on_connect is what registers the slash commands
Or delete it, or add await bot.sync_commands()
a dictionary, not a big deal got it workin. except it put everything on one page
it's showing all the commands two times
after i added that
refresh discord with ctrl + r at the desktop version
it did not work
yes
why...
remove the on_connect stuff and the bot.sync commands stuff and wait a few minutes
i removed it
ok
discord takes sometimes some time to "refresh" the commands
oh
for item in list_of_items:
embed = discord.Embed(title=item['city'], description="Market Data")
embed.add_field(name="Prices", value=f"Item: {item['name']}\nSell Max: {item['sell_price_max']}\nSell Min: {item['sell_price_min']}\nBuy Max: {item['buy_price_max']}\nBuy Min: {item['buy_price_min']}", inline=False)
embeds.append(embed)
paginator = pages.Paginator(pages=[embeds])
is there no way to limit X amount of item per page? because this just gives me 30 embeds all at once, 1 page.
Pass pages=embeds
embeds is already a list...
i think on_member_update triggers for that
async def select_callback(self, interaction,select):
await interaction.response.send_modal(journeytomeleeislandmodal(title="Enter Post Text"))# the function called when the user is done selecting options
await interaction.followup.send_message(f"Awesome! I like {select.values[0]} too!")
it doesnt send the followup msg
Hey so im trying to make a command that will as part of its functionality give everyone a role. I'm trying to use guild.members but only get the bot, I looked it up and tried the solutions given but still only get the bot even with member intents. If someone could point me in the right direction that would be greatly appreciated.
Did you add such intents to the code?
I have intents = discord.Intents().all() in my Main should I also have it in all my cogs?
Show me your main file
I don't see you passing them to the bot instance
And it is discord.Intents.all() not discord.Intents().all()
Alright thank you how do I pass it into the bot instance though?
Oh wait I see on an example one nvm thank you so much for the help. Have a good one brother.
what's supposed to be provided in auto_archive_duration when using create_thread? Im using auto_archive_duration=1 but I'm getting this error:
future: <Task finished name='Task-17' coro=<Loop._loop() done, defined at /home/zuzu/discordbots/HYDRA-Discord-Bot/venv/lib/python3.10/site-packages/discord/ext/tasks/__init__.py:152> exception=HTTPException('40
0 Bad Request (error code: 50035): Invalid Form Body\nIn auto_archive_duration: Value "1" is not a valid enum value.')>
It looks like there are only 4 allowd values descibed here
https://discord.com/developers/docs/resources/channel#thread-metadata-object
What is the default value of a discord.ui.InputText.value object if no value from the user was provided and it’s marked as optional? Is it None? It’s giving me an empty string
Did you pass a default when adding the input?
You can’t provide a default
The library has helpers to help create component-based UIs. Shortcut decorators: Objects: Attributes children, disable_on_timeout, message, timeout. Methods cls View.from_message, def add_item, def...
value will pre-fill it, not give a value if one wasn’t provided
is there a way to get the pycord event loop
for asyncio
or do I make my own
wait would: https://stackoverflow.com/questions/51689285/how-to-add-a-function-to-discord-py-event-loop work?
I am using Python with discord.py. Documentation here
I've got a bot that is running on a Discord server that links the server with a subreddit. Users have various commands that do things like get...
client.loop.create_task(func())
shouldn't worry about this right
if thats pycord code then no
alr thx
and?
bot inherits client
why does it have the raise NotImplementedError on the func?
Probly cuz it was planned but has not fully been completed yet
but it should still work?
that function will not work, but the asyncio_loop_from_bot.create_task will
I believe the purpose of the function you showed was so you did not manually have to add the task to the loop like you do currently
I see
thanks!
also why do I get this on bot startup
you must have a command that has more than 25 choices.
ohhhh frick
you would need to switch to autocomplete or make 2 options
tysm!
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
ok so while trying to add options
like before
with:
breeds = discord.Option(str, options=[discord.OptionChoice(name=name) for name in breed_types])
how the heck did I get a forbidden error
switched it to ```py
breeds = discord.Option(str, autocomplete=breed_types)
but it still gives the same weird error
what is even that option?
wait nvm... just commented out the entire func and it still gave the same error
which means it's a diff thing
api request to a random dog image
with aiohttp? ;3
nah with requests
...
await bot.loop.run_in_executor(None, requests.get, f"https://dog.ceo/api/breed/{breed}/images/random")
oh
plz use aiohttp. requests is blocking
I just add it to the aync look
oh nvm
wat
oh yeah
why do I get a forbidden err tho
you would not have to use stuff like that if you use aiohttp
you would have to show the traceback
Ignoring exception in on_connect
Traceback (most recent call last):
File "C:\Users\julia\PycharmProjects\Nestling Bot\venv\lib\site-packages\discord\client.py", line 377, in _run_event
await coro(*args, **kwargs)
File "C:\Users\julia\PycharmProjects\Nestling Bot\venv\lib\site-packages\discord\bot.py", line 1164, in on_connect
await self.sync_commands()
File "C:\Users\julia\PycharmProjects\Nestling Bot\venv\lib\site-packages\discord\bot.py", line 738, in sync_commands
app_cmds = await self.register_commands(
File "C:\Users\julia\PycharmProjects\Nestling Bot\venv\lib\site-packages\discord\bot.py", line 531, in register_commands
prefetched_commands = await self._bot.http.get_guild_commands(
File "C:\Users\julia\PycharmProjects\Nestling Bot\venv\lib\site-packages\discord\http.py", line 360, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
it's weird
I have multi factor (read somewhere about that)
.tag 403
You get a 403 Forbidden (error code: 50001): Missing Access as error?
You might've added your bot in the past without the applications.commands scope.
What to do?
Old way: Re-add the bot with the applications.commands scope.
New way: Since 11/07/2022 discord automatically includes the applications.commands scope in OAuth. You just need to re-add the bot with the bot scope. See [#discord-api-updates@996103073111998544](#discord-api-updates message) for more infos.
I have that though
on all servers?
yea
it's on one server
ima try readding it
just in case I was big dumb
YO WHAAT IS THIS AUTH
ok I readded the bot but I'm still gettin the goofy error
should I worry bout it?
if commands still work i guess you can ignore
ok thx
also
i can put a str iterable right?
idunno
breeds = discord.Option(str, autocomplete=breed_types)
breed types is a huge str list of dog breeds
I think that might be a type in docs. You can use this in the meantime discord.utils.basic_autocomplete
should I make a git issue?
:O IT WORKS
TYSM
but yeah it didn't accept a string iterable
go for it (or you could even PR)
Idk if I'm experienced enough to PR
but I might do a thing where it automatically converts it to a discord.utils.basic_autocomplete thing
await interaction.message.delete() deletes an ephemeral message correct?
It doesn’t, so how does Pycord support ephemeral message deleting?
does discord have that at all?
Yes
what'd you put in .delete()?
you have to delete using the interaction object
so interaction.delete_original_response()
interaction.delete_original_response? That gave an unknown message error
send err
you have to delete it from the interaction object that sent the message
The ephemeral message that was sent is from select
you're using the button's interaction, not that select's interaction
ohhh, thank you!
Hello, im trying to catch this error, but i seem to do something wrong.
Application Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
async def on_application_command_error(ctx: discord.ApplicationContext, error: discord.DiscordException):
# MissingPermissions
if isinstance(error, discord.ext.commands.MissingPermissions):
await ctx.send_response("Missing Permissions", ephemeral=True)```
My guess is that that error is occurring when you are registering commands not when you are running them. That event will not run for errors during registration. I will link some infor and if that doe snot fix the problem please send the full traceback
.tag 403
You get a 403 Forbidden (error code: 50001): Missing Access as error?
You might've added your bot in the past without the applications.commands scope.
What to do?
Old way: Re-add the bot with the applications.commands scope.
New way: Since 11/07/2022 discord automatically includes the applications.commands scope in OAuth. You just need to re-add the bot with the bot scope. See [#discord-api-updates@996103073111998544](#discord-api-updates message) for more infos.
thank you, but no.
the errors accours when the user uses the /ban command, but the role of the bot is not over the role of the user that should be banned. (at least thats what i think after some users gave me feedback. and ctx.command says its the ban command)
if the bot is set up correctly it will ban the user. if not that error will trigger.
So how and where do i get the traceback from for you?
you didnt include full error here
my guess would be that the raised error is an ApplicationInvokeError, so in your handler you gotta check for that one and then if its the case check if error.original is the Missing Permissions error
Errors raised in app commands are being wrapped by that ApplicationCommandInvokeError
i am sorry, i dont know how to get the full error.
ApplicationInvokeError means that the bot takes too long to answer right? then thats also not it as all commands use defer().
i clearly dont have enough informations, i will look into getting the full error and come back. sorry for the inconvinience
i cant refer to the docs right now but ApplicationInvokeError is the error raised for all exceptions happening inside an app commands execution
If you dont have permission to ban someone an ApplicationInvokeError is being raised with .original attribute set to nopermissions error or similar
What you gotta do is wrap your isinstance condition into another, checking for the ApplicationInvokeError
if isinstance(error, discord.ApplicationCommandInvokeError):
original_error = getattr(error, 'original', error)
if isinstance(original_error, discord.Forbidden):
"""Handle Error"""
else:
"""Other Errors"""
exactly

thank you three so much.
was having that issue for some days.
its now fixed and i can finally catch it
Yes
its good i have install, thats all?
okay
Now the error is:
Traceback (most recent call last):
File "C:\Users\antoi\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 399, in _run_event
await coro(*args, **kwargs)
File "C:\Users\antoi\OneDrive\Bureau\Projets VSC\EvoBot\main.py", line 19, in on_ready
await bot.load_extension(f"Cogs.{extension_name}")
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\antoi\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\cog.py", line 913, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Users\antoi\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\cog.py", line 780, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.errors.ExtensionFailed: Extension 'Cogs.general' raised an error: ImportError: cannot import name 'app_commands' from 'discord' (C:\Users\antoi\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\__init__.py)
What do I replace app_commands with?
i know, this is the error
discord.commands have slash commands
i write this?
yes I have import Option normally
from that you can also import slash_commands
like this?
from discord.commands import slash_commands, Option
i write the commands like this?
that also work if you do it in the main file
lol
?
That is not how you create a cog
oh
discord.Cog for discord.Bot, bridge.Bot and command.Cog for commands.Bot
For Discord UI, is there a better way to reference buttons when using add_item()? Since they're decorators on a method, referencing view.add_item(self.my_button) whines about it being a coro vs an Item
It's literally the last warning for this file in PyCharm 😩
is there a way to check if bot has enough perms to change roles of a given user? preferrably, without catching 403's
having issues with my bot not being high enough in roles list not being able to change roles of some users placed higher
even though bot already has Administrator permission on invite, it's a bit silly to me or i'm not understanding how it's supposed to work
Check the user and bot highest rolen
.rtfm Member.top_role
thanks!
Here's the modal dialogs example.
Can someone help me use followup, i try this :
await interaction.followup.send("Votre cdc a été créé avec succès")
error :
Traceback (most recent call last):
File "C:\Users\lytox\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ui\modal.py", line 341, in dispatch
await value.callback(interaction)
File "E:\TRANSFERT\CODE\CLIENT\SWIFT BOT\bot.py", line 475, in callback
await interaction.followup.send("Votre cdc a été créé avec succès")
File "C:\Users\lytox\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\webhook\async_.py", line 1745, in send
data = await adapter.execute_webhook(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\lytox\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\webhook\async_.py", line 219, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook ```
Hello, how do I make the “Delete Button” still work after a bot restart?
https://pastebin.com/YLvVGdbs
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Here's the persistent example.
@vivid spoke
Provide code
ty
Hello,
I can't resolve this error:
Traceback (most recent call last):
File "C:\Users\antoi\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\cog.py", line 777, in _load_from_module_spec
spec.loader.exec_module(lib) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<frozen importlib._bootstrap_external>", line 940, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "C:\Users\antoi\OneDrive\Bureau\Projets VSC\EvoBot\Cogs\general.py", line 10, in <module>
class General(bot.Cog):
^^^^^^^
AttributeError: module 'discord.bot' has no attribute 'Cog'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\antoi\OneDrive\Bureau\Projets VSC\EvoBot\main.py", line 16, in <module>
bot.load_extension(extension)
File "C:\Users\antoi\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\cog.py", line 913, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Users\antoi\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\cog.py", line 780, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.errors.ExtensionFailed: Extension 'Cogs.general' raised an error: AttributeError: module 'discord.bot' has no attribute 'Cog'
Here is the code:
import discord
from discord.commands import slash_command, Option
from discord.ext import commands
from discord import bot
import yaml
with open('config.yml', 'r') as config_file:
config = yaml.safe_load(config_file)
class General(bot.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
print(f'Bot Loaded | general.py ✅')
I tried to look on Google and fix the error myself but I can't
why do you import bot from discord?
I saw examples and it was like that I think, otherwise how do I do the from discord import bot?
do you have a file with the name of discord?
you would just use commands.Cog, not bot.Cog
^
but still weird that you dont get an error by doing from discord import bot
commands.Bot = commands.Cog
discord.Bot = discord.Cog
I have now written
import discord
from discord.commands import slash_command, Option
from discord.ext import commands
from discord import bot
import yaml
with open('config.yml', 'r') as config_file:
config = yaml.safe_load(config_file)
class General(bot.Cog):
def __init__(self, bot):
self.bot = bot
@bot.Cog.listener()
async def on_ready(self):
print(f'Bot Loaded | general.py ✅')
You clearly didn't understand
I still wonder how you import bot from discord
for commands.Bot
Assuming you're using a commands.Bot yes
.
should I write this?
from discord.ext import commands.Bot
Sorry this is my first bot and code in Python
Learn python basics and OOP
Before creating a bot
You'll get nowhere without knowing what you're actually coding
.learnpython
Resources For Learning Python
- Official Beginner's Guide
- Shortcut to guide for people new to programming and people with experience programming
- Official Tutorial
Other Resources To Learn Python
- Automate The Boring Stuff for complete beginners to programming
- Learn X In Y Minutes for people with experience programming
- Swaroopch is a useful book
- Code Abbey has practice for beginners
- W3Schools is a good resource for general use
?tag learnpython
To be clear:
When we tell you to learn Python before asking questions here, it is not meant in a derogatory way, we are not calling your dumb or incompetent. We are simply stating the fact that usage of PyCord requires a fair bit of knowledge with using OOP, Async/Await etc. in Python. If you are not comfortable with these concepts, chances are you will not understand the answers given to you in this channel.
We understand that everyone learns at a different pace, and your current knowledge with Python may have been enough so far. When we say "you need to learn Python", it is most likely a sign that we have given you an explanation that you could not understand and there is no way for us continue to help you without spoonfeeding.
thanks
I don't support anyone has seen this error before
discord.errors.DiscordServerError: 507 Insufficient Storage (error code: 0): exceeded request buffer limit while retrying upstream
I've seen it a decent amount recently and while its a server error i'm not sure if something i'm doing might be leading to it. Its leading to some exceptions that aren't being handled.
(it came from sending a short message in a channel)
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Traceback (most recent call last):
File "C:\Users\lytox\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ui\modal.py", line 341, in dispatch
await value.callback(interaction)
File "E:\TRANSFERT\CODE\CLIENT\SWIFT BOT\bot.py", line 475, in callback
await interaction.followup.send("Votre cdc a été créé avec succès")
File "C:\Users\lytox\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\webhook\async_.py", line 1745, in send
data = await adapter.execute_webhook(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\lytox\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\webhook\async_.py", line 219, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook ```
This is the error whithout interaction.defer i will delete it
Why are you deferring? And youre doing it wrong.
And why would you try to send a followup without deferring
??
don't mind about the defer
idk why he is here
i delete it
You only defer if you think your code will take more than 3 seconds to respond.
Otherwise, you dont defer.
And if you were going to defer, you do it at the TOP of the callback, not before sending a followup.
Now that you dont defer, you use interaction.response.send_message
@lofty parcel , i can use discord.utils.get(self.bot.application_commands, name="name_command") to see look subcoomands. Example subcommand = discord.utils.get(self.bot.application_commands, name="name_command_subcommand") and -> print(subcommand.id) ?
@lofty parcel
Thanks
Do you know why i have this on my hosting ?
[notice] A new release of pip is available: 23.2.1 -> 23.3.1
[notice] To update, run: pip install --upgrade pip
Traceback (most recent call last):
File "/home/container/bot.py", line 2, in <module>
import discord
ModuleNotFoundError: No module named 'discord'```
Do you have a reqs file?
yup
ofc , when i lauch i see py-cord is already gieofgr
Show your reqs file
And what are you using as host?
a little hosting that you don't know
srry i'm french, i have a bad english
discord-ext-i18n
py-cord
requests
asyncio
datetime
discord.ui
captcha
googletrans
anyio
sqlite3
Remove discord.ui
And py-cord
Hm. I'll assume it doesn't conflict with pycord.
are you sure your host is actually installing the dependencies?
it's not, try removing sqlite3 as a dependency (it's part of the standard lib, isn't needed as a strict dependency, it'll always be available)
Here's the link example.
What does this mean? This just happened when restarting my bot
Ig it's because you have a blocking function being called somewhere
most probably in your on_ready I think
@loud kayak
Nope
Changing my bot to shards fixed it, probably because it reached 2k servers the last time I restarted it.
Ah I see
@loud kayak which host is that?
Pterodactyl
My friend has a panel
It’s surprisingly cheap
elif total <= 24999999: # 24.99m
money_to_bot = int((amount * 15) / 100)
money_to_user = int((amount * 85) / 100)
await update_balance(self.pool, user.id, balance_delta=money_to_user)
await update_balance(self.pool, bot_id, balance_delta=money_to_bot)
log_message = await log_user_send_info(self, self.pool, ctx.author.id, ctx.author, user.id, user, amount)
send_logger.info(log_message)
embed = create_send_embed(ctx, new_balance, new_bank_balance, amount, user)
await ctx.respond(f'{user.mention}', embed=embed)
why doesnt this actually pings
teh user for the notification
im so confused
user: Option(discord.Member, 'Discord Member', required=True```
any idea, this makes no sense cause i swear this used to work
where is the )?
It’s at the end I didn’t copy it all the way
Try passing allowed_mentions (look it up in the docs for how to create the object.
allowed_mentions (AllowedMentions) –
Controls the mentions being processed in this message. If this is passed, then the object is merged with allowed_mentions. The merging behaviour only overrides attributes that have been explicitly passed to the object, otherwise it uses the attributes set in allowed_mentions. If no object is passed at all then the defaults given by allowed_mentions are used instead.
Thanks I’ll give it a shot
still nothing
allowed_mentions = discord.AllowedMentions(users=True, roles=False, everyone=False)
await ctx.respond(f'{user.mention}', embed=embed, allowed_mentions=allowed_mentions)```
What is your py-cord version?
py-cord-dev==2.5.0rc5
Hi there,
How can I find out who modified a thread?
Changelog
whats the most elegant version of checking a user's activity?
currently i have
if "<Streaming name='" not in str(user.activities)
but i think the issue with that is obvious
is there a way to check whether my bot can DM given user? so that i don't need to catch 403
I think it's just permissions you need to handle... if the users dms are open, eventually it will always throw an error if it tries to but can't which'd be your check :)
my bot already has administrator perms and his role is located right after highest
yet it can't DM some ordinary users with 403 Forbidden (error code: 50007): Cannot send messages to this user
which is a bit annoying, as i've heard getting too many of these may lead to bot being quarantined?
Then what do you mean by handling permissions
Bit usually says smith like insufficient permissions to dm a user, as discord.Permissions iirc.
It's used for the error Handling.
I forget what is the "accepted" way of making slash command options?
@slash_command()
my_command(self, arg1: Option(str, description="Argument 1"), arg2: Option(int, description="Argument 2")):
...
Or
@slash_command()
@Option("arg1", description="Argument 1")
@Option("arg2", description="Argument 2")
my_command(self, arg1: str, arg2: int):
...
Both work. But i do prefer typehinting discord.Option()
So the first one? Does that allow for the typehint to actually work? Or will the IDE have no idea what the type will be because it is nested in a instance of Option?
Uhh, I think the IDE doesn't know what it actually is cause it's nested.
I don't exactly remember
While my bot is in ctx.defer() it does not respond to any other command, how can I fix that?
You have a blocking function. And its not the defer.
Something AFTER the defer is blocking it
Why can't I do this:py await DiscordCDN.send(file=await attachment.to_file()).url
Trying to get a new attachment URL from a message file
I get this error:py RuntimeWarning: Enable tracemalloc to get the object allocation traceback
You are right, the function that stops the operation is synchronous, I guess that is the problem
what are you doing in there
what is it with the .url? you cant await an attribute
well i know what you wanna do and the await is correct for the _send() but why is the .url there
I have to stop using the library and make the request with aiohttp
do they not offer any asynchronous functions?
I don't know, it's probably
Also, just a warning, i once implemented a bootleg GPT API with aiohttp, and it's very painful to do
it used the same API structure as the official API but its just pain if you wanna properly do history and stuff
It needs to send the message to the channel before I can get the URL
you aren't storing the url anywhere judging from your tiny code snippet, and it would help if you sent the full error
(and more of the code around the place it errors)
please make it more readable and just store the coro in a variable
you mean the sending or the attachment to file? i never store functions in variables so i have no idea lol, but i wanna get better
you have to access the select again to find the it
the coro is after the await
so like
a = await b()
a.attr
ah yea, makes sense
I'm storing its URL to a website, because the channel the message is in will be deleted right after, making the attachment url invalid
well, then, again, show us a bit more of the code around the erroring part, and also the entire error
send it in a different channel or something and proxy it
That's what I'm doing, sending the attachment to a different channel
just a reminder that you’ve seen the recent announcement regarding attachment changes?
#discord-api-updates message
anyway i found the official async usage https://github.com/openai/openai-python#async-usage

(also if you use the stream you can edit the message every X characters and it looks really cool)
ohh thank you very much I was looking for that for a long time
is there a wait to completly stop the bot for X seconds?
You can technically block the bot loop using time.sleep()
letme check rlly quick
But couldnt it happend that time.sleep will completely crash the bot?
Well yes
You're blocking the code ig
Not the best way.
xD
Why do you want to block the bot?
you could add instead a if else check and if you want to pause the bot it should not react to anything
so your bot is not crashing for using something like time.sleep
how can i make it not react to anything
xD
with basic if else
with time.sleep it does pause but it "queue" the commands
and execute them after the pause
yes
.
and after the time.sleep it resume and execute all the commands xd
oh you deleted the msg
rip
I have started to use stuff like that
that can be a good idea
oh no it's not
because the commands are executed after pause anyway
to the online/offline mode will be in pause
so its the same i think(?
just use a bot var
and override the events that execute the commands
if the var is true, completely ignore the execution
otherwise process the command
for slash commands you could use on_interaction and after that filter the slash commands
why would u not ignore views
im a bridge enjoyer

i don't know that that is
Does pycord have a way to do converts for slash like you could with ext.commands?
anyone?
anyone knows the total number of select menus that can be used in an embed? is there any limit?
Converts as in?
3 or 4.
There's a max of around 20 items for views. Select menus use 5.
Like commands.Converter but for slash
thank you!
(its 5, there are 5 usable rows)
Hello, someone on fiverr coded me this ticket system, but I get Errors when im switching Categories in the Select Menu.
I think the Problem is, that I get 2 bracelets "}" in the json sometimes, but idk how to fix it.
Code: https://pastebin.com/U0qDj9tD
Error: https://pastebin.com/7qCmrivD
The json look sometime like this:
{
"channel_id": 1170860691427692545,
"category_id": 1176955264654659597,
"counter": 0,
"reason": "Sonstiges"
}
}
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
If no one else helps you fix it I’ll help ya tomorrow just ping me
Is there some sort of automatic internal cache for autocomplete? When I add records to datasets that the autocomplete draws from, it doesn't seem to reference them in subsequent executions of the command. How can I ensure that Autocomplete is always referencing the compleete dataset?
How many item does it have?
About 40 or so.
It was my error; I had async-lru set up for those methods; explicitly clearing the cache when I update records makes it better.
im getting this error:
Exception has occurred: ModuleNotFoundError
No module named 'discord.interactions'
File "C:\Users\Angel\Downloads\yonny\main.py", line 4, in <module>
from discord.ext import commands, tasks, bridge
ModuleNotFoundError: No module named 'discord.interactions'
but i doesnt import the module discord.interactions
I don't suppose its possible to make a button, on a bot response message, copy something to the clipboard is it?
Not a feature of Discord, as cool as it would be. Could always just send them a code block in an ephemeral, which at least on Desktop has a Copy.
it has to specifically be ephemeral?
(Oh wait, no they don't. Not sure how I invented that in my head)
ah ok
Doesn't specifically have to, but I assumed you wanted just the user who clicked to get the output.
yea in this case it doesn't reallllly matter but it would probably be less chatty if that was teh case
Hello. Can you tell me how to make a clear choice in one of the arguments for the slash_command?
From what i've seen, beyond the API definition docs there doesn't appear to be any docs on the application role connection stuff for pycord. Does anyone have an example they could share by chance on how to properly use it?
Because pycord hasn't added role connections.
What is a clear choice supposed to be?
not vague
is there something wrong with slash commands?
I cant seem to add even the most basic slash command to my bot
it just doesnt work
if I go into any cog and add:
@bot.command()
async def testcommand(self, ctx):
await ctx.respond('hey!')```
it wont register at all
and ive had the bot on for an hour
How do you load the cog?
@client.event
async def on_ready():
logging.info(f"{client.user} has logged in")
for filename in filter(lambda f: f.endswith(".py"), os.listdir("commands/")):
try:
client.load_extension(f"commands.{filename[:-3]}")```
here's the thing: the cog has other commands in it and those load just fine
its just if I were to add this new command into the cog it wont load that specific command
Dont load the cogs at the Event
ah mb thats not part of the cogs being loaded
ok. I tried moving this into its own cog but I forgot to remove it from its original code. It spat out an error and said that it cant register the new cog because 'a command with that name is already registered'
so apparently it loads the command
but it doesnt show up at all
full cog:
import logging
from os import path
from discord import bot
from discord.ext import commands
class Test(commands.Cog):
def __init__(self, client):
self.client = client
@commands.Cog.listener()
async def on_ready(self):
logging.info(
f"Cog {path.basename(__file__).removesuffix('.py')} loaded successfully"
)
@bot.command()
async def random(self, ctx):
await ctx.respond('hey!')
def setup(client):
client.add_cog(Test(client))
if I add random into an already existing cog, it spits out an error and says that the commands must have a different name. if I remove this cog, and leave random in said existing cog, it loads all commands from that cog perfectly fine, but does not load /random
wait. now it loaded. what the fuck?
and leaving the bot up for one hour did nothing?
bruh
For example, one letter from the suggested
why do you import bot from discord?
I have the following code to change my bot's status. However, when executed it doesn't show any status on the bot. It seems pretty straightforward in the documentation, so is this a bug or did I miss something?
await self.bot.change_presence(activity=CustomActivity(name=f"Proofreading {random.choice(translator_list).name}'s translations"))
Where are you doing this and how often?
Generally you should not put this in on_ready and rather pass the first status to the bot constructor.
If you have it in a task you need to make sure that you are waiting until the bot is ready.
.rtfm wait_until_ready
discord.Client.wait_until_ready
discord.AutoShardedClient.wait_until_ready
discord.ext.bridge.Bot.wait_until_ready
discord.Bot.wait_until_ready
discord.ext.commands.AutoShardedBot.wait_until_ready
discord.AutoShardedBot.wait_until_ready
discord.ext.commands.Bot.wait_until_ready
discord.ext.bridge.AutoShardedBot.wait_until_ready
guys is there any way to put description for a parameter while using bridge commands without breaking the prefix functionality? Like this: Want to read some memes bla bla... that part
I think options should still work as normal. They will just not be used by the prefix commands? Is it not working currently?
If it is not please show your comand definition
This is being executed within a task that doesn’t run until the bot is ready.
how frequently?
Once every 5 minutes. The status doesn’t show up any time it’s ran so I don’t think it would be getting ratelimited.
I just tried to find if their is a length limit and I did not see one. But could you try making it shorter just to test.
Can you send an example please? Probably i messed up (i always do) ty
that does not work? Try using the decorator way instead.
IE
@bot.slash_command()
@option("name", description="Enter your name")
@option("gender", description="Choose your gender", choices=["Male", "Female", "Other"])
@option(
"age",
description="Enter your age",
min_value=1,
max_value=99,
default=18,
# Passing the default value makes an argument optional.
# You also can create optional arguments using:
# age: Option(int, "Enter your age") = 18
)
async def hello(
ctx: discord.ApplicationContext,
name: str,
gender: str,
age: int,
):
await ctx.respond(
f"Hello {name}! Your gender is {gender} and you are {age} years old."
)
If that does not work someone else will have to help you. I am not knolagable with bridge.
It says TypeError: 'description' is an invalid keyword argument for str()
idk lemme try again changing a few things
discord.ext.commands.Option
Ok so for example, in this reddit.py, when i do this image, ONLY the slash works, as expected with options, but i get no response whatsoever when i do >meme (prefix), and get this error which really isnt being helpful at all...
Ignoring exception in on_command_errorTraceback (most recent call last):
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 378, in _run_event await coro(*args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^TypeError: on_command_error() missing 1 required positional argument: 'error'
But when in this image, i un-comment the commented places and replace the bridge with slash_command (basically divide it into 2), it works, both slash and prefix, which made me get to the conclusion of Options not working with prefix commands (ext).
When i do it the long way (seperated), the slash command also has options working fine, and the description shows up, but as i said, >meme, the prefix version doesnt respond. As you can see, this is fine but since both commands technically have the exact same code, it would REALLY save me some time if i could write both in one piece (using bridge?), and probably would be neater as well.
is there a way to make this work with bridge? and does it break with prefix commands?
Can you show your pip list
There are a lot of irrelevant pips tho
aiohttp==3.8.4
aiosignal==1.3.1
aiosqlite==0.18.0
akinator==1.1.1
alembic==1.10.2
anyio==3.6.2
async-generator==1.10
async-timeout==4.0.2
attrs==22.2.0
beautifulsoup4==4.12.0
Brotli==1.0.9
bs4==0.0.1
certifi==2022.12.7
cffi==1.15.1
charset-normalizer==3.1.0
colorama==0.4.6
discord==2.2.3
discord.py==2.2.3
emoji==2.2.0
exceptiongroup==1.1.1
filelock==3.10.6
frozenlist==1.3.3
greenlet==2.0.2
h11==0.14.0
httpcore==0.17.1
httpx==0.24.0
idna==3.4
Jinja2==3.1.2
Mako==1.2.4
MarkupSafe==2.1.2
mpmath==1.3.0
multidict==6.0.4
mutagen==1.46.0
networkx==3.0
openai==0.27.2
outcome==1.2.0
psutil==5.9.5
py-cord==2.4.1
pycparser==2.21
pycryptodomex==3.17
pyfiglet==1.0.2
PyNaCl==1.5.0
pypresence==4.2.1
PySocks==1.7.1
python-dateutil==2.8.2
pytz==2022.7
pywin32==305
redis==4.5.3
regex==2023.3.23
requests==2.28.2
rfc3986==1.5.0
roblox==2.0.0
sanic-routing==0.7.2
selenium==4.9.1
six==1.16.0
sniffio==1.3.0
sortedcontainers==2.4.0
soupsieve==2.4
spotipy==2.22.1
SQLAlchemy==2.0.7
sympy==1.11.1
tiktoken==0.3.3
tokenizers==0.13.2
torch==2.0.0
tqdm==4.65.0
trio==0.22.0
trio-websocket==0.10.2
types-pytz==2022.7.0.0
typing_extensions==4.5.0
urllib3==1.26.15
wcwidth==0.2.6
websockets==10.4
wsproto==1.2.0
yarl==1.8.2
youtube-dl==2021.12.17
yt-dlp==2023.3.4
You will have to uninstall
discord, discord.py, and py-cord
Then re-install py-cord.
After that make sure that you are using bridge.BridgeContext
And also try using discord.Option for the options.
do i reinstall discord and discord.py? or just py-cord alone?
read it again what Wolfy was writing
i guess no?
and is it fine if i replace every bridge.bridge_command in all my cogs or does it have a probability to break some things?
with BridgeContext
What is ctx: Context?
its ctx but with a lil added feature
commands.Context?
yeah
but they are bridge commands and not prefix commands
i dont even know how i reached this point, it just somehow worked
every time i think i finally understood discord.py... it just keeps getting more complicated
but py-cord is not discord.py
i mean yeah, but still. pycord is lowkey better i guess
but still it keeps getting more and more complicated
py-cord is really easy to use
dont underestimate my noobiness
Now it says this: TypeError: Can't instantiate abstract class BridgeContext with abstract methods _defer, _edit, _respond
nvm my fault
Still having the same problem tho, the slash works just fine but prefix doesnt
it gives that error each time prefix is used
Anyways, if someone could provide a single example on usage of Options with bridge, i might be able to try&fix the errors. note that it should both work for prefix and slash.
Here's the bridge commands example.
this is the offical example for it but I do not know if this will solve your issue
this isnt uncommon, i either try reloading the discord client, or have someone else to try to run the command, cause for somes it'll show up right away.
Hello, how can I make the prompt detect it as an argument like this: spaces, for example?
"Hello friends, how are you?" then I detected those arguments for +
What do you mean, "the prompt?"
el message content example "hello friends"
yeah, you can use string's .split method to split a string into a list
What function does prompt have = prompt.replace(' ', '+')
For example:
my_string = "Hello, world!"
new_list = my_string.split(",")
print("my_string: ", my_string)
print("new_list: ", new_list)
Output:
my_string: Hello, world!
new_list: ["Hello", " world!"]
Can I show my code?
@bot.command(name='chatgpt')
async def chatgpt_command(ctx, *, prompt: str):
prompt = prompt.replace(' ', '+')
api_url = f'https://api.cirrus.center/api/v1/generations/gpt-3.php?prompt={prompt}'
try:
response = requests.get(api_url)
if response.status_code == 200:
data = response.json()
generated_text = data['openai']['generated_text']
embed = discord.Embed(
description=f'{generated_text}',
color=0x2f3136
)
await ctx.send(embed=embed)
else:
await ctx.send(f"{response.status_code}")
except Exception as e:
await ctx.send(f"{e}")```
this would replace the first character with the other characters.
prompt = "Hello, world!"
new_prompt = prompt.replace("Hello", "Goodbye")
print("prompt: ", prompt)
print("new_prompt: ", new_prompt)
Output:
prompt: Hello, world!
new_prompt: Goodbye, world!
I have good news for you! In the case of web requests, you can use urllib's parse to make sure your string is URL-ready.
example:
import urllib.parse
prompt = urllib.parse.quote_plus(prompt)
There's also methods such as urlencode
prompt = urllib.parse.urlencode(prompt)
sorry for my ability but I don't understand
What part of the code changed?
You can take a look at the docs for it here
I need it to detect the message after the spaces, it only detects the message after the command
To implement this in your code, you would have to import urllib.parse, preferably at the beginning of your file.
import urllib.parse
Then, you would want to change your prompt to something url-friendly.
Instead of:
prompt = prompt.replace(' ', '+')
you can put:
prompt = urllib.parse.urlencode(prompt)
Oh, I see.
man, i haven't used that in a while
one moment
okay
Are you sure your command isn't storing everything in prompt already?
That looks like it should work fine.
doesn't look
Do you want to add a print statement at the beginning of your function, to check if that is working?
print(prompt)
This message shows that it only detects the first word
Unfortunately, no hablo espanol. Do you want to try out that print statement anyway? Something else may be going on.
yeah, that seems to confirm that the command is detecting all of the words.
OK
do you want to print the URL as well? If that's okay, it may be an issue with the API you are using.
how print the url
same way you did the prompt
print(api_url)
work
Yeah, that looks good. In that case, it may be something wrong with the API you are using. In any case, though, I would recommend using URL encoding anyway, as that is more secure and will save you some headache if people decide to use your command with some special characters.
I tried to do it with the openai API but I got an error.
@torpid cosmos
If you want to use certain packages, you need to install them.
In this case, you would need to run the following line in your terminal:
pip install openai
i have the packages installed already
In that case, you need to make sure you have the correct Python installation selected for use.
in your terminal, type python --version and show me the result.
Python 3.10.5
Now, in VSCode, towards the bottom-right corner of the screen it should show you a python install
Something like this:
Show me what it says there for you
when I run my bot on testing bot, everything is working fine, but if I try on my real bot with a lot of servers I get this error :
py_cord is destroying the task on_connect
and in that on_connect, I connect to my database
Anybody knows what is happening ?
The only difference between the 2 code run is the size of the bot (one testing with 2 server, one with 2100 server)
i need help
pip install discord_slash
ERROR: Could not find a version that satisfies the requirement discord_slash (from versions: none)
ERROR: No matching distribution found for discord_slash
We don't use discord_slash
And we are not the discord_slash library
Try connecting to your db on on_ready
I cannot, I need to have my connection ready before the on_ready
the on_ready event can take quite a longtime before getting called
while loading the cache
can you start your database before starting the bot?
I will problably need to do that yes
but strange that pycord is destroying that event
Can you stay in one channel pls? ;3
#1178539122923683840
or close the thread
^^
yess I though the questions was more complex than a simple general question, that is why I created a thread
after
Changed it to just test but still got nothing. This is the full code. I know it's running because the print statement is working, so I'm either doing something wrong in change_presence/CustomActivity or there's a bug in the library.
@tasks.loop(seconds=300)
async def update_discord_status(self):
print("triggered")
await self.bot.change_presence(
activity=CustomActivity(
name=f"test")
)
@update_discord_status.before_loop
async def before_update_discord_status(self):
await self.bot.wait_until_ready()
that is working fine for me
Can you think of any reason for why that wouldn't be working for me? Im on the latest version of pycord (2.4.1 if I'm not mistaken).
Uninstall py-cord and install py-cord-dev
And can I see your pip list?
How can I get the member who banned another member?
I believe you have to check the audit log.
I found a way through Audit Log, thanks. Can you tell me if there is an event for Audit Log or just use loop?
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...
Thank you
quick question - i am linking all buttons in a view to the same callback. is there a way to retrieve which button was clicked (e.g. get the button's custom_id attribute?)
https://docs.pycord.dev/en/stable/api/models.html#discord.Interaction.custom_id
That will be the custom ID
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 ...
yes.
how you retreive the custom id in the callback function?
The first argument of the callback function should be Interaction. (Might be second)
yes, first, now i dont believe interaction contains such data
could anyone tell me where to find / how to set the description of an argument? cuz i figured out how to make the command have a description but not the args
Like it is empty/None?
Here's the slash options example.
Look at the above example please :)
Got a very weird error on my bot that's running. First time ever this has come up and I have zero clue what this is about:
1|rimuru | INFO:discord.client:Cleaning up tasks.
1|rimuru | INFO:discord.client:Cleaning up after 2 tasks.
1|rimuru | INFO:discord.client:All tasks finished cancelling.
1|rimuru | INFO:discord.client:Closing the event loop.
1|rimuru | Traceback (most recent call last):
1|rimuru | File "/root/RIMURU/main.py", line 2077, in <module>
1|rimuru | client.run(token)
1|rimuru | File "/usr/local/lib/python3.10/dist-packages/discord/client.py", line 715, in run
1|rimuru | return future.result()
1|rimuru | File "/usr/local/lib/python3.10/dist-packages/discord/client.py", line 694, in runner
1|rimuru | await self.start(*args, **kwargs)
1|rimuru | File "/usr/local/lib/python3.10/dist-packages/discord/client.py", line 658, in start
1|rimuru | await self.connect(reconnect=reconnect)
1|rimuru | File "/usr/local/lib/python3.10/dist-packages/discord/client.py", line 553, in connect
1|rimuru | await self.ws.poll_event()
1|rimuru | File "/usr/local/lib/python3.10/dist-packages/discord/gateway.py", line 589, in poll_event
1|rimuru | await self.received_message(msg.data)
1|rimuru | File "/usr/local/lib/python3.10/dist-packages/discord/gateway.py", line 539, in received_message
1|rimuru | func(data)
1|rimuru | File "/usr/local/lib/python3.10/dist-packages/discord/state.py", line 1221, in parse_guild_create
1|rimuru | guild = self._get_create_guild(data)
1|rimuru | File "/usr/local/lib/python3.10/dist-packages/discord/state.py", line 1185, in _get_create_guild
1|rimuru | guild._from_data(data)
1|rimuru | File "/usr/local/lib/python3.10/dist-packages/discord/guild.py", line 504, in _from_data
1|rimuru | self.stickers: Tuple[GuildSticker, ...] = tuple(
1|rimuru | File "/usr/local/lib/python3.10/dist-packages/discord/guild.py", line 505, in <lambda>
1|rimuru | map(lambda d: state.store_sticker(self, d), guild.get("stickers", []))
1|rimuru | File "/usr/local/lib/python3.10/dist-packages/discord/state.py", line 370, in store_sticker
1|rimuru | self._stickers[sticker_id] = sticker = GuildSticker(state=self, data=data)
1|rimuru | File "/usr/local/lib/python3.10/dist-packages/discord/sticker.py", line 277, in __init__
1|rimuru | self._from_data(data)
1|rimuru | File "/usr/local/lib/python3.10/dist-packages/discord/sticker.py", line 420, in _from_data
1|rimuru | super()._from_data(data)
1|rimuru | File "/usr/local/lib/python3.10/dist-packages/discord/sticker.py", line 284, in _from_data
1|rimuru | self.url: str = f"{Asset.BASE}/stickers/{self.id}.{self.format.file_extension}"
1|rimuru | File "/usr/local/lib/python3.10/dist-packages/discord/enums.py", line 560, in file_extension
1|rimuru | return lookup[self]
1|rimuru | KeyError: <StickerFormatType.unknown_4: 4>
what event is triggered when loading Cog? I need to run an asynchronous function in it to connect the wavelink node
I'm switching from d.py and it turned out to be a problem
P.S. before that I used
async def cog_load():
...
Thanks, fixed! Very weird issue, find it strange my bot isn't running off my python virtual env so better fix that as well
Hello. I have a problem: on_audit_log_entry called on my computer, but not called on the hosting, the application and the code are exactly the same
on_cog_load or something similar I believe, give me one moment to verify
I'm not seeing anything in the event reference, actually
I may be overlooking something though. You can use asyncio to run a coroutine in the cog's __init__ method
import asyncio
import discord
class MyCog(discord.Cog):
def __init__(self, bot):
self.bot = bot
asyncio.run(my_coroutine())
...
It should be MyCog
do you agree with that solution, though? is there a better way it can be done?
it works, not the best way tho
I didn't think so
what other solutions do you have
it's probably fine
How does MEE6 hide commands from the command list until the user adds new features?
What do you mean?
Discord changed how stickers worked a while back. You would not notice the error unless someone sent an animated sticker and you had message content I think.
yea I learnt the hard way as apparently my bot made 1k requests
and discord sent me a DM lmao
Yes, I would like to get a better way. I understand that this will work, but I want to do it in a normal way
What's the default interaction timeout; 15 mins, right?
Do options like disable_on_timeout work if you don't specify a specific timeout period? I feel like it is sometimes too slow
Default timeout is 3 minutes.
is that targeted towards my question? if so, if you invite mee6 to your server, mee6's command list is pretty empty until you start adding features such as 'moderation' which will add a bunch of commands
Ah, only three. Apparently you can't have an ephemeral timeout greater than 15.
How long can non-ephemerals be?
as long as the message exists
Ignoring exception in on_connect
Traceback (most recent call last):
File "C:\Users\domin\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 399, in _run_event
await coro(*args, **kwargs)
File "C:\Users\domin\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\bot.py", line 1182, in on_connect
await self.sync_commands()
File "C:\Users\domin\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\bot.py", line 738, in sync_commands
registered_commands = await self.register_commands(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\domin\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\bot.py", line 602, in register_commands
registered = await register("bulk", data, _log=False)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\domin\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\http.py", line 283, in request
async with self.__session.request(
File "C:\Users\domin\AppData\Local\Programs\Python\Python311\Lib\site-packages\aiohttp\client.py", line 1141, in __aenter__
self._resp = await self._coro
^^^^^^^^^^^^^^^^
File "C:\Users\domin\AppData\Local\Programs\Python\Python311\Lib\site-packages\aiohttp\client.py", line 560, in _request
await resp.start(conn)
File "C:\Users\domin\AppData\Local\Programs\Python\Python311\Lib\site-packages\aiohttp\client_reqrep.py", line 899, in start
message, payload = await protocol.read() # type: ignore[union-attr]
^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\domin\AppData\Local\Programs\Python\Python311\Lib\site-packages\aiohttp\streams.py", line 616, in read
await self._waiter
aiohttp.client_exceptions.ClientOSError: [WinError 1236] The network connection was aborted by the local system
why in the world is this happening?
I don't have anything to do with aiohttp in the code
You will be surprised when i tell you pycord uses aiohttp
my events to what the bot response al mention @bot no function me
Rephrase that question and provide relevant code.
What are the limitations of the Guild.fetch_message(), Message.edit() and Message.delete() functions? Can I lose access to a message earlier than two weeks? Could I lose access to messages after a reload?
fetch makes an api call.
you will never lose access to such message if you fetch it
and you will never lose access to deleting or editing a message older than two weeks, thats a limitation for bulk deletions
Thank you
sigh, so what do I do to fix this
maybe anyone who can help me please?
I think the problem is with using json itself as a database. Don't see anything wrong with any of the read or writing part. Maybe two people may have used the command at the same time causing the program to write it in a wrong manner.
Otherwise I don't think it's even possible to write an invalid dictionary to a json as it would return an error before writing it to the file.
Also I think the person who coded it may have structured the json in a wrong manner?
Cuz if anyone uses the ticket command the entire json gets reset, unless if that's what you want?
Tbf you should show these to the person whom you got the code from, they must know it better
is it possible to get a text input in a view (not a modal) ?
@bot.event
async def on_message(message):
if message.content.startswith(bot.user.mention):
prefix = bot.command_prefix
embed = discord.Embed(title="", description=f"Current bot prefix: {prefix}\nUse **{prefix}help** for a list of commands.", color=(0x2f3136))
await message.channel.send(embed=embed)
else:
await bot.process_commands(message)
my events to what the bot response al mention @bot no function me
k tysm
maybe he should do it without the select Button and just with the message select menu.
Is it possible for the bot to send voice messages?
Na
quick question i know its possible to have a bot in multiple servers but is it possible to have the bot pull different role ids from different servers?
What I am asking is it possible to pull different roles from different discord guils
guilds*
Should be, want u wanna do?
I wanted to make a command but I wanted it to be a check that only a certain role/roles can do
I planed on using if statements but how can I pull the roles from different guilds
Would I have to define the guild or can I just put the role id and the bot will pick up on it?
When you mean by both id you are referring to the role itself and the guild?
Yep
If u want to have it more general, look for certain permissions or role names
Permissions check via decorator is the most common way
Yea I was thinking permissions but its alright
Thanks for you help and your help clarifying my question
Always again
help me
What are your message intents?
yes
the bot all work but the events to mention no work in this case
@limber terrace Can you help me with trying to solve this problem
I don't know where to go to start about defining roles from different guilds
Have you enabled privileged message intents in the developer page?
Whats the problem?
How did u start?
Get the guild and from the guild u need to get the role
how to convert a webhook object to webhook url
U can do that?
I dont know, I'm asking how to.
Hello! How to use the link button?
Here's the link example.
how i can load all the cogs?
Stay in one channel pls
how install pycord on windows8.1?
OK
how do i give commands (regular prefixed ones) aliases?
you mean not application commands?
prefixed commands
Learn how to use the commands extension for Pycord.
pass aliases=[] to the decorator
aliases is a list of strings
thanks
i was gonna make my own decorator lmao
oh no no, lmao. it is built in.
thanks!
is it currently possible to manage these settings via a bot?
def guardar_datos():
datos = {
"antiraid_bots": antiraid_bots,
"antiraid_channels": antiraid_channels,
"antiraid_roles": antiraid_roles,
"antiraid_links": antiraid_links
}
try:
with open("datos.json", "w") as archivo:
json.dump(datos, archivo)
except Exception as e:
print(f"Error al guardar los datos: {e}")
def cargar_datos():
try:
with open("datos.json", "r") as archivo:
datos = json.load(archivo)
return (
datos.get("antiraid_bots", {}),
datos.get("antiraid_channels", {}),
datos.get("antiraid_roles", {}),
datos.get("antiraid_links", {})
)
except FileNotFoundError:
return ({}, {}, {}, {})
antiraid_bots, antiraid_channels, antiraid_roles, antiraid_links = cargar_datos()```
This code works if the bot remains online and saves the data
but when you restart the bot it is as if data.json was empty.
Hello. How can I edit a bot message that was sent before it was reload?
Fetch the message
.rtfm fetch_message
discord.abc.Messageable.fetch_message
discord.PartialMessageable.fetch_message
discord.TextChannel.fetch_message
discord.ext.commands.Context.fetch_message
discord.Member.fetch_message
discord.VoiceChannel.fetch_message
discord.ext.bridge.BridgeExtContext.fetch_message
discord.Thread.fetch_message
discord.Webhook.fetch_message
discord.ext.bridge.BridgeApplicationContext.fetch_message
discord.SyncWebhook.fetch_message
discord.ApplicationContext.fetch_message
discord.User.fetch_message
discord.DMChannel.fetch_message
discord.GroupChannel.fetch_message
help me
It causes an error after reload, but I'll try again, thanks
current_time = datetime.now(gmt3_timezone)
print(f"current time: {current_time}")```
The result is 6 hours behind from what the actual time is. Any way to fix it?
what i should use commands.slash_command or discord.slash_command
ok and what is this error?
Traceback (most recent call last):
File "C:\Users\Assaf Cohen\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 399, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Assaf Cohen\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 1182, in on_connect
await self.sync_commands()
File "C:\Users\Assaf Cohen\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 738, in sync_commands
registered_commands = await self.register_commands(
File "C:\Users\Assaf Cohen\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 602, in register_commands
registered = await register("bulk", data, _log=False)
File "C:\Users\Assaf Cohen\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\http.py", line 371, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In 36: Application command names must be unique
application commands names must be unique
Is there a way to call py print(paginator.current_page) everytime the page is switched? cant figure it out
class shopCategory(discord.ui.View):
@discord.ui.select(
placeholder="Pick a section",
min_values=1,
max_values=1,
options=[
discord.SelectOption(
label="Crates",
emoji="",
description="View the crates shop!"
),
discord.SelectOption(
label="Limited time offers",
emoji="✨",
description="View FiveaSide limited time offers!"
),
]
)
async def select_callback(self, select, interaction):
if select.values[0] == "Crates":
crate_types = ["Base", "Elite", "Divine", "Golden"]
crate_buttons = crateButtons(crate_types)
crates_pages = [
create_crates_embed(),
coming_soon_embed(),
]
paginator = pages.Paginator(pages=crates_pages, use_default_buttons=True, timeout=60, custom_view=crate_buttons)
print(paginator.current_page)
await paginator.respond(interaction)```
if i want to add a link and primary button to a view, do i have to group them under a single class or can they be two separate classes and then i just add them to the view using view.add_item
You can use view.add_item
And youre indeed forced to use view.add_item for link buttons
i have these two classes for buttons but when i try to add_item, i get the error expected Item not <class '__main__.RegButton'>
Is there a way to lock a forum channel thread through Pycord? I looked in the documentation and didn't see anything.
Can't tell if I'm blind or not
Someone help solve the problem, please
https://discord.com/channels/881207955029110855/1179248212138262548
How I can remove all the build in application commands?
hey guys quick question: do you have only 1 connexion to the database for the whole bot (and use cursors where it's necessary), or do you create (and close) a connexion each time you interact with the db ?
If you have only one, where do you "store" it (global var, attribute of bot, etc) ?
Thanks 😄
Call .edit() on the Thread obj with locked set to Trur
https://docs.pycord.dev/en/stable/api/models.html#discord.Thread.edit
is it possible to add multiple classes to view?
diff. view classes?
or button/menu classes
Nope, different view classes.
For example, i have pagination buttons made for a shop command, for each page switch, the buttons have to change to match page content for users to be able to buy the items listed.
Dont know if that made much sense but im willing to explain further if needed
There are no built in application commands. Except possibly help.
So I hoe I can remove help
are you creating a help command?
If I remember correctly discord.Bot does not have a defualt help command
I use connection pooling.
I call a setup DB function before the bot starts then. I import my database instance. Then I can call methods on that.
from database import database as db
await db.fetch("SQL", args)
The fetch function I made will get a curser and release the curse to the pool after the request is made.
ok thanks a lot 😄
Hello,
does anyone of you know how to get this column? 🙂
by column you mean the multiple embeds?
its just .send(embeds=[discord.Embed(), ...])
But these are not individual embeds, are they?
The dark gray fields?
How can you get the corners of an embed so round?
the color set is the same as the embed background
Okay, I've just tested it myself. They are indeed embeds 🙂
Thank you! 🙂
Yeah but again how come they’re rounded 🤔
embeds were always
…well I feel dumb. I guess it just looked extra round because of the accent color being the same
it’s always like that. If i didn’t tell you that the old discord logo isn’t symmetrical you wouldn’t’ve known
what a random fun fact
is there a max tasks.loop or is it "infinite"?
it's your computer's memory
well, it's not even close to infinite
Best I can do is tree-fiddy
How can I reset channel permissions? Using overwrites?
ture
Thank you
But.. I don't know what permissions are defined for the channel, set_permissions allows to change if there is a target
I'll use property overwrites, which will give me information about all the permissions to the channel
How can I add Apps to my bot? I do not know what it is called
Context menus.
Here's the context menus example.
thank you
How do I get the quick invite like like some bots do when you click on the profile and it has the invite me button
Like @rugged lodge
Is it possible to create a slash command that I can activate or deactivate while the bot is running by booing True or False so that it is displayed or not displayed when I type /?
no
is it possible that you get discord.errors.NotFound interactions when discord api lags a bit? sometimes i get them poping up not sure if i should just set any code that might look heavy to defer or just defer all interactions just in case
Is it interaction that are not found? It could be true. You should only defer long running code and not all of it. (If it is already high latency then the defer might not even go through)
yea interaction not found
i guess i should benchmark the commands to ensure they're executing fast enough
depends on the percentage that is occurring
it's happened twice in the last month, bot is used daily by pretty low number of users like 10-20
i wouldn’t worry about it until the fail rates are like 3%
quick question - how do i set a paginator to use a paginatormenu i made?
quick question. Somehow when I've restarted the bot, discord re-registered the commands that don't exist anymore.. and the commands that do exist.. are now not showing up as slash commands at all in the menu.
Any help?
do you use cogs?
yes
how do you load them?
async def load_cogs():
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
# cut off the .py from the file name
client.load_extension(f"cogs.{filename[:-3]}")```
why do you use async def?
Because in an old version it needed the client.load_extension to be aync, and forgot to remove the async
just removed that now
Now I would like to see your pip list pls ;3
you should start to use a venv for your projects
the only reason I don't is that it's the only project on that machine
@little cobalt Just uninstalled those and now I have an issue running the bot.
File "index.py", line 6, in <module>
from discord.ext import commands
ImportError: cannot import name 'commands' from 'discord.ext' (unknown location)```
install py-cord-dev
I already have
XD
that's why I don't get the issue
just to show
@little cobalt -- pycord-dev is already installed and it's still producing that error
restart the IDE
do you mean the VPS? the code isn't running inside the IDE
because both restarting VPS and IDE are still producing same issue
but you uninstalled and reinstalled py-cord-dev right?
and that was the issue. I'd done an upgrade instead of uninstalling and reinstalling
although, I'm still having the same issue. None of these commands should be registered. (Literally rewriting the bot today and none of these commands exist in the code)
and the commands that should be registered, are not
when they were working fine before a bot restart that somehow pushed all of the old commands back, despite them not existing
I was literally using the command, then after using the command, it de-registered said command, and now refuses to see the command at all
But now I can’t continue development because obviously it’s not picking up any commands
you can run an “empty” bot (like a file with just a bot and an on_ready event) to unregister all commands and then run your actual bot
I’ll try this, just went to get food. The thing is, it unregistered the commands, then registered them again.. which I don’t get
An error occured: 403 Forbidden (error code: 50001): Missing Access
``` Hello, users are receiving this error, if they denied the view channel permission as the bot is not able to edit the message. How can I catch this using global error handling for slash commands, as i want to explain to the user how they can fix it. I cant seem to figure this one out .
well, you had conflicting libraries
this is what i last tried
@commands.Cog.listener()
async def on_application_command_error(self, ctx, error):
if isinstance(error, commands.CommandOnCooldown):
await ctx.respond(f"This command is on cooldown, please wait {round(error.retry_after)} seconds.")
return
elif isinstance(error, discord.errors.HTTPException):
await ctx.respond("i dont have view channel perms.")
return```
I'm not sure why it would register commands that didn't even exist in the code though
that's what I don't get
Do you know where this error is occurring?
Ignoring exception in on_application_command_error
Traceback (most recent call last):
File "/home/container/src/cogs/slotscog.py", line 117, in slotmachine
suspense_message = await ctx.send(f"{emote_spinning} | {emote_spinning} | {emote_spinning}\n"
File "/home/container/.local/lib/python3.10/site-packages/discord/abc.py", line 1628, in send
data = await state.http.send_message(
File "/home/container/.local/lib/python3.10/site-packages/discord/http.py", line 365, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access``` that is the exact line that causes it, but it only causes it if the bot doesnt have view channel permissions (slash commands still work as long as you're editting messages / sending them afaik), but it's caused whenever the user runs the slash command
Okay, all fixed now :)
if it is a slash command, shouldn’t you be using ctx.respond
i actually do delete the message, th en send the end results, in a slash command. I think my reasoning for doing it like that, is because editting a message over was easier to do so at the time for me .
usually it adds the slash commands back instantly on my development bot, still waiting for it to re-register the commands. (Turns out the code was broken that was loading the modules, too)
🤔
Will give it an hour though to see if it's just discord being slow
how do i set the PaginatorMenu in the Paginator to be in the second row? paginator_menu.row = 2 doesnt do anything
the hour rule was removed like 2 years ago
I did not know this. 🤔
well then, it's still not registering the slash commands
are there at least no slash commands
i am able to edit a slash command respond like 3x back to back? if so how wo uld i
There's none, but there should be the kick, warn, mute, etc
Which is the issue now
.slashnoshow
Application Commands Not Showing Up?
- 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.
what is your bot’s invite link?
can someone help? :(
ill dm you it,
you can send it here without the “client_id”
tried this, on main bot with the same code, it picks up the commands.
On dev bot, not picking up at all
does the development bot have any commands
yes, in fact, 2 more commands than the main
is it bad to send it with the client id?
well, i mean, are there any commands appearing on discord
none at all
i wanted to know the permissions and scopes your invite link is using
do you use bot.sync_commands anywhere in your code
not that I know of, no
just checked, not in any files
where are you running this bot
on a VPS hosted by OVH
Because I'm curious, I'm going to quickly try something.. brb
ah.. that would be our problem:
Ignoring exception in on_connect
Traceback (most recent call last):
File "/home/ubuntu/.local/lib/python3.8/site-packages/discord/client.py", line 399, in _run_event
await coro(*args, **kwargs)
File "/home/ubuntu/.local/lib/python3.8/site-packages/discord/bot.py", line 1182, in on_connect
await self.sync_commands()
File "/home/ubuntu/.local/lib/python3.8/site-packages/discord/bot.py", line 738, in sync_commands
registered_commands = await self.register_commands(
File "/home/ubuntu/.local/lib/python3.8/site-packages/discord/bot.py", line 602, in register_commands
registered = await register("bulk", data, _log=False)
File "/home/ubuntu/.local/lib/python3.8/site-packages/discord/http.py", line 386, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 429 Too Many Requests (error code: 30034): Max number of daily application command creates has been reached (200)```
It's hit the limit for that bot. But when I put it on a new bot it instantly worked. So that'll work until the limit gets reset
another thing though.. @shell radish, I can't seem to get user commands to show for me at all. On any bot
nevermind, was reloading the wrong bot >.>
Shows up fine now!
i got a quick question, how could I give someone a role in a command?
heres the code i got for now
@bot.slash_command(description="For mods to verify people")
async def verify_user(
ctx: ApplicationContext,
user: Option(discord.User, "User you want to verify"),
):
if ctx.guild.roles[-5] <= ctx.user.roles[-1]:
verification_role = ctx.guild.get_role(1019808770630623252)
member = ctx.guild.get_member(user.id)
member.add_roles(verification_role)
res = f"{member.name} has sucessfully been verified"
else:
res = "You aren't allowed to do that"
await ctx.send_response(content=res, ephemeral=True)
in theory they have no roles currently so would there be a permission issue here?
What is that if clause supposed to do?..
thats irrelevant for now
its supposed to deal with mod perms and stuff
its a bit jank but works
- You don't need to get
member. You can just use ctx.author - You're not awaiting it
isnt ctx.author the person using the command?
also the await might be the issue
Didn't see.
Then you can use user.add_role?
Just typehint discord.Member
Instead of discord.User
how do i set the PaginatorMenu in the Paginator to be in the second row? paginator_menu.row = 2 doesnt do anything
Is it possible to know what guild a shard is handling. Also if I send a request to discord, which shard will send it (I am guessing the shard responsible for that guild) ? I cant find it in the doc
ooh I see. I was looking at the wrong place
I'm using py-cord==2.0.0b5 and randomly my bot broke out of nowhere.
This error makes no sense. Something about a sticker?
Why would this version randomly do this?
1. Uninstall discord.py or any other forks of discord.py you might have with the namespace discord.
python -m pip uninstall discord.py discord -y
2a. Install py-cord
python -m pip install py-cord
2b. Update py-cord
python pip install -U py-cord
Installing other builds:
Note: You need to have git installed. Use ?tag git to find out how to install git.
Updating the module to master branch (unstable):
pip install -U git+https://github.com/Pycord-Development/pycord
discord updated
But when I use py-cord it breaks everything
as in?
here
?
otherwise anybody can steal you bot
I reset it but my god they were fast af
How do they grab tokens that fast.. Luckily no damage happened.
no that's just me
Why did you add it to the github
so it is invalidated?
How does that work?
If you add a token there it gets invalidated?
yes
Can I have the link?
if your token is in any public github thing, it is reset
Ah Discord has a partnership with github?
not directly
class ReviewStringsManagementButtons(View):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs, timeout=None)
@discord.ui.button(
label="Approve",
style=discord.ButtonStyle.green,
)
async def approve_button_callback(self, button: discord.ui.Button, interaction: discord.Interaction):
await interaction.response.send_message("You clicked the approve button!", ephemeral=True)
self.stop()
@discord.ui.button(
label="Clarification",
style=discord.ButtonStyle.gray,
)
async def clarification_button_callback(self, button: discord.ui.Button, interaction: discord.Interaction):
await interaction.response.send_message("You clicked the clarification button!", ephemeral=True)
self.stop()
@discord.ui.button(
label="Reject",
style=discord.ButtonStyle.red,
)
async def reject_button_callback(self, button: discord.ui.Button, interaction: discord.Interaction):
await interaction.response.send_message("You clicked the reject button!", ephemeral=True)
self.stop()
await string_review_channel.create_thread(name=f"String Review | # {review.count_documents({}) + 1}", embed=embed, view=ReviewStringsManagementButtons())
Am I doing something wrong here? I feel like this is correct but it's not working (see video).
Any errors?
Nothing in my console, no
stupid question but the bot is running right?
yes
lmao
Nothing to do with persistence, I sent that message and attempted to click the buttons right after.
could you send a screenshot of this please? its all over the place on phone
thanks
can you try removing everything but print from a button? see what that does
that error is thrown because you stopped listening to the view
what do you mean?
same result
once you press one button, it stops listening to all of them
The print statements don't trigger on the first button press either
are you trying with a new embed each time?
Yes


