#Basic Pycord Help
1 messages · Page 17 of 1
Here's the context menus example.
o you beat me to it
Thx
xd
Why does Pycord use 'discord' as the module name? It's annoying to confuse it with other modules like discord.py, it should be 'py-cord' instead of 'discord', right?
It’ll be pycord in v3 if it ever gets released
You could change it or do
import discord as pycord
Can I get an answer on why my slash commands aren't working?
skill issue?
kill yo-
meanie
Nah but fr why 😭
wut commands are the problem?
I did everything it said in the docs
The one in cogs
Regular ones are working fine
its kinda hard to tell you why when you share no details or code
Ill send them wait
I'm getting a call
import discord
from discord.ext import commands
class Fun(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command()
async def ping(self, ctx):
await ctx.send(f"Pong! {round(self.client.latency * 1000)}ms")
@commands.slash_command()
async def ballbeater(self,ctx):
await ctx.respond("ballbeater")
@commands.user_command(name='Test2')
async def test2(self, ctx, user: discord.Member):
await ctx.respond(f'{user.mention} is cool')
@commands.Cog.listener()
async def on_ready(self):
print('Fun cog is ready')
def setup(client):
client.add_cog(Fun(client))
This is my cog code
The slash commands and context menus don't work
The cogs do get loaded
And prefix cmds work
is there no way to dm all members in a server w my bot?
you can, just iterate over all guild member
why commands.has_role won't work with bridge commands? is it only supported
prefixed commands? and how do i make it work with bridge
Yep. Or use @bot.event in the main file
Why are application commands not working?
.tag idw
Saying it doesn't work or asking what's wrong with this code is not helpful for yourself or others.
Describe what you expect and/or tried (with your code), and what isn't going right.
Please provide any errors you get for optimal assistance.
does discord IP Ban bots or smth? bots running fine on my Linux server suddenly all stopped working and all of them just log: discord.client INFO logging in using static token
the bots start without issues on my pc so they aren't banned or anything
Is pycord compatible with aiohttp >= 3.9?
Discord does not allow you to edit a channel several times in a short period of time. Is it possible to filter this out if Discord is currently blocking it?
Any help?
Nope, it’s server-side
But public bots can do that?
yes, they ban a certain IP
No, they just do it slowly
Well it worked again after a while, probably a temp ban cuz of some ratelimit issue
Happens when your code is shit IG
ah okay. Thank you
probably
When a user selects an option in a select menu and the bot responds to the interaction, the option they selected is still on their view. How would I be able to have discord not show the option still selected and show no options selected?
edit the message and put the view there again
thanks that works
Ok
is there a reason for my bot randomly restarting with no errors? the .py file is still running, on_ready is just being called again
i'm able to dm 2 users 1 file each and then it just restarts
cooldown of 7.5s between dms
sessions restart
its only happening when i'm running my task
every single time it dms 2 people
without timestamps that doesn’t say anything
the task runs every 5 minutes
sometimes it completes ("done", in the ss), sometimes it fails
task begins with "new update"
without providing the code for the task, it’s practically impossible to diagnose the issue
there could be other factors that cause a “restart” so to speak
yeah hold on im uploading the code
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.
figured out the cause
my giant for loop (going through a 100k+ length list of dictionaries) was timing out the bot as it was blocking for some reason
is there a reason async code run inside of a task would be blocking and cause the entire bot to freeze
im playing the game of "how many times can I fk around with my code and have it still not work" 😭
solved my problem, just reduced the amount of data i was iterating through
hello, on my journey of understanding pycord.
i was following the example:
channel = await guild.create_forum_channel('cool-channel')
but since guild.create_forum_channel() does not exist i tried using
@bot.slash_command(name="create_channel", description="")
async def create_channel(createchannelfunc):
await guild.Guild.create_category(guild,'test')
but this does not work erroring with
AttributeError: module 'discord.guild' has no attribute '_create_channel'
could a poor soul be helped out to be shown the answer?
i have looked and looked and have found no answer -_-
i even tried:
await bot.get_guild(guild.Guild.id).create_text_channel('test')
and i get this error instead:
AttributeError: module 'discord.guild' has no attribute 'create_text_channel'
What is createchannelfunc?
What are you trying to do? Create a channel?
It would be await ctx.guild.create_text_channel("cool-channel")
oh so referance the slash command 🤦♂️
right
sorry im stupid sometimes. its dumb bc pycharm doesnt auto fill any of that
at the slash commands its still ctx
;3
Github Copilot 
i use that and it acts dumb sometimes.
doing autofills that make no sense and dont work at all in c++ so i hardly use it there
you can create live templates with pycharm
oh really ill check that out!
interesting
Need some suggestions
Needing to send a message from an interaction to say how many votes are remaining, but then that same interaction also needs to be able to edit the message for a new image. These are done at two seperate times and I am aware you can't edit the same interaction twice
You can edit the same interaction twice
Just use interaction.edit_original_response
Oh, interesting. I was using interaction.response.edit_message so I guess that’s why. Thanks
You use that if you're responding
If you need a second edit/response, you use what I said
Can someone show me an example on how to make a slash command in a cog, because I followed the docs and the GitHub guide and neither work?
.idw
Saying it doesn't work or asking what's wrong with this code is not helpful for yourself or others.
Describe what you expect and/or tried (with your code), and what isn't going right.
Please provide any errors you get for optimal assistance.
I tried everything I got in, in the docs and the GitHub guys but the command just dosent appear.
No errors
Prefix cmds work
.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.
why does it tell me that i have to enter a valid number? i have int inside?
You'll have to use a string instead and then convert to an int. Discord doesn't support long ints
Thank you
semi-related to PyCord, but
what would be the most optimal way to like, export a list of User IDs into a list which my bot can sample and add to at any time
and won't lose it when it reboots
SQLite?
I want to make(upgrade lmao) a whitelist system, where I get a prompt whether to allow somebody in or deny them
and if I allow them, add their user ID to the whitelist
all databases can do the job. Just use which one you are most familiar with
and if I'm not familar with any?
what would you recommend?
SQLite seems... vaguely nice? but I've never really done anything with db
my dbs were always just plain txt files lmao
Does anyone know how I can send the whole thing if I use interaction.defer() beforehand?
await paginator.respond(interaction, ephemeral=True)```
you can't
But you can simply:
await interaction.response.defer(ephemeral=True)
And then:
await paginator.respond(interaction, ephemeral=True)
Use without problems 🙂
Just tested it 🙂
The docs also state the following:
Paginator.respond() is used to send an interaction response (or followup) message with the paginator.```
I misread the question 💀
why is await reaction.users() so slow
i only want a list of user ids who reacted a certain reaction on a message
ask discord lol
SQLite is perfect for beginners
Is there any way to access response headers with Pycord? I need to better understand individual rate limits.
If not, is there some other way to understand specific rate limits such as ephemeral interaction responses?
can some help me with this error
Ignoring exception in on_connect
Traceback (most recent call last):
File "/home/container/.venv/lib/python3.11/site-packages/discord/client.py", line 378, in _run_event
await coro(*args, **kwargs)
File "/home/container/.venv/lib/python3.11/site-packages/discord/bot.py", line 1164, in on_connect
await self.sync_commands()
File "/home/container/.venv/lib/python3.11/site-packages/discord/bot.py", line 719, in sync_commands
registered_commands = await self.register_commands(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/.venv/lib/python3.11/site-packages/discord/bot.py", line 588, in register_commands
data = [cmd["command"].to_dict() for cmd in filtered_deleted]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/.venv/lib/python3.11/site-packages/discord/bot.py", line 588, in <listcomp>
data = [cmd["command"].to_dict() for cmd in filtered_deleted]
^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/.venv/lib/python3.11/site-packages/discord/commands/core.py", line 1164, in to_dict
"options": [c.to_dict() for c in self.subcommands],
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/.venv/lib/python3.11/site-packages/discord/commands/core.py", line 1164, in <listcomp>
"options": [c.to_dict() for c in self.subcommands],
^^^^^^^^^
AttributeError: 'BridgeExtCommand' object has no attribute 'to_dict'```
this is the script:
group = bot.create_group("comandos-de-staff", "Comandos para el personal del servidor")
group.add_command(bot.get_command("warn"))
group.add_command(bot.get_command("unwarn"))
group.add_command(bot.get_command("warnings"))
group.add_command(bot.get_command("imagewarn"))
group.add_command(bot.get_command("mute"))
group.add_command(bot.get_command("unmute"))
bot.add_application_command(group)
Why do you create the Applikation command group like that?
because it used bridge commands and that came up searching on the internet
At the py-cord docs?
nope
from here:
https://guide.pycord.dev/extensions/bridge
https://stackoverflow.com/questions/74790979/pycord-how-to-make-subcommands-or-slashcommands-groups
https://guide.pycord.dev/extensions/commands/groups
Let me see if I guess, should I look for it?
If you want to use a bridge group yea
The reference manual that follows details the API of Pycord’s bridge command extension module. Bots: Bot: Methods def add_bridge_command,@ bridge_command,@ bridge_group. AutoShardedBot: Commands: B...
A question, if I want to make a command appear in the !help command in a category that is not in a category, how can I do it?
You mean with the build in help one?
if you look here:
Use `@ElBotDelYonny help [command]` for more info on a command.
You can also use `@ElBotDelYonny help [category]` for more info on a category.
__**Excepsiones**__
modo_molestar
__**No Category**__
8ball avatar cancel_outro clear desilenciar desilenciar_all embed_creator fijar grafica help imagewarn info jumbo mute outro ping randomcolor randomuser rank record rps say server servericon silenciar silenciar_all stock stop_recording top translate unmute unwarn user-info warn warnings xp_remove
Here it shows the !help command of my bot but it only shows the cog commands in one category
What I want to know is how to put the commands that are in the category called: No Category in a category, which says that it is not in a category, this is because the commands are integrated into the main.py file
not in a cog file
yea, that is the build in help command for prefix commands and I dont know how to use it x3
At least do you know where or what part of the pycord docs it is to try to see how it is used?
I usually create a full custome one at my bots
lemme see if I can find it
k
Pycord's commands extension comes with a built-in help command. In this guide, we will take a look at them as well as learn how to create your own. Let's dive in!
:v
Ignoring exception in on_command_error
Traceback (most recent call last):
File "C:\Users\Angel\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 178, in wrapped
ret = await coro(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Angel\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\help.py", line 858, in command_callback
return await self.send_bot_help(mapping)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Angel\Downloads\yonny\main.py", line 44, in send_bot_help
filtered = await self.filter_commands(commands, sort=True)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Angel\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\help.py", line 604, in filter_commands
for cmd in iterator:
File "C:\Users\Angel\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\help.py", line 584, in <lambda>
else filter(lambda c: not c.hidden, prefix_commands)
^^^^^^^^
AttributeError: 'BridgeCommand' object has no attribute 'hidden'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Angel\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 378, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Angel\Downloads\yonny\cogs\excepsiones.py", line 65, in on_command_error
raise error
File "C:\Users\Angel\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 347, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Angel\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 950, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Angel\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 187, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'BridgeCommand' object has no attribute 'hidden'
I tried to investigate a solution but it seems that it is a problem in the library
this is what i found
This error is occurring because the filter_commands method in your send_bot_help function is trying to access the hidden attribute of a command object, but it appears that the ‘BridgeCommand’ object does not have this attribute.
The best part is that I used the example that the website you gave me gave me.
i mean stable literally doesn't have that so ig it's working
you probably want master instead of stable
also bookmark bar (if you care)
oooh I see thank you !
filtered = await self.filter_commands(commands, sort=True)
I am having problems with this simple line that always returns the same error
yes, because the example is for text-based commands only and not bridge commands
So how do I do it for bridge commands? 
you can probably override the filter_commands method with one that would work for bridge commands
it didn't work for me 
class MyNewHelp(commands.MinimalHelpCommand):
async def filter_commands(self, commands, *, sort=False, key=None):
"""Returns a list of commands that meet the conditions specified by the predicate and sorter."""
if sort and key is None:
key = lambda c: c.name
iterator = commands if self.show_hidden else filter(lambda c: not c.hidden, commands)
# Verifica si el comando es una instancia de 'BridgeCommand' y si tiene el atributo 'name'
return sorted(filter(lambda c: isinstance(c, commands.BridgeCommand) and hasattr(c, 'name') and self.verify_checks(c), iterator), key=key)
async def send_bot_help(self, mapping):
destination = self.get_destination()
for category, commands in commands_dict.items():
filtered = await self.filter_commands(commands, sort=True)
command_signatures = [self.get_command_signature(c) for c in filtered]
emby = discord.Embed(description=f"{category}: {command_signatures}")
await destination.send(embed=emby)
I get almost the same error
Ignoring exception in on_command_error
Traceback (most recent call last):
File "C:\Users\Angel\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 178, in wrapped
ret = await coro(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Angel\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\help.py", line 861, in command_callback
return await self.send_bot_help(mapping)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Angel\Downloads\yonny\main.py", line 1870, in send_bot_help
filtered = await self.filter_commands(commands, sort=True)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Angel\Downloads\yonny\main.py", line 1865, in filter_commands
return sorted(filter(lambda c: isinstance(c, commands.BridgeCommand) and hasattr(c, 'name') and self.verify_checks(c), iterator), key=key)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Angel\Downloads\yonny\main.py", line 1862, in <lambda>
iterator = commands if self.show_hidden else filter(lambda c: not c.hidden, commands)
^^^^^^^^
AttributeError: 'BridgeCommand' object has no attribute 'hidden'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Angel\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 378, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Angel\Downloads\yonny\cogs\excepsiones.py", line 65, in on_command_error
raise error
File "C:\Users\Angel\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 347, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Angel\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 950, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Angel\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 187, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'BridgeCommand' object has no attribute 'hidden'
you can probably override the filter_commands method with one that would work for bridge commands
I think I'm going to have to give up since I've been trying for a while to do something that was so easy to return to cog command but as a consequence I would have to write the code again in cog command
.
why persistent view still expired?
class Verify(discord.ui.View):
def __init__(self, bot):
self.bot = bot
super().__init__(timeout=None)
@discord.ui.button(custom_id="unranked_button", label="Unranked")
async def callback_1(self, button, interaction):
role = discord.utils.get(interaction.guild.roles, name="Unranked")
await interaction.user.add_roles(role)
did you add the class to a add_view to the bot?
no
;3
I have slash commands in main.py file that work and i believe I invited the bot with applications.commands
.docs
Get a doc section easily
Flags
d- the directory, most likely to bedata_classesfor most things,indexby default
dcl, docslink, docs
.docslink
Get a doc section easily
Flags
d- the directory, most likely to bedata_classesfor most things,indexby default
dcl, docslink, docs
MailTM - Tempmail API not working
Why would this be a pycord issue when the issue is from another library
I'm using pycord in this code

But the issue isn't pycord
And the error is kinda self explanatory

why commands.has_role won't work with bridge commands? and how do i make it work with bridge
#international-chat

How it doesnt?
I thought I was on a German server sry xd
lol
idk, i tried it, the command can be used without the role, when i changed it to prefixed command, the role is required
Then you could just implement the check manually
It's literally two lines of code? 
Hi, does anyone know how to exclude users from a cooldown?
My cooldown looks like this
@commands.cooldown(1, 30, commands.BucketType.user)
You will need to create a custom cooldown
How can I do that?
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - Pycord-Development/pycord
Thx 
I am trying to get the oldest_first in the audit logs:
async for entry in guild.audit_logs(limit=None, after=object_id,
oldest_first=True, action=discord.AuditLogAction.member_role_update):
print(f'{entry.created_at}')
But it is returning the most recent first ...
2023-12-28 19:49:21.731000+00:00
2023-12-28 19:49:18.526000+00:00
2023-12-28 19:49:14.620000+00:00
2023-12-28 19:49:11.040000+00:00
are you on master, rc, or stable?
I am on py-cord-dev==2.5.0rc5
try seeing if this sae behavior happens on master. If so, please file a bug report on github
In the mean time I just did:
entries = await guild.audit_logs(limit=None, after=object_id,
oldest_first=True, action=discord.AuditLogAction.member_role_update).flatten()
entries.sort(key=lambda val: val.created_at)
add this comment to the issue so others can also find it easily
yeah but it is not a real fix, more a work around
hey, is there a given way through pycord to access the /gateway/bot endpoint?
not publically documented, so you can make your own requests
okay, just using the token and aiohttp?
Yes
okay, thx
is it should be placed in on_ready?
yea
How can I get a slash command user's profile pciture URL
ctx.author's pfp
I tried avatar_url, doesn't work
^ got answerd here #1190258685532966983
does persistent view uses api request to discord? if want to make selfrole system is it necessary to keep that message only in one channel? so if i want to change the selfrole location i need to delete the old message
just to prevent rate limiting
#1190309845459533865
I highly recommend using onboarding over any custom solution unless onboarding doesnt meet your needs at all
Any thoughts why an interaction_check isn't working on a modal?
class bioModal(discord.ui.Modal):
def __init__(self, buttonInteraction, *args, **kwargs, ) -> None:
super().__init__(*args, **kwargs)
self.buttonInteraction = buttonInteraction
async def interaction_check(self, interaction: discord.Interaction):
print(interaction.user.id)
print(self.buttonInteraction.user.id)
if interaction.user.id == self.buttonInteraction.user.id:
return True
else:
return False
async def callback(self, interaction: discord.Interaction):
await interaction.response.send_message(
"view", view=MyView(),
ephemeral=True)```
The print statements aren't running so I think it's being skipped over for some reason
onboarding? what is that?
Modals don't have interaction checks
Don't know why you'd need one? Modals just show to the user that receives it
Trying to work through the suggestion here: #1187068274102509632 message
Well, modals don't have interaction checks
discord community server feature
which de facto replaced self roles in every bot
hmm, i use bots because I'm creating complex selfroles
like what
Hi there!
Since I've added a verification system to an API I've been getting this error, any ideas?
Ignoring exception in view <VMonthlyPass timeout=None children=7> for item <BVoteVerify style=<ButtonStyle.success: 3> url=None disabled=False label='Vérifier' emoji=<PartialEmoji animated=False name='2️⃣' id=None> row=1>:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.11/site-packages/discord/ui/view.py", line 421, in _scheduled_task
await item.callback(interaction)
File "/home/container/addons/EAVote/functions/buttons/buttonVoteVerify.py", line 111, in callback
await interaction.response.send_message(embeds=embeds, ephemeral=True, delete_after=120)
File "/home/container/.local/lib/python3.11/site-packages/discord/interactions.py", line 904, in send_message
await self._locked_response(
File "/home/container/.local/lib/python3.11/site-packages/discord/interactions.py", line 1198, in _locked_response
await coro
File "/home/container/.local/lib/python3.11/site-packages/discord/webhook/async_.py", line 220, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
It appears completely at random, so I don't really understand...
How can I check if my bot is already connected to a vc or not
is there any way?
Probably sometimes your request takes longer to process and you are responding after the 3 seconds.
Hello I'm Getting an issue.. ctx.content always returning an empty string
What is ctx.content?
Documentation page for adding dropdown list to embed
what
That attribute doesn't exist
bro thinks this is chatgpt
fr
Thank you, yall are so helpful
Here's the dropdown example.
truly an impossible feat
that's enough
bing chat, thats why
imagine getting trolled for asking help in the one and only support server
Man, use google
Support is for actual issues not for "pls give me this publicly accessible website link"
There's nothing wrong with not knowing where to find examples, but ok
womp womp
you know how hardcore google regionlocks stuff
even their new gemini model for bard is region locked
I expect everyone seeking support to at least have done a google search with what they want, especially if all they need is a page in the docs
@edgy nest @sage tendon #general
how to add description to parameters, like if I have a slash command:
#not an actual command just example
@client.slash_command()
async def test(ctx, answer: str):
await ctx.respond(f'cool opinion about {answer}')
How can I add a description when we are inputting answer.
You typehint discord.Option()
.rtfm discord.Option
Works thanks
hey, what is the best way to make a handler that checks whether the user is on a mongodb blacklist or not every time a slash command is executed. if so, the bot should only send that it is on a blacklist.
i had just tried this with the on_application_commmand, but i only get problems with my on_application_command_error event. what is the best way to do this?
Is it not possible to use Discord timestamps in an embed footer?
You can create a custom check:
def custom_check():
async def predicate(ctx: Context):
# Do something here
return check(predicate)
@custom_check()
async def function()
And you can catch the error here and then output a message:
isinstance(error, discord.CheckFailure)```
You should set the timestamp of the embed with https://docs.pycord.dev/en/stable/api/data_classes.html#discord.Embed.timestamp. This will only display as a time (IE not relative) directly to the right of the footer.
under the @slash_command
https://max1385.no-friends.xyz/oCDHZrHc.png
I dont think it matters but try it an see. Also if you do this you should make a cache so you are not constantly calling the DB if someone is "spamming" commands
but wouldn't that just work with on_application_commmand?
Yeah, I guess you are right, there is not a huge difference. What are you trying to avoid?
Or what is the issue with on_application_command_error
I have a MongoDB collection with bans in it, i.e. blacklisted users who are no longer allowed to use slash commands from the bot.
I had already tried this once, but then had problems with my normal error handler. Always had the error that the interaction had already been answered.
Do you still have this old handler avalible for me to help debug?
I will be back in ~20 to help you fix your error handling. As that is the best way other than just putting a function at that start of every command.
to make commands work with prefix as well as when bot is mentioned we use the when_mentioned_or function when creating the bot object but if i just have to make some commands which have the mentioned at property what should i do according to the best practice
Yes, I'm looking for in few min
I do not know of a way to set prefixes per command ( that is just not how the library is set up) However once the command is found you can check if the prefix is a mention and not run the command if it is with https://docs.pycord.dev/en/stable/ext/commands/api.html#discord.ext.commands.Context.prefix You could even put this in a custom check if you want
oh so i check the prefix of the command when its invoked and then if a want to make it a command in which mention should not be allowed i can just see if the prefix used for the commands was the mention of the bot or not .. i guess this will work and i suggest to add something to the library which makes it possible to set per command prefixes
import discord
from discord.ext import commands
import json
from mongodb import db
# json config laden für die verschiedenb parameter in den embeds
def load_config():
with open("config.json", "r", encoding="utf-8") as f:
config = json.load(f)
color = int(config["color"], 16)
footer_text = config["footer-text"]
return color, footer_text
class ErrorHandler(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.db = db
self.collection = self.db['bans']
@commands.Cog.listener()
async def on_application_command_error(self, ctx, error):
# Embeds
color, footer_text = load_config()
avatar = self.bot.user.display_avatar.url
embed = discord.Embed(
description=f"Unfortunately, the following error occurred when executing the (slash) command: {error}",
color=color
)
embed.set_footer(text=footer_text, icon_url=avatar)
if isinstance(error, commands.CheckFailure):
# Check if the interaction is still valid before responding
if ctx.interaction:
await ctx.respond(embed=embed, ephemeral=True)
return
# Check if the interaction is still valid before responding
if ctx.interaction:
await ctx.respond(embed=embed, ephemeral=True)
raise error
@commands.Cog.listener()
async def on_application_command(self, ctx):
user_id = ctx.author.id
if self.collection.find_one({"user_id": user_id}):
await ctx.respond("you are banned", ephemeral=True)
return False
return True
def setup(bot):
bot.add_cog(ErrorHandler(bot))
unfortunately i didn't find the code from before, but i have now created a new one. the user id, with which i execute the command, is on the blacklist, but still no error or other grade appears, the blacklisted user can execute the command just like that.
channel = self.bot.get_channel(result[3])
if channel is None:
channel = await self.bot.fetch_channel(result[3])
this returns a: NotFound: 404 Not Found (error code: 10003): Unknown Channel
i coppied the code into a notmal prefixed command and coppied the id from the db and it works fine
Returning True/False within a event does not effect the result of the command. Raising an error instead might. I am not 100% sure. But you can try it.
IE return False -> raise YourError and catch that in the on command error
But it does not work in a slash comand?
with what kind of option?
Make sure the value is an int and not a string
wrapped hte result[3] with int() and still returns the same error
but I don't have an error here that I can raise, do I? I mean, otherwise I would have to write error at the top as well
async def get_channel(self, channel_id: int):
channel = self.bot.get_channel(channel_id)
if channel is None:
channel = await self.bot.fetch_channel(channel_id)
print('fetch')
print(channel)
if channel is not None:
print('get')
print(channel)
coppied the channelID from the db and it returns get then the channel name
in the same cog file aswell
the perfixed command for testing btw
You would have to create your own error or just choose one that already exists. You would have to make another isinstace tho.
Can you show the slash command that it is not working for
@medbay.command(name="return", description="Returns a user from the medbay")
@discord.option(name="member", description="The member to return from the medbay", input_type=discord.Member,
required=False)
async def _return(self, ctx: discord.ApplicationContext, member: discord.Member = None):
if member is None:
member = ctx.author
db, cursor = await connect_to_db()
await cursor.execute(
f"SELECT UserID, endDate, Status, channelID FROM medbay WHERE UserID = {member.id} AND (Status = {1} OR Status = {3})")
result = await cursor.fetchone()
if result is None:
await ctx.respond(f"No active medbay ticket open for member: {member.display_name}")
await cursor.close()
await db.close()
return
print(result[3])
# channel = await self.get_channel(result[3])
channel = self.bot.get_channel(result[3])
if channel is None:
channel = await self.bot.fetch_channel(result[3])
if result[2] == 1:
await cursor.execute(f"UPDATE medbay SET Status = {2} WHERE UserID = {member.id} AND Status = {1}")
await db.commit()
await cursor.close()
await db.close()
await ctx.respond(f"Returned {member.display_name} from medbay")
elif result[2] == 3:
end_date = datetime.datetime.strptime(result[1], "%d-%m-%Y")
days_late = (datetime.datetime.today() - end_date).days
new_end_date = datetime.datetime.today().strftime("%d-%m-%Y")
print(new_end_date)
await cursor.execute(
f"UPDATE medbay SET endDate = {new_end_date}, Status = {4} WHERE UserID = {member.id} AND Status = {3}")
await db.commit()
await cursor.close()
await db.close()
await ctx.respond(f"Returned {member.display_name} from medbay. {days_late} days late")
await channel.delete()
can you add print(type(result[3]))
something like that?
import discord
from discord.ext import commands
import json
from mongodb import db
class UserBanned(commands.CommandError):
pass
# json config laden für die verschiedenen parameter in den embeds
def load_config():
with open("config.json", "r", encoding="utf-8") as f:
config = json.load(f)
color = int(config["color"], 16)
footer_text = config["footer-text"]
return color, footer_text
class ErrorHandler(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.db = db
self.collection = self.db['bans']
@commands.Cog.listener()
async def on_application_command_error(self, ctx, error):
# Embeds
color, footer_text = load_config()
avatar = self.bot.user.display_avatar.url
embed = discord.Embed(
description=f"Unfortunately, the following error occurred when executing the (slash) command: {error}",
color=color
)
embed.set_footer(text=footer_text, icon_url=avatar)
if ctx.interaction:
await ctx.respond(embed=embed, ephemeral=True)
raise error
@commands.Cog.listener()
async def on_application_command(self, ctx):
user_id = ctx.author.id
print(f"User ID: {user_id}")
if self.collection.find_one({"user_id": user_id}):
print(f"User {user_id} is banned.")
raise UserBanned()
return True
def setup(bot):
bot.add_cog(ErrorHandler(bot))
<class 'int'>
if isinstance(error, UserBanned): you would want to add this and just pass so that it does not actually raise the error to your console but yes. Also the return True at the bottom is not needed.
import discord
from discord.ext import commands
import json
from mongodb import db
class UserBanned(commands.CommandError):
pass
# json config laden für die verschiedenen parameter in den embeds
def load_config():
with open("config.json", "r", encoding="utf-8") as f:
config = json.load(f)
color = int(config["color"], 16)
footer_text = config["footer-text"]
return color, footer_text
class ErrorHandler(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.db = db
self.collection = self.db['bans']
@commands.Cog.listener()
async def on_application_command_error(self, ctx, error):
# Embeds
color, footer_text = load_config()
avatar = self.bot.user.display_avatar.url
embed = discord.Embed(
description=f"Unfortunately, the following error occurred when executing the (slash) command: {error}",
color=color
)
embed.set_footer(text=footer_text, icon_url=avatar)
if ctx.interaction:
await ctx.respond(embed=embed, ephemeral=True)
if isinstance(error, UserBanned):
return
raise error
@commands.Cog.listener()
async def on_application_command(self, ctx):
user_id = ctx.author.id
print(f"User ID: {user_id}")
if self.collection.find_one({"user_id": user_id}):
print(f"User {user_id} is banned.")
raise UserBanned()
def setup(bot):
bot.add_cog(ErrorHandler(bot))
Sorry I dont know why this is. The docs say that your error only occurs when the channel ID is not valid. Something must be going wrong with the results from your database.
what pacakge are you using to access the DB?
aiosqlite
@lapis dock Unfortunately, this does not work. The user is on the banlist, but he can execute any command just like that. And I don't get any other errors in my console.
try changing @commands.Cog.listener() to @bot.event()
okay, I will do it later 😄
i removed the status = 3 peramiter in the query and it worked, must have been accessing a different record
thanks for the help :)
I hope that works for you if not try to make custom check, simple example you can convert to app commands https://gist.github.com/Harukomaze/a81d60ba7f3c8dbf6bcbfe0df2decbfc
hey, is there a way to get the raw member as json format? like the raw response from discord is?
Make a request by yourself?
but I then do 2 requests for 1 user, my idea is to send the raw data to a dashboard, but I could also build my own jsons using only the data I need in the dashboard
idk, this also doesn't work.
class Blacklisted(CheckFailure):
pass
class UserBanned(commands.CommandError):
pass
@bot.event
async def on_application_command(ctx):
user_id = ctx.author.id
print(f"User ID: {user_id}")
if db['bans'].find_one({"user_id": user_id}):
print(f"User {user_id} is banned.")
raise UserBanned()
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, Blacklisted):
return await ctx.send("du kannst nichts mehr benutzen.")
elif isinstance(error, UserBanned):
return await ctx.send("You are banned from using this command.")
else:
await bot.handle_error(ctx, error)
this is in the main.py file
nice mix of languages
yes
try using on_interaction
now i'm not getting any more interaction answers.
https://max1385.no-friends.xyz/gK2TekxF.png
did you read the footnote regarding the event?
do you mean in the docs?
you need to put this at the bottom of your event where things that should be triggered will trigger
you mean this?
class Blacklisted(CheckFailure):
pass
class UserBanned(commands.CommandError):
pass
@bot.event
async def on_interaction(interaction):
user_id = interaction.user.id
print(f"User ID: {user_id}")
if db['bans'].find_one({"user_id": user_id}):
print(f"User {user_id} is banned.")
raise UserBanned()
await bot.process_application_commands(interaction)
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, Blacklisted):
return await ctx.send("du kannst nichts mehr benutzen.")
elif isinstance(error, UserBanned):
return await ctx.send("You are banned from using this command.")
else:
await bot.handle_error(ctx, error)
ig so
puhh, idk, the commands work again, but a blacklisted user can still execute the commands...
no idea
does the if statement work
which one do you mean?
if db['bans'].find_one({"user_id": user_id}):
idk how your DB is organized
the user id is an int, but you saved it as a string
so you should convert it a string then search for it
class Blacklisted(CheckFailure):
pass
class UserBanned(commands.CommandError):
pass
@bot.event
async def on_interaction(interaction):
user_id = str(interaction.user.id)
print(f"User ID: {user_id}")
if db['bans'].find_one({"user_id": user_id}):
print(f"User {user_id} is banned.")
raise UserBanned()
await bot.process_application_commands(interaction)
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, Blacklisted):
return await ctx.send("du kannst nichts mehr benutzen.")
elif isinstance(error, UserBanned):
return await ctx.send("You are banned from using this command.")
else:
await bot.handle_error(ctx, error)
Now the prints are going through, but I still get this little error:
User ID: 1038849770380345457
User 1038849770380345457 is banned.
Ignoring exception in on_interaction
Traceback (most recent call last):
File "C:\Users\Max\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 378, in _run_event
await coro(*args, **kwargs)
File "c:\Users\Max\PycharmProjects\Vysion\main.py", line 67, in on_interaction
raise UserBanned()
UserBanned
This is how it would work now.
is there a way to add alises like this one ["np add"] ... basically which have a space between them
?
would i have to make a command group ?
you forgot the application it should be on_application_command_error
I have that in my handler file. Can I delete it in the main file, right?
If i understand what you mean yes
is there like a command mention
like example if they click on this <#command> it runs the command?
.slashmention
</full name:ID>
thanks
it doesn't run the command, but puts it in their chat
....?
without making a group is it not possible to make a command like "np add"
without using the on message event ofcurse
If it does not work normally than no. There is not a special work around to make it work without changing the library internals. Are you trying to make np default to the add mode unless otherwise specified or something?
is there an upper limit to guild.fetch_members?
There should not be.
im adding members to a db. matches the display name to a regex and if theres a match it adds the member to the db but there are some members missing that should be added
Are you sure it is not an issue with your regex?
Also make sure you are using the right name not that there is user name, display name, nickname, etc
ironically some of the ones missing were tested with the regex
defiantly the right one (display_name)
pattern = r"^([A-Z0-9]{2,4}) ([A-Z][a-z]+) ([A-Z]{1,2}-(?:[0-9]+|(?:\d-\d+\/\d+)))$"
async for member in ctx.guild.fetch_members(limit=12000):
print(counter, member.display_name)
if re.match(pattern, member.display_name):
name_info = member.display_name.split(" ")
RANK = name_info[0]
NAME = name_info[1]
DESG = name_info[2]
try:
await cursor.execute(
f"INSERT INTO Members (ID, Rank, Name, Designation) VALUES ({member.id}, '{RANK}', '{NAME}', '{DESG}')"
)
counter += 1
except IntegrityError:
pass
the main part of the command
?tag sqli
SQL Injection is a technique used by attackers to interfere with and alter queries that an application makes to its database via input data. A vulnerability to this exploit can lead to attackers being able to read sensitive data, modify existing data (Insert/Update/Delete), perform administrative operations on your database and in some cases even issue commands directly to the operating system of the server.
More information on SQL Injection
w3schools, owasp.org
To avoid SQL Injection vulnerability, you should never directly merge or concatenate data into an SQL query through string operations (f-strings, + operator, string interpolation with %, etc.). Always use the parameterized queries included with the library you are using.
Examples of parameterized queries for popular libraries
psycopg2, asyncpg, sqlite3, mysql
side-note
is there a way to reload the code of the bot like push changes without restarting the bot/server, without using a cog or do i need to use cogs
what exactly this take in consideration and what it does not. For exemple I found that it take in considerations the admin roles
you can try putting bot.run() in a loop, then creating a task with tasks.loop() decorator that'll check if files are changed and running bot.close() if so
discord.ActivityType.custom isn't working? when i try like watching it works fine but custom just don't
hmmm thx
for the get_prefix function in which i get the prefix from a database made in aiosqlite should i just make a single conn and reuse it since it will be triggered on every message
or i should create conn easch time ?
if i have seperate error handeler for a command using @commandname.error
the command gives the error to it but it also raises it on the on_command_error cant we prevent this since for some commands we need specific error handelers
would i have to specifically chekc on the on_command_error that if the command has its on_error already or not
async def on_command_error(self, ctx: Context, error: CommandError) -> None:
if ctx.command.on_error:
return```
which version of pycord do you use?
how do you get the amount of pins in a channel?
I essentially want a simple if statement
if pinamount == 50:
print("can't pin")
else
pin()
does this work?
pinlist = channel.pins()
pincount = pinlist.count()
# get the number of pins in a channel
pins = len(await channel.pins())
oh ty
oh, with justm messages, message author etc. can you get a channel?
hey wsg!
i recently reset my pc
and im unable to install pyc again
the installation fails at 'aiohttp build wheel'
note: This error originates from a subprocess, and is likely not a problem with pip.
ERROR: Failed building wheel for aiohttp
Failed to build aiohttp
ERROR: Could not build wheels for aiohttp, which is required to install pyproject.toml-based projects
Building wheels for collected packages: aiohttp
Building wheel for aiohttp (pyproject.toml) ... error
error: subprocess-exited-with-error
× Building wheel for aiohttp (pyproject.toml) did not run successfully.
│ exit code: 1
╰─> [110 lines of output]```
message.channel
what python version are you on
latest 3.12 or sum
i installed py again yesterday
downgrade please
some libraries didn't yet update to 3.12
yeah 3.11 works fine
yeah
alright, tysm!
np
yeah, I have the same problem.
How can i create/edit/delete channels using the bot?
Look at the methods of https://docs.pycord.dev/en/stable/api/models.html#discord.Guild for how you can create channels.
An abstract base class(also known as an abc) is a class that models can inherit to get their behaviour. Abstract base classes should not be instantiated. They are mainly there for usage with isinst...
and to edit you need to have a channel object and just run edit
try updating to new ver (uninstall pycord and install py-cord-dev; see #library-updates)
you too, if you have old ver
what version do you have if it doesn't work for you either?
I don't even use it, I'm just telling you to update since that could fix the bug
oh, sorry. I meant him
Due to some issue with uploading a new version to pypi we made a temporary version called py-cord-dev it is just as stable as 2.4. In the future we will switch back to using py-cord
^
though some bugs might've been fixed already
stable obv doesn't mean no bugs at all
okay, then I'll try
I use it too
yeah
yes
how i can get the ping down?
get better internet lol
well, where is your bot hosted
wdym?
I mean, the best way to get better ping is to move closer to the host
yea, i was gonna get to that lol
getting better internet does help, but the difference generally isn't large
the physical location where your code for your bot runs
thats a good question
lol
i am using the free one of course
There are about 30 ways i could tell you that can host your bot for free
But how high is the bot's ping anyway
like your mom's house?
121.179 ms
thats not really much for a bot
good
anything below 300 is fine
@sinful juniper I think that bug was fixed in master
?Tag install
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
I will try it soon
status is not a user attribute
also legally, the people you are taking the status from should consent to have their data being collected
this isn’t a problem until bot verification, but something to note
hey, any idea why my message command isn't appearing, nor does the ping command?
@bot.slash_command(name="ping", description="Check if the bot is alive.")
async def ping(ctx):
ctx.respond(f"🏓 Pong! at `{bot.latency()}ms`")
@bot.message_command(name="Unpin")
async def unpin(ctx, message=discord.Message):
link = message.jump_url
caller = ctx.author
caller = caller.global_name
victim = message.author
victim = victim.global_name
channel = message.channel
if message.pinned:
await ctx.respond(f"{caller} Unpinned message {link} by {victim}.")
await message.clear_reaction("📌")
await message.unpin()
else:
await ctx.respond(f"{caller} Can't unpin this message, as that message isn't pinned!", ephemeral=True)
the discord api is slow to deploy new commands or update their informations
just wait a bit
yep
Generally the API is fast about it now. Try the solutions below if it still does not work
.tag 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.
how to add description to an slash's option in slashcommandgroup? i don't find it in docs
I take it you wish to add a description to a group?
You can add a description to a group when creating them
https://docs.pycord.dev/en/stable/api/clients.html#discord.Bot.create_group
Bots: Attributes activity, allowed_mentions, application_flags, application_id, auto_sync_commands, cached_messages, cogs, debug_guilds, description, emojis, extensions, get_command, guilds, intent...
bot.create_group("name", "description")
nope
i mean add description to option
async def example(ctx, arg)
add a description into "arg" argument
in slash
oh
wait are you using the @option decorator or not?
because this might be of interest to you then; https://github.com/Pycord-Development/pycord/blob/master/examples/app_commands/slash_options.py
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - Pycord-Development/pycord
worked
thnk u
nope
maybe i should try that
@lapis dock I have now installed pip install -U git+https://github.com/Pycord-Development/pycord and it's working now in my code editor.
probably, option descriptions always were weird, which is why I decided to use the decorators
I have to install this on my host too, don't I?
yes
Master should be stable as of now
Hey! I have some questions! Can anyone tell me how to make a command be able to run before the same command's first usage if finished? (My wordings bad so lemme explain)
Let's say i have a command that takes some time, and i used the command >long_command. before it returns me a result, i want to use >long_command again, but when i do, the code waits for the first one to return a result first, and then starts the second one. I want to make it more efficient by running both of them immediately once the command is recieved, so instead of waiting 2 long commands, i save some time buy running them in parallel. Any way i can do that? Thank you!
If you are using async properly this sohuld not happen. You need to make sure that you have no blocking code in your command. If you need help finding the blocking code send it here and I will help.
Some common blocking functions: time.sleep should be asyncio.sleep. Also the requests library is blocking you should use aiohttp or httpx
@bridge.bridge_command(
name="imagine",
description="Make pictures with OpenAI's image generation AI: Dall-E!",
help="Create gorgeous pieces of art using OpenAI's famous Dall-E!",
aliases=["dall","img","dalle","image"],
)
async def _bing_img(self, ctx: Context, *, prompt: str):
await ctx.defer()
windows = os.name in ('nt', 'dos')
if windows: service = Service('C:\chromedriver-win64\chromedriver.exe')
options = Options()
#options.add_argument('--headless=new')
if windows: options.add_argument("--user-data-dir=C:\\Users\\Administrator\\Desktop")
else: options.add_argument("--user-data-dir=/home/ubuntu/botpp/chromeprofiles/")
options.add_argument("--profile-directory=Profile 4")
if windows: driver = webdriver.Chrome(service=service, options=options)
else: driver = webdriver.Chrome(options=options)
self.driver = driver
prompt = ''.join(c for c in unicodedata.normalize('NFC', prompt) if c <= '\uFFFF')
self.prompt = prompt
try:
driver.get('https://www.bing.com/images/create/')
search_box = driver.find_element(By.NAME, 'q')
search_box.send_keys(prompt)
search_box.send_keys(Keys.RETURN)
try:
wait_for_error = WebDriverWait(driver, 2, ignored_exceptions=self.ignored_exceptions)
error_text = wait_for_error.until(EC.presence_of_element_located((By.XPATH, '//*[@id="girer"]/div/div[1]'))).text
error_msg = self.find_error(error_text)
if error_msg != None:
await ctx.send(error_msg)
except:
wait_for_gen = WebDriverWait(driver, 60, ignored_exceptions=self.ignored_exceptions)
image = wait_for_gen.until(EC.presence_of_element_located((By.XPATH, '//img[contains(@src, "w=270&h=270")]')))
images = driver.find_elements(By.TAG_NAME, 'img')
image_links = []
for image in images:
src = image.get_attribute('src')
if src and 'w=270&h=270' in src:
src = src.replace('w=270&h=270&c=6&r=0&o=5&', '')
image_links.append(src)
image_links = list(set(image_links)) # Remove duplicates by converting the list to a set and then back to a list...
driver.close()
print(image_links)
async with aiohttp.ClientSession() as session:
files = []
for i in range(len(image_links)):
async with session.get(image_links[i]) as resp:
img = resp.read()
async with io.BytesIO(img) as file:
files.append(discord.File(file, "imagine_prax.png"))
await ctx.send(f"*Your prompt:* `{prompt}`", files=files)
except Exception as e:
print(e)
await ctx.send("There was an error while generating your image!")
I'm using selenium, that's probably blocking it...
I don't know where, or how to fix it though...
how i can make the bot send a message every time somebody is getting on live in YouTube?
I found this
you can use run_in_executor method with asyncio
Also the top answer here has 2 alternatives to selenium. Or you could try threading but not sure if that works well with Pycord.
How could I implement that to pycord?
so you suggest i use concurrent.futures.ThreadPoolExecutor?
worked for me
I mean i did try but didnt rlly succeed, i will retry looking at this code
also
does the other def has to be just def or can it be async def
i mean the one being run by the executor
async
guild = self.bot.get_guild(guild_id)
premium_roles = discord.utils.get(guild.roles, id=premium_role)
await interaction.user.add_roles(premium_roles)
user object has no attribute add_roles
Actions take place inside discord.ui.select
Hi, so i have a cog with commands in it. When i start the bot it says the cog has been started but i cant use any of the commands in it
it says command not found
Perhaps you have @commands.command Is not under def
show your code\
import platform
import psutil
import datetime
import aiohttp
from discord.ext import commands
class basic(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command(aliases=["botinfo", "bot-info", "binfo", "bi", "boti"])
async def botinfó(self, ctx):
pythonVersion = platform.python_version()
dpyVersion = discord.__version__
serverCount = len(self.client.guilds)
memberCount = len(set(self.client.get_all_members()))
channelCount = len(set(self.client.get_all_channels()))
embed = discord.Embed(title=f"Bot információ", description="A Retron bot információi", color=0x10b9e3, timestamp=datetime.datetime.utcnow())
embed.add_field(name="Bot neve", value="Retron", inline=True)
embed.add_field(name="Készült", value="2021.03.31.", inline=True)
embed.add_field(name="Programozási könytár", value="Pycord")
embed.add_field(name="Szerverek", value=f"{serverCount}")
embed.add_field(name="Csatornák", value=f"{channelCount}")
embed.add_field(name="Felhasználók", value=f"{memberCount}")
embed.add_field(name="Python verzió", value=f"{pythonVersion}")
embed.add_field(name="Parancsok száma", value=f"{len(self.client.commands)}")
embed.add_field(name="Pycord verzió", value=f"{dpyVersion}")
embed.add_field(name="CPU magok száma", value=f"{psutil.cpu_count()} db")
embed.add_field(name="Memória mérete", value=f"0,5 GB")
embed.add_field(name="CPU kihasználtság", value=f"{psutil.cpu_percent()}%")
embed.add_field(name="Memória kihasználtság", value=f"{psutil.virtual_memory().percent}%")
await ctx.reply(embed=embed, mention_author=False)
def setup(client):
client.add_cog(basic(client))```
you can try fetching or getting the member.
how are you loading your cog
if filename.endswith('.py'):
client.load_extension(f"cogs.{filename[:-3]}")
print(f"[COGS] ~> {filename} elindítva\n ")
print("[INFO] ~> Parancs cooldownok betöltése...")
if os.path.exists("cooldown.pkl"):
with open("cooldown.pkl", 'rb') as f:
d = pickle.load(f)
for cmd in list(client.commands):
if cmd.name in d:
cmd._buckets = d[cmd.name]
print("[INFO] ~> Parancs cooldownok betöltve!")
how do you run your bot
what do you mean by that?
what do method do you call to run your bot
if I asked you which line of code would start the entire bot, what would that be?
client.run("mytoken")
where is this in your code
import sqlite3
import os
import pickle
from discord.ext import commands
intents = discord.Intents.all()
a = []
x = 1
x = x +1
players = {}
client = commands.Bot(command_prefix=_get_prefix, case_insensitive=True, intents=intents)
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
client.load_extension(f"cogs.{filename[:-3]}")
print(f"[COGS] ~> {filename} elindítva\n ")
print("[INFO] ~> Parancs cooldownok betöltése...")
if os.path.exists("cooldown.pkl"):
with open("cooldown.pkl", 'rb') as f:
d = pickle.load(f)
for cmd in list(client.commands):
if cmd.name in d:
cmd._buckets = d[cmd.name]
print("[INFO] ~> Parancs cooldownok betöltve!")
@client.event
async def on_ready():
for x in client.commands:
a.append(x)
print("gg")
client.run("mytoken")```
thats my main.py
i don't see client defined anywhere
there it is
you say that the cog is being loaded?
you say when you run botinfo you get the CommandNotFound error?
yep
@commands.command(aliases=["botinfo", "bot-info", "binfo", "bi", "boti"])
async def botinfó(self, ctx):
I think you can't have an alias being the same as the original command name
try removing "botinfo" from aliases?
its not the same. botinfó and botinfo is different
but okay i will try
still nothing
why the hell does your command name have an ó
because in hungary we spell it like that
i think it was common practice to not use any special characters in code ever
it worked
my bet is that it's that
no
only if you're english-centric
removing the ó from the name?
yes
any idea whats the problem?
do all your commands not work?
and a bunch of things in your main.py that you've shown are not defined
nope only the commands in basic.py
they are but i didn't send the whole code because i didn't wanted to show it
but they are just random commands
does moving to a different cog work
hmm
hmm sorry i just found it. i got this error when i start it RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited client.load_extension(f"cogs.{filename[:-3]}") RuntimeWarning: Enable tracemalloc to get the object allocation traceback
You have conflicting libraries. Show your pip list.
member = await guild.get_user(int(user_id))
object has no attribute get_user
Also I tried fetch_user / fetch_member but error was same no attribute fetch_member
yeah i figured it out btw thanks for the help
It's get_member
Read the docs.
Same error
Where and how did you define guild
guild = self.bot.get_guild(1185946025479909447)
member = await guild.get_member(int(user_id))
role = guild.get_role(premium_role)
if premium_roles:
await member.remove_roles(premium_roles)```
get_memberisn't a coroutine.- Show me the whole traceback
In the first case, I copied it wrong
get_guild is returning None
That means the bot isn't in that guild or the guild isn't cached or the guild ID is invalid
Is it possible to get the bot object from anywhere in my program?
Like a decorator that gets the bot object from the global scope or something and does something with it?
Ofc I mean the wrapper getting the bot object (so at runtime), not the decorator.
In cogs you receive the bot object on the init
Otherwise you'd just be in your main file where your bot object is there
I tried many options, but id 100 lumens correct
The bot is also 100 percent located on this server
Since every time it starts, it enters a channel in the voice on the server
What's stopping you from using ctx.guild?
import discord
from discord.ext import commands, tasks
import sqlite3
from datetime import datetime
from main import *
class PremiumCheck(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.check_expiration.start()
@tasks.loop(seconds=1)
async def check_expiration(self):
conn = sqlite3.connect('database.db')
cursor = conn.cursor()
current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
cursor.execute('SELECT user_id FROM premium_user WHERE end_time <= ?', (current_time,))
expired_users = cursor.fetchall()
for user_id_tuple in expired_users:
user_id = user_id_tuple[0]
guild = self.bot.get_guild(guild_id)
role = guild.get_role(premium_role)
member = guild.get_member(int(user_id))
if premium_roles:
await member.remove_roles(role)
cursor.execute('DELETE FROM premium_user WHERE user_id = ?', (user_id,))
conn.commit()
conn.close()
def cog_unload(self):
self.check_expiration.cancel()
def setup(bot):
bot.add_cog(PremiumCheck(bot))
is bot.guilds populated or empty
I was actually looking for something lower level. The gc module should be what I was looking for 🙂
That way I can actually get the bot instance even from a utils function
Although that might actually not be good practice... Well, whatever xD
what do you even need that for
Some weird decorator that I wrote so that I don't have to pass the bot during an object instantiation xD
wtf
Basically I wanted to access the bot in a decorator wrapper for a method in a Modal
But didn't want to just pass the bot to the Modal xD
don't ask me why
Oh I know why: I like to overcomplicate things before I can actually make them simpler
Do modals that have timed out not get deleted from the modal store automatically?
I can successfully submit a modal that has already timed out... Is that right?
Even when I do modal.stop() it can still be submitted successfully
pycord v2.4.1
Is the time zone of the server where the bot is running used or is the time zone displayed for everyone as the Discord settings are for the user?
bro joined the wrong support server
ok
can i get starting code for pycord?
rude
perhaps start with reading the docs or watching some basic tutorials of newly slash commands in py-cord
Why is that rude?
the guide is a little outdated but it may be of aid
can you write the code
my man, this is a support server, not a code writing server >-<
You should create full new project and rewrite your bot with py-cord
ok
We are not gonna write the code for you...
plz
._.
no.
Excited to create your first bot? Once you install Pycord, you can start right
come back here when you have got actual questions, we will not be writing code for you, this is a support server not a code generating server. dito.
It will be the users timezone settings. To get it to work properly you may have to pass a UTC time though.
Or read the docs
intellisense...
AttributeError: module 'discord' has no attribute 'Bot'
After py-cord-dev got deleted idk how to fix this
use the git one
tried that already
take a look at here -> #app-commands message
Can you show the pip list if its still the same error
it had discord.py in there mb
i think that was the prboelm
let me relaunch
shit yeah
alr thank u
Hey guys, I was wondering if there's an easy way to stop the bot ?
I made a command to stop it, but it doesn't work properly: the bot itself closes its connection to the Discord API but the process doesn't stop, does someone have an idea to make it stop the process also ?
Here's my code from my bot class (which is a subclass of discord.Bot)
async def stop(self):
"""Stops the bot"""
await self.close()
exit(0)
And here's the error message when I force the process to end with a control-C:
^CException ignored in: <module 'threading' from '/home/mathis/.pyenv/versions/3.11.7/lib/python3.11/threading.py'>
Traceback (most recent call last):
File "/home/mathis/.pyenv/versions/3.11.7/lib/python3.11/threading.py", line 1590, in _shutdown
lock.acquire()
KeyboardInterrupt:
Thanks 😄
Where and how are you running the bot?
usually you can just stop the bot in the console by using ctrl + c
For now simply on my own computer (I have an oracle server but I just launch the bot without nohup from my computer to test it (so python path/to/main.py
Yes but i would like to avoir this as the bot will be deployed to a server
it's the same on servers though...
And I don't want to connect to the server every time I want to stop the bot properly
Same, it stays stuck until I control-C
and same error
seems like it gets stuck waiting for a lock
try to implement this:
def _cleanup_loop(loop: asyncio.AbstractEventLoop) -> None:
try:
_cancel_tasks(loop)
loop.run_until_complete(loop.shutdown_asyncgens())
finally:
_log.info("Closing the event loop.")
loop.close()
def _cancel_tasks(loop: asyncio.AbstractEventLoop) -> None:
tasks = {t for t in asyncio.all_tasks(loop=loop) if not t.done()}
if not tasks:
return
_log.info("Cleaning up after %d tasks.", len(tasks))
for task in tasks:
task.cancel()
loop.run_until_complete(asyncio.gather(*tasks, return_exceptions=True))
_log.info("All tasks finished cancelling.")
for task in tasks:
if task.cancelled():
continue
if task.exception() is not None:
loop.call_exception_handler(
{
"message": "Unhandled exception during Client.run shutdown.",
"exception": task.exception(),
"task": task,
}
)
after or before the loop.stop()
That's basically what the bot does on ctrl+c
what is the _cancel_tasks ?
Oh ok that's smart i'll check the source code
oh, yeah. sorry xD
await bot.close()
should be right
The following section outlines the API of Pycord’s prefixed command extension module. Bots: Bot: Attributes activity, allowed_mentions, application_flags, application_id, cached_messages, case_inse...
but that wont stop the loop does it?
It stops the connection but not the process
even with an exit just after
I feel like the problem "comes" from asyncio, as the error message is always on the lock.acquire
yeah some coroutines are locked
I added them to the message
But as already said, take a look at bot.run(), that's where all that is implemented
close is killing the process for me
You launch you bot like that ?
Right, for me too...
I just tried it
@argobot.slash_command(...)
async def stop(ctx):
await argobot.close()
Here's my bot class:
class ArgoBot(discord.Bot):
def __init__(self, description=None, *args, **kwargs):
super().__init__(description, *args, **kwargs)
self.load_extension('cogs.diver_info')
self.load_extension('cogs.admin')
async def stop(self):
"""Stops the bot"""
await self.close()
print("hello")
exit(0)
I have the same thing
async def stop_bot(self, ctx: discord.ApplicationContext):
if not ctx.author.guild_permissions.administrator:
await ctx.respond("You don't have the permission", ephemeral=True)
return
await ctx.respond('Stopping the bot', ephemeral=True)
await self.bot.stop()
try removing the exit(0)
doesn't matter the hello is never printed (and it wasn't working before the exit)
try adding this to the main file and stop it with the /stop command
does that work?
I'll try wait
Ok i think i found the problem
@argobot.event
async def on_ready():
await database.init_db()
await argobot.stop()
print('Launching bot')
If i put await argobot.stop() before the db init it stops
and if I put it after it doesn't
yeah aiosqlite so that's probably why
yeah
that won't get stopped by bot.close() so it locks the loop
just overwrite the bot.close() method like this:
class MyBot(discord.Bot):
async def close(self):
await database.stop() #or whatever it is
await super().close()
then you can use bot.close() and the database will be closed too
yes that was the problem, it works now thanks 😄
when using buttons, how do i edit original message to change the embed
Using edit original it gives me 404 error
interaction.response.edit_message
ok ill try that
get the channel and send the message
how would i send the message to the channel though
.rtfm get_channel
discord.ext.commands.Bot.get_channel
discord.ext.bridge.AutoShardedBot.get_channel
discord.ext.commands.AutoShardedBot.get_channel
discord.AutoShardedBot.get_channel
discord.AutoShardedClient.get_channel
discord.ext.bridge.Bot.get_channel
discord.Guild.get_channel
discord.Guild.get_channel_or_thread
discord.Client.get_channel
discord.Bot.get_channel
.rtfm Channel.send
I was close to mention google but that also works ;3
can u link me an example pls
view=MyView(timeout=30)) these are 30 seconds? or ms, or minutes? idk
I already provided you the docs link
Read the docs.
thank you so much 
how i can make the bot send a message every time somebody is getting on live in YouTube?
You integrate that with YouTube's API or whatever they use.
oh ok
@lofty parcel before bot run then?
Yes
thanks
How do I set a cooldown for a command with a specific amount of time (determined in the command's function) using commands.cooldown?
you want to be able to update the cooldown from inside the command? so, if the command takes longer, the cooldown is higher? you could use some cooldown, and manipulate the bucket you are using, if that is, what you want to achieve
own question:
in file /discord/ext/commands/converter.py
there is
CONVERTER_MAPPING, which is used to determine, which converter is used for which type.
is there any better way to override a specific converter than putting it in there when my bot starts?
I want my threads to be resolved, even if the bot needs to call the api for this (archived threads)
You didn't even answer my question 
"use some cooldown"
Doesn't help.
oh, ok, I thought the problem was, that you did not know, how to manipulate the cooldown, give me a second
I'll just wait for a helper or someone reputable.
https://docs.pycord.dev/en/stable/ext/commands/api.html#discord.ext.commands.cooldown just use this decorator.
if you want to be able to "change the waiting time", you might need to create your own decorator (just look at the source) which enables you to pass the cooldown object yourself, instead of the type of bucket.
store this cooldown object somewhere and you can manipulate it
The following section outlines the API of Pycord’s prefixed command extension module. Bots: Bot: Attributes activity, allowed_mentions, application_flags, application_id, cached_messages, case_inse...
a few weeks ago, I created my own cooldown object to limit the clicks on a button by user which clicked it
it is possible, but I just do not know, how much you know about these things
Why do you need to manage the cooldown from the command
It's an apply command and the application has a setting for how long the user has to wait after applying to use the command again.
Application cooldown if you will.
is there a way to use a Role from one guild in another guild with a bot ?
Why would you use a role in another guild
a shared bot between 2 server for a event
that is what I though, but I read online that bot have a nitro like permissions for roles
(they can use role from other guild to another)
like if you have nitro
but not sure if true
Bots don't have nitro
Nitro doesn't even do that
Bots can't randomly give a role from X guild in a Y guild.
no I dont mean give a role, just use it in text
Uh? As in?
You can't mention a role that's from another guild.
It won't parse.
You could just use the name.
I see, so the role should exist in both server right in order for it to work ?
No?
I'm literally not understand what you want to do.
WHY do you need a role from another server
HOW do you want to use such role
the user would run the command, after that the bot will respond: You have won x {emote}
I want to use the same emote in both server
I mean emote
emote
Why do you say emote when you're asking about a role
AND NOW YOU SAY EMOTE
We wasted 10 minutes arguing about some imaginary role when it was just an emote.
there is emote in the last 3 message, I just use the wrong world at the start
not everyone speek english as native language
English is not my native language
Role and emote are not even a remotely close word.
Now that we agreed you want an EMOTE.
I just use the wrong word, why are you getting so worked up
You just upload it to some private server of yours and just copy it.
You wasted 10 minutes of our lives and literally confused the hell out of me by using the wrong word more than 4 times.
well mistake happen, I did not meant to use the wrong word on purpose and I am sorry for that.
What is your native language?
how i can move a specific text channel into a specific category?
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 ...
Read the docs.
man the rude role does fit
The docs tell you.
yea
yea to what
to use category or to look in the docs?
both
very specific
if you dont want it sorted i think you only need the category and maybe sync_permissions param depending on what you need
thanks
Should I use discord.Cog or commands.Cog for a bridge bot?
discord.Cog if you only have application commands
So I have to use commands.Cog for both, I see ;3
@errant trout hi, sorry if I'm bothering you, you've once once mentioned about "ctx.me.activity", where can I read more about this method?
.rtfm activity
discord.Activity
discord.Activity.application_id
discord.Activity.assets
discord.Activity.buttons
discord.Activity.created_at
discord.Activity.details
discord.Activity.emoji
discord.Activity.end
discord.Activity.flags
discord.Activity.large_image_text
discord.Activity.large_image_url
discord.Activity.name
discord.Activity.party
discord.Activity.session_id
discord.Activity.small_image_text
discord.Activity.small_image_url
discord.Activity.start
discord.Activity.state
discord.Activity.sync_id
discord.Activity.timestamps
ctx.me refers to the bot's Member object (i.e. guild.get_member(bot.user.id)), so look for discord.Member.activity in docs
got it, thanks!
class MyView(discord.ui.View):
def __init__(self):
super().__init__(timeout=10)
async def on_timeout(self):
self.disable_all_items()
# Buttons below...
The buttons stop working after 10 seconds but their animation does not change to disabled, what i'm doing wrong?
do you edit the view?
nope
;3
how?
Its at the example for buttons
Learn all about implementing buttons in your Discord Bot using Pycord.
yeah but there is no interaction i cant use await interaction.response.edit_message()
.
Anyone know off-hand if you're able to get the reddit username of a user who has connected reddit to their account and joined your server? Last I checked this was not the case but was hoping it'd changed
so i am trying to put the bot up and it keeps saying it is not finding a module discord
can anyone quick help me?
Show your pip list
mo pip list except pycord its a new server
if it's really only pycord in the pip list, there's something wrong...
httpx.LocalProtocolError: Illegal header value then bots discord key
class accept(discord.ui.View): # Create a class called MyView that subclasses discord.ui.View
@discord.ui.button(label="Post", style=discord.ButtonStyle.success) # Create a button with the label "😎 Click me!" with color Blurple
@discord.ui.button(label="Delete", style=discord.ButtonStyle.danger) # Create a button with the label "😎 Click me!" with color Blurple
async def button_callback(self, button:discord.Button, interaction:discord.Interaction):
if button.label == "Post":
#todo
await interaction.respond(content="Posted", ephemeral = True)
if button.label == "Delete":
await interaction.respond(content="Ignored", ephemeral = True)```
oh wait fuck I did it wrong
I don't think you can actually use two command decorators on one function can you?
Also the class name is triggering me xD
accept.
It just defies common practice xD
most understandable function names when its only you working on the project
class accept_vw(discord.ui.View): # Create a class called MyView that subclasses discord.ui.View
@discord.ui.button(label="Post", style=discord.ButtonStyle.success) # Create a button with the label "😎 Click me!" with color Blurple
async def bcp(self, button:discord.Button, interaction:discord.Interaction):
if button.label == "Post":
await interaction.respond(content="Posted", ephemeral = True)
@discord.ui.button(label="Delete", style=discord.ButtonStyle.danger) # Create a button with the label "😎 Click me!" with color Blurple
async def bcd(self, button:discord.Button, interaction:discord.Interaction):
await interaction.respond(content="Deleted", ephemeral = True)```
it still not working 😭
same error
can you send the exact error pls
httpx.LocalProtocolError: Illegal header value b'eyJhbGciOiJIUzI1NiIsInR5cC..bot key
but seems like you got something wrong with the bot key...
there is a \n at the end
also now regen you bot key
oh shit yeah I made a new key its like a fourth of the size
well now it says improper token
its not my discord key its the key to my database
where tf is it getting the key to my database
is it an environment variable?
no I just made a file and .readlines()
can you just show us your code please? How you start the bot and add the token etc...
.
oh
What the hell is that way of storing secrets
use .env file and use the dotenv library to load it...
Use a doenv if you want to do it properly
Yeah. Like in the guide
Excited to create your first bot? Once you install Pycord, you can start right
💀
so uhm I fixed it it didnt have anything to do with pycord
I jsut assumed it did
obviously xD
also dotenv wont install because AttributeError: module 'importlib._bootstrap' has no attribute 'SourceFileLoader' this is with --use-pep517
idk wth I did to make it do that
me neither...
How can i get the ID's of the people who reactioned to a msg?
should be smt like msg.reactions[0].users()
yes
async for user in message.reactions[0].users:
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 ...
or users = await reaction.users().flatten()
returns none
await msg.reactions[0].users().next() shows them but only using next
its strange xd
can options in slash commands be dropped depending on a previous option?
e.g
/add <x> <y> <z>
if y is 0 dont ask for an input for z
you can just ignore z
@vital bramble sorry i just read correctly your answer
thank you, it worked
yeah, it's actually users() at the end.
also you can just use users = await reaction.users().flatten() to get a list of users or just go read the docs yourself
Welcome to the guide for voice features in Pycord.
Hey, I'm trying to make a global error handler whenever one of my checks fails for a command. Even though I've set up a dedicated check for this exception, its still going through. Why is that? It works for some commands but doesn't work for others.
I am trying to work on coding challenges, and was trying to find how to replace values. Ex. I want to change all e's someone puts in with f.
def replace_e_with_f(string: str) -> str:
return string.replace('e', 'f')
Ok so the string is being modified with .replace?
no strings in python are immutable
def replace_e_with_f(string: str) -> str:
return string.replace('e', 'f')
string: str = "hello"
replace_e_with_f(string)
print(hello)```
will print `>>> hello`
Thank you for the explanation.
How do I set a cooldown for a command with a specific amount of time (determined in the command's function) using commands.cooldown? I have an apply command and the application settings has a cooldown time, and I want to apply that cooldown when the command is done.
I have to test something after that I can tell you if its possible ;3
But it should be possible to do
Ok I appreciate it, I didn’t see anything in the docs that was clear
A command object only has the reset_cooldown, is_on_cooldown, and get_cooldown_retry_after methods.
It’s just not in the docs so idk how
cd_mapping = commands.CooldownMapping.from_cooldown(1, 60, commands.BucketType.user)
bucket = cd_mapping.get_bucket(ctx.message)
retry_after = bucket.update_rate_limit()
if retry_after:
await ctx.send("Error")
else:
await ctx.send("Text")
That also works with buttons and menus
Would you be able to explain to me how that works?
No, I found that at searching for a cooldown for the on_message event
Oh I see, thanks
Doesn’t seem to work, it always says the user isn’t rate limited, unless I understood the usage wrong.
Can you set the cd_mapping = commands.CooldownMapping.from_cooldown(1, 60, commands.BucketType.user) outside of the command?
I need the seconds to be changed in the command since in the command is where I have the application data fetched from the database, which is what application a user is submitting a response for.
how to unmute bot in voice?
Since you can't defer before sending a modal, is there any other similar alternatives?
how do i add a callback to this?
need to do it this way since i cant predefine all options
tried this but it annoyed and i cant figure out how to give it what it wants
and if i run it anyways... Application Command raised an exception: AttributeError: 'method' object has no attribute '__discord_ui_model_type__'
You can simply create a select menu using the decorator with some placeholder options and then override the options inside the init
For example
class MyView(discord.ui.View):
def __init__(self, select_options):
super().__init__(…)
self.my_select.options = select_options
@discord.ui.select(…)
async def my_select(…):
…
Notice the callback name and the method I am calling in the init
Ok thanks that worked
how to use cooldown on user id but admins don't get affected?
Do you guys know how some bots have certain commands that are visible only to mods like Arcanes xp set level?
How can I replicate that?
When I get home can you help me? I'll be home at 3:00 PM EST
I can try...
I am home now if you wanna help
Make a post in #969574202413838426 , I'll help you there.
bro don't just randomly ping me for a problem please. It's for replying to me, not for getting help.
there is a typo in the second line...
also what errors did you get?
also have you tried google?
google says that?
bro idk ask chatgpt or whatever but if you want to get help here, describe what you're trying to do, what the problem is, what errors you get and what you have already tried to solve the problem.
a.k.a. everything in #help-rules ...
😂
Is it possible to have a view with multiple reusable buttons? Think I've had an issue in the past where Discord would say I already sent a response or something and error out.
Responses are per interaction.
You can use the view as many times as you want as long it doesnt timeout or your don't disable the buttons.
Hmm 🤔 so as long as I don't send a response (e.g. defer instead?) it's fine?
Hmm. Maybe I should explain what I'm trying to do better to give you an idea of what I'm working with.
I've got this blackjack game (vs the bot only) that uses emojis right now. You can hit any of the two reaction emojis to change the state of the game until you win or lose (or draw).
Issue with this is that reactions are painfully fucking slow compared to buttons from what I've noticed.
But the thing is, these reactions can be pressed over and over again (the bot removes the user's reaction after they click on an emoji).
Is it possible to have a system like this with buttons or do I have to figure something else out?
Yes. That's what I told you.
You can click buttons whatever many times you want as long as the view doesn't timeout or your disable the buttons.
Ah, see my concern with no response is that the user will get some kind of response timeout error, won't they? Because it'll just infinitely wait for a response.
And a deferred response still seems to count as a response? So sending multiples of those isn't really an option is it? Or can I send the deferred response once and let the user keep clicking after?
You can just defer it (which will send an interaction failed message after like 15 minutes) or edit the message passing no new things
You can defer and the user can click everytime
Every click is a new interaction
Gotcha, thanks.
so my bot is in a big server with 2fa moderation enabled
how do i make it work even without 2fa
the bot owner needs to have 2fa enabled
I know that this question is not on the topic of the server, but hosting support simply does not answer me, so I solved it here.
What to do if requirements.txt I add py-cord But the result is an error no module discord
Can you show what you have in the txt file?
py-cord
That's all there is
I found something when I tried to install hosting py-cord These are the errors
You're using Python 3.12, Pycord currently doesn't support that, next update will, however. I'd recommend downgrading to 3.11
Thank you very much, I'll try it now
How do I add / remove items from a view? Like I want to be able to add buttons if the user selects a certain option from a selector, and remove the buttons and add anothrr delector if they change the option
Ok thanks
Quick question, I currently have a View with 2 Dropdown menu and a confirm button, right now when someone select an option on the dropdown menu it the response go though fine, but how do i make it so that the user's side don't show "This interaction failed"? Do I ping the interaction or something?
The "Interaction failed" is from discord and not py-cord
yea i know but like, do i make pycord side send out a ping or something so it doesnt' show that?
Or will it always happen?
it will always happen
right.. i should probably just send a small message or something so it doesn't confuse users then
unless you set a timeout or edit the view so they cannot press the button again
you can "lock" the views so they cannot press it anymore
guys, how to make a similar feature for commands?
for example, I have a /account command that I would like to add to this list
Here's the context menus example.
thx
is there a reason why auto complete and options stop working, was setting up a slash command with auto complete and it was working fine, added a few more options and it stopped syncing with the new options and the autocompete wont load
whats causing this exception
await interaction.followup("Your LFG channel has been deleted.")
TypeError: 'Webhook' object is not callable
But you know that you can only see 25 at discord?
im way below the 25 limit
it doesnt have a limit
it only shows 25 at autocomplete
the options have a limit of 25
okie, thought they applied to both, nice to know
but either way its between 4 and 14
options
new question, how do i get discord to update my slash commands, i added a new one but its not appearing nor usable
Do you have the commands in a cog?
no
.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.
how to i set my embed's colour to a custom hex value?
ive already tried that, but i get Expected discord.Colour, int, or Embed.Empty but received str instead.
@little cobalt ??
usually 0x992d22 should work?
oh, thanks :3
hi hi i have a quick question, i have a command using autocomplete a function for choices.
the choices come from a database which is a dictionary that contains the name of the option, is there a way to let that name be the choices the user sees AND keep the dictionary in scope for the actual command function?
