#Basic Pycord Help
1 messages · Page 8 of 1
it does
it's also evident based on the methods and properties of each class
why?
its just an empty dict
so like this?
>>> x["foo"].update({"bar": 2})
>>> x
{'foo': {'bar': 2}}```
Does pycord discord.Option support typing.Annotated (i.e. foo: typing.Annotated[str, discord.Option(str, ...)] instead of foo: discord.Option(str))
can i have an example of how to use this function?
https://docs.pycord.dev/en/stable/api/ui_kit.html#discord.ui.View.interaction_check
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...
Inside your view class
async def interaction_check(interaction):
if interaction.user.guild_permissions.manage_messages:
return True
await interaction.response.send_message("You can't use this")
return False```
Ignore indentation, I'm on mobile
got it, thanks so much!
wait, what do you mean inside of the class? im just creating an instance, should i create a class that extends it?
Here's the confirm example.
Yes on the dev release
See #library-updates to install dev release
dev release is at/behind main on github right?
awesome
It seems unless I do Annotated[discord.SlashCommandOptionType.<type>, discord.Option(...)], I get
Sep 02 02:30:53 pi python3[318641]: Ignoring exception in on_connect
Traceback (most recent call last):
File "/home/pi/Bots/server-bot/venv/lib/python3.11/site-packages/discord/client.py", line 399, in _run_event
await coro(*args, **kwargs)
File "/home/pi/Bots/server-bot/venv/lib/python3.11/site-packages/discord/bot.py", line 1182, in on_connect
await self.sync_commands()
File "/home/pi/Bots/server-bot/venv/lib/python3.11/site-packages/discord/bot.py", line 757, in sync_commands
app_cmds = await self.register_commands(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/pi/Bots/server-bot/venv/lib/python3.11/site-packages/discord/bot.py", line 591, in register_commands
data = [cmd["command"].to_dict() for cmd in filtered_deleted]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/pi/Bots/server-bot/venv/lib/python3.11/site-packages/discord/bot.py", line 591, in <listcomp>
data = [cmd["command"].to_dict() for cmd in filtered_deleted]
^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/pi/Bots/server-bot/venv/lib/python3.11/site-packages/discord/commands/core.py", line 866, in to_dict
"options": [o.to_dict() for o in self.options],
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/pi/Bots/server-bot/venv/lib/python3.11/site-packages/discord/commands/core.py", line 866, in <listcomp>
"options": [o.to_dict() for o in self.options],
^^^^^^^^^^^
File "/home/pi/Bots/server-bot/venv/lib/python3.11/site-packages/discord/commands/options.py", line 336, in to_dict
"type": self.input_type.value,
^^^^^^^^^^^^^^^^^^^^^
AttributeError: type object 'int' has no attribute 'value'
it should've been a pre-release as opposed to an rc imo
which kinda defeats the purpose of it being annotated in the first place
Does it just take the first value of annotated and prioritises that over the one supplied to discord.Option?
I think that's what happens
foo: typing.Annotated[str, discord.Option(...) is the equivalent of foo: discord.Option(str, ...)
It lets you pass the input type through the 1st part of the annotation
Why would you want to have a different annotation and a different input type
.load_extensions isnt recognised
load_extension is recogniced but is async not sinmple def
any ideas why?
you have conflicting dependencies
cheers, fixed
How do you get labels that are not limited to 45 characters in Modals? I want to create a survey but the 45 character limit is getting in the way. What is the solution to this? Why is it there a character limit in the first place?
Expand max_length
I am sorry, my question wasn't clear. I am talking about the label, not the value
nope you can't. i would recommend shortening down your label to only what is needed
ahh, I dont understand why is it like that though
What is your "title" supposed to be?
As far as I know, there isn't any item for showing text like a label or something
I am creating a form, kinda
For a survey to collect information from users
Limiting my question to 45 characters is immprossible
The only alternative I see here is to ask question using the placeholder
this is what modals are really designed to do. You are going to either have to find another way to collect responses (honestly Google Fourms would be a better choice instead) instead
I just recommend going with Google Forms, and then putting the link within the message so people can take the survey
That would never work haha. As I have noticed, my user base is filled with extremely lazy people. I tried a DM based approach where the question and answers where sent in dm and they just ignored all of it.
I am pretty sure this Modal thing will also not work
but I wanna give it a try
Don't DM them. That's just poor privacy practice
whoever basically DMs me to send me an survey will automatically get blocked by me
and no warning at all
Nope, its only if they want to do it. The survey only start when you click on the 'take a survey' button, its not against their will. Nor do I send links. Just a question answer based approach.
i see
Thats why I am pretty sure they will ignore this as well, but lets see
you know that you can make a link button that links to the google fourms. If you really want to get feedback, i would recommend trying to start up a convo about your bot and ask for feedback
more than likely it's not that you have lazy people, it's that people are not interested in using your bot
The thing is, taking a survey outside of the discord environment is something even I won't ever do lmao. But I understand what you want to say. I do have a community where occasional discussions take place.
honestly it's up to you on how you want to approach it. my recommendation is probably to start up a convo about it but idk if that would work for you
That sure helps but limits the reach. Many people dont participate in discussions, some might not bring up points cz everyone is watching. Modals would have been a good solution. The thing is, why is there a 45 characters limit. Whats wrong with a longer label. 45 is a very weird/specific/small number to set as text size limit ngl
AA
Yk what
screw this
placeholders also have 100 character limit
I am so done with this
Funny as value can be upto 4000 characters but placeholders not more than 100
No that's not what I'm saying, if I pass str as the first annotated argument, it throws an attribute error when casting the command to a dict in on_connect
Seems like a bug I should report on GitHub to be honest
how to bypass autocomplete's limit?
async def cmd(ctx, option: Annotated[int, discord.Option(int, ...)]):
...
This raises an error ^
async def cmd(ctx, option: Annotated[discord.SlashCommandOptionType.integer, discord.Option(int, ...)]):
...
This does not, however this then makes intellisense think option is literally 4
Hmm that's interesting
2nd one is an enum so it will be recognised as 4
1st one shouldn't error
It should ideally go through the python type to discord input type conversion
Definitely a bug
You can create a GitHub issue
I'll try to look into it, but it not someone else will surely check this out
Make sure to provide adequate info
from git
hmm
pip install git+https://github.com/pycord-development/pycord.git to be precise
i hope you updated to the latest commits
cool 👍
its on commit 00b544cfeff615e51a0a555cdc2a92580b555142 👍
idk why its saying FINAL, after updating it says Successfully installed py-cord-2.4.1.dev167+g00b544cf
ouu
(venv) Bots/server-bot [ pip show py-cord ] 2:42 pm raspberrypi
Name: py-cord
Version: 2.4.1.dev167+g00b544cf
Summary: A Python wrapper for the Discord API
Home-page:
Author: Pycord Development
Author-email:
License: MIT
Location: /home/pi/Bots/server-bot/venv/lib/python3.11/site-packages
Requires: aiohttp
Required-by:
(venv) Bots/server-bot [ python3 -m discord -v ] 2:42 pm raspberrypi
- Python v3.11.0-final
- py-cord v2.4.1-final
- aiohttp v3.8.5
- system info: Linux 6.1.21-v8+ #1642 SMP PREEMPT Mon Apr 3 17:24:16 BST 2023
right okay
you know there is 2.5 already? x3
master on git is already ahead of that
it just says 2.4.1 because that's the last official version
idk im just installing the default branch im not doing any fancy git fuckery 😭
double checking here:
say i wanted to see who banned a user from a guild
is the only way to get that info to iterate through guild.bans? it feels like that would be terribly inefficient but i don't know if there's any other options
ah wait that's entirely wrong, i need audit log i see
Yea master is the default lul
Okay good 
who will tell you how to remove this damn response to the command, it spoils the whole view
if your embed command sends an embed somewhere, I suggest using an ephemeral response saying “your did it” and a regular .send() for the embed
I tried to do it through submit, but the error slips inside the modal window
show code?
embed = discord.Embed(title=self.children[0].value, description=self.children[1].value, color = color)
embed.set_image(url=self.children[2].value)
embed.set_footer(text = self.children[4].value)
await interaction.channel.send(embeds=[embed])
@bot.slash_command(name="embed")
async def modal_slash(ctx: discord.ApplicationContext):
"""Simple embed generator."""
modal = Gen1(title="Embed Generator")
await ctx.send_modal(modal)
await asyncio.sleep(1)
await ctx.respond("silent", ephemeral = True)
above is a huge palette and the modal window itself
Why are you sending a modal and then trying to respond
Sending the modal is already a valid response.
One way or another, a send error occurs in the modal window, but it sends
Something wrong. Try again
What's the error in the console
console without error
Remove the respond in the slash command callback
Do you respond to the modal interaction?...
If you give an answer to the modal dialog, then the answer from the bot will hang, which will be aesthetically mega in the future
What
await interaction.response.send_message(embeds=[embed])
@bot.slash_command(name="embed")
async def modal_slash(ctx: discord.ApplicationContext):
"""Simple embed generator."""
modal = Gen1(title="Embed Generator")
await ctx.send_modal(modal)
Original respond
You respond to the modal with some "sent" message like squid said
And send the embed with a normal .send
Like squid said
Ty
any reasons for why slash commands arent registering?
?tag slashnoshow
No tag slashnoshow found.
.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.
all of the above have been done
not the last step
no errors
import sqlite3
from os import environ, getenv, listdir, path
from dotenv import load_dotenv
from bot import CPObot
# get the relative path fo the folder called "cogs"
COGS_PATH = path.join(path.dirname(__file__), "cogs")
load_dotenv()
bot = CPObot()
def get_cogs() -> list[str]:
"return each cog in the cogs folder"
cogs = []
for file in listdir(COGS_PATH):
if file.endswith(".py"):
cogs.append(f"cogs.{file[:-3]}")
return cogs
@bot.event
async def on_ready() -> None:
"send a success message to terminal when the bot is ready"
print("Bot is ready")
for cog in get_cogs():
bot.load_extension(cog)
setup_db()
bot.run(getenv("TOKEN"))
if check_count < 14:
self.disable_all_items()
await interaction.response.send_message(embed=regen_embed(queue), view=PickupButtons())
await interaction.response.send_message(embed=queuelengthembed(queue, False, "init"))
how would i just send a message in an interaction?
im getting the error, this interaction has been responded to already
what about the cogs
use interaction.channel.send or interaction.followup.send
if you own a repository for this project, share that instead
are the cogs loading?
yup i get the print statements from each on_readiy in the cogs
try refreshing your discord client
and when i do .help i get the prefixed command in attendance
restart or ...?
same thing
can you not send interaction.channel.send as ephemeral message?
noting changed, dk if this important this is the terminal output:
Bot is ready
Attendance cog loaded
Server cog loaded
is there a way to?
ephemeral messages can only be sent as a response to interactions
okay
it doesn’t seem like you initiated the parent cog.
Can somebody explain me how donation bots actually work? You execute a command like !donate
The bot reacts and opens a modal or anything where you can choose what you want to (maybe) get for it like a specific role.
Then the user will get the paypal link for example.. how does the bot get if the payment was successfull or not?
could you explain that pls
Aesthetics saved
paypal has an api thing too
super().init() in the Cog class
Aaaaah, okay didnt know of that. Thanks!
still not appearing
pip list and show output?
pip
aiohttp 3.8.5
aiosignal 1.3.1
aiosqlite 0.19.0
async-timeout 4.0.3
attrs 23.1.0
charset-normalizer 3.2.0
frozenlist 1.4.0
idna 3.4
multidict 6.0.4
pip 23.1.2
py-cord 2.4.1
python-dotenv 1.0.0
setuptools 65.5.0
yarl 1.9.2
Bot is ready
Attendance cog loaded
Server cog loaded
try using the dev build
which one is that?
#library-updates
when a guild id is specified how long does it usually take to register the command?
the same as a normal command
still got nothing
try setting up logging. Maybe there’s a debug message there that could be helpful
just get a massive dictionary pertaining to the guild and dispatch events
Is it possible/feasible to make 'temporary' slash commands? e.g. adding a command on demand to use the structured fields of the input then unload it after use or some time later
you set auto_sync_commands=False...
Oh ffs 🤦♂️
There is a global rate limit of 200 (?) command creates a day
I am stupid
Interesting; I don't think it would ever hit that, but mostly just asking if it's possible to create a command while the bot is running rather than only on start
it’s supposed to, but it’s inconsistent
I still can't get slash commands to update when reloading the cog; I guess that should've been my first logical clue.
even with bot.sync_commands()
i'll probably make that my next target after i've completed my current prs
Ah, it looks like I have those lines disabled; IIRC the last time I tried, it was giving me "commands must be unique" errors.
@commands.command(name='reload', hidden=True)
@commands.is_owner()
async def owner_cog_reload(self, ctx, *, cog: str):
"""Command which Reloads a Module.
Remember to use dot path. e.g: cogs.owner"""
try:
self.bot.reload_extension(cog)
# await asyncio.sleep(1)
# await self.bot.sync_commands(force=True)
except Exception as e:
await ctx.send(f'**`ERROR:`** {type(e).__name__} - {e}')
else:
await ctx.message.add_reaction('👍')
reloading slash is meant to work fine without sync
just not updating/creating/deleting command metadata
The logic itself doesn't seem to change. Like if my slash command responded 'hello' and and I updated it to respond 'goodbye', I've never been able to get that to work if the logic itself is in a decorated method.
But I will triple-check my claim
it used to not work for me but started working around 2.2 or so, regardless people still seem to have mixed results so who knows
I probably know the answer, but just to brainstorm things I may not be thinking of -- if one can assign a before_invoke call for slash commands, is there a way to then apply some logic to the command parameters?
For instance, I have an integer option that would really benefit from a max_value on the Discord validation side. (But I guess if the command is registered with those rules, that wouldn't be possible)
...but dammit, it should be.
discord does have max value...
It does. But I would want it to be based on the result of the before_invoke, as the max value might change over time or between guilds.
hm
i mean
we could add something like @cmdname.process_options
but it seems so pointless
because, like, the point of a command itself is to process options... so we're just creating a second callback
the best you could do on the current system is either use autocomplete to read a previous option and tell the user if it's out of range (then error in command), or just add another function at the top of your callback
Would process_options be able to be dynamic? e.g. I have a max_value of 4 now, but after the command itself runs, it might be 5.
idfk i made up an implementation on the spot
in a class based system it would be easy enough to be dynamic
so probably
It was mostly a question on whether it would require redefinition of the command to Discord. I assumed max_value params are passed to Discord's command def. (Apologies for not knowing that process well enough)
max_value is set on initalization yes
you could update the command metadata, but definitely not based on option
(this circles back to the current command syncing system being bad)
Appreciate the thoughts.
Currently building the list in the autocomplete and validating in the command, but I also like the idea of building the values in before_invoke and simply having ac reference the stored values (cuz it only needs to be built once and I don't really need the autocomplete aspect, just the dynamic part) [brain-dump]
Edit: Oh, right. Cannot do it this way because the before_invoke doesn't actually get called until the method is actually invoked. Womp.
ctx.edit
quick question, how do I send something in a specific channel? this is what i tried
Initialize channel in the on_ready scope
oh
same error
What error
do you know how Pylance works?
i think so, i installed it a long time ago
Ok, so do you know how to use assert or LBYL works?
sorry what
no idea what that is
Are you sure you know how pylance works
are you talking about end-of-line sequence?
yea no i dont think so lmao
assert is a python keyword. LBYL means Look Before You leap
Then disable it
what does that have to do with sending a message to a specific channel
in pycord
That’s the way to resolve the error you are facing
can you just tell me how i can send a message to a specific channel
Disable Pylance
Is there a way to see pycord functions typehitns in pycharm?
I only see *args, **kwargs 💀
use ctx.response.send instead of ctx.respond
since thats just a shortcut i think
lol
I have a role selector Dropdwn class, is there a possibility that the user has previously pre-selected one, does anyone know how I can do it?
class DropdownByPassRoles(discord.ui.View):
def __init__(self, max_values: int, role_preselect: list):
super().__init__()
self.role_select_dropdown.max_values = max_values
@discord.ui.role_select(
placeholder="Select roles...",
min_values=0
)
async def role_select_dropdown(
self, select: discord.ui.Select, interaction: discord.Interaction
) -> None:
cache = Cache_Config()
db_server_config = ServerConfigDB()
roles_list = [roles.id for roles in select.values]
embed = discord.Embed(title=f"{Emojis.green_tick.value} Cool! The roles has been updated",
color=discord.Color.green())
for role in select.values:
embed.add_field(name=f" ", value=f"New role: {role.mention} ❯ ID: `{role.id}`", inline=False)
await interaction.response.send_message(
embed=embed
)
is it possible to get user's username history?
ephemeral messages are also affected by Forbidden Missing Access error or?
Then there is no real way to make the user aware that the bot has no permissions to send a message to the channel or?
How do i sync commands on pycord
await client.sync_commands()
Tysm bro
Ty
It says bot.sync_commands() does not have sync_commands
@little cobalt
why do you use it at the on_ready event?
?tag replit
Installing Pycord with Replit (only use replit as a last resort) - pycord-replit-install.md
Your installation looks faulty
also that ^
How i use it
@shell radish sorry for ping but what should i put sync in
Just make an sync command and manually syncing
Auto syncing within on_ready events is so not recommended. Why? On_ready fires multiple times, and the behavior is unpredictable. Plus, it causes unnecessary API requests (which probably leads to an CF 429 ban if you do it way too much) and you only need to sync once you have updated your commands
py-cord already sync the commands at starting the bot
I know that. But I still wonder why the behavior is implemented. I suppose it is to make folks have an easier time and abstracting it all away
So, if Py-cord would change to 3.9+ they would be kick all the Replit users ;3
oh please do
How can i make a button persistent that was added to a view like so:
view = CreateTicket()
cat1 = Button(label=self.name, emoji=self.emoji, style=style, custom_id=str(self.category))
cat1.callback = CreateTicket_callback
view.add_item(cat1)
Not like that ;3
you have to use a view class
Here's the persistent example.
I have one
class CreateTicket(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
How can i add items to it and keep it persistent? The items are configured by the user. Color, label, emoji etc.
ephemeral messages are also affected by Forbidden Missing Access error or?
Then there is no real way to make the user aware that the bot has no permissions to send a message to the channel or?
It should be from Forbidden, yeah
any action which the bot cannot do because it is missing permissions should just raise a Forbidden Error
in your bots console too, except if you silenced that :P
@hazy turret
Thought I'd ping u heh
Yes I know that but I wanted to somehow tell the user that he has not given the right permissions but I can not do that if I can not send a message 😄
You could send them a DM or ping them in a channel it has permissions in
Well... indeed as XeTrinityz recommended dm them, or mention them in an other channel as the bot cannot do anything else.
If the user has privacy settings set to so that the bot may not dm them, then youre a bit stuck.
Okay thanks, now have different mechanisms built into my bot to avoid stupid forbidden errors, thanks 🙂
im still running into issues with the typehints for discord.utils.basic_autocomplete() even after this update https://github.com/Pycord-Development/pycord/issues/2163
I get this mypy error:
error: Argument 1 to "basic_autocomplete" has incompatible type "Callable[[TeXBotAutocompleteContext], Coroutine[Any, Any, set[str]]]"; expected "Iterable[OptionChoice] | Iterable[str] | Iterable[int] | Iterable[float] | Callable[[AutocompleteContext], Iterable[OptionChoice] | Iterable[str] | Iterable[int] | Iterable[float] | Awaitable[Iterable[OptionChoice] | Iterable[str] | Iterable[int] | Iterable[float]]] | Awaitable[Iterable[OptionChoice] | Iterable[str] |
Iterable[int] | Iterable[float]]" [arg-type]
is this mypy messing up? or is the typehints still incorrect
(yes i am using the latest dev release)
I think it is because TeXBotAutocompleteContext is not allowed, even though it is a subclass of discord.AutocompleteContext. Rlly don't know why subclasses wouldnt be allowed.
Can I ask how to build text channel using pyocrd
Yes you can ask
how to build a text channel using pyocrd
.rtfm guild.create_text
Target not found, try again and make sure to check your spelling.
nvm
what did you try?
so I need to write a function which is using a slash command input a str and the command can creat a text channel and the channel name will be what the member just input
all member can access to the channel
So what code do you have currently? What have you tried?
Because I have no idea how to build a text channel with command so I want to know it first before start
Did you look at the documentation link sent?
oh Thank you
I don't know I can click on it
what is secret channel
a channel have some permission or some people can't access
Yes, only specific roles/users can see the channel.
already wrong in the first line :<
@bot.command(discription="create a game room")
async def createchannel(ctx, roomName:discord.Option(str)):
channel = await ctx.create_text_channel(roomName)
await ctx.send(channel)
The method is a method from the Guild not from the context
so what is guild mean
not the actual menaing
create_text_channel is a method of discord.Guild
You get the guild with ctx.guild
Do you know oop basics?...
Object Orientated Programming
You need to learn OOP before you use pycord
#help-rules
actually can I do it will discord.guild.create_text_channel as you say the method is from discord
💀
And that's why you need to learn OOP
What would be the best way to delete a category and all the channels under it by the category id?
uhh just do it?
¯_(ツ)_/¯
I'm not sure what your question is
I have nothing but the category ID, I want to delete that category ID and all the channels under it.
fetch the channel (categories are channels)
then delete the children
then delete the parent
Yeah I got it working, ty
One issue I am having which just randomly occured is on one of my commands, ephemeral just doesn't do anything.
embed = discord.Embed(title="Embed Builder", description="Click the buttons below to build your embed.", color=int("#FFFFFF"[1:], 16))
await ctx.respond(embed=embed, view=EmbedBuilder(name, emoji, color, category.id), ephemeral=True)
The message was ephemeral for awhile and then just stopped. Any ideas?
Its happening with another command. I just added the response twice and this is what happens.
Is it the original response or not?
Yes
is it deferred?
await ctx.respond("Panel has been reset.", ephemeral=True)
await ctx.respond("Panel has been reset.", ephemeral=True)
Yes
Only the original response to the interaction can be ephemeral
followups can be ephemeral iff it was a defer and the defer was ephemeral
This is at the top of the command
await ctx.defer()
Yes, it should be ```py
await ctx.defer(ephemeral = True)
Ah, that fixed it. I appreciate it.
yay

is it possible to choose which roles to appear in role_select?
How did make these options appear faster bruh i need to wait 20h
Get better Internet/hosting
Make code faster
Use async
Use caching
better hosting/internet doesn't really affect the speed of autocompletes if your db is locally hosted on your server
get less ping
and plus autocompletes already require async
code faster probably means use a non-blocking driver. optimize your sql queries
and always cache your data for autocompletes
if you have data that you need to look up, cache it
Or something that is not async blocking the code
in a ticket bot, is sending messages in a forum or normal channels better? and if so why
If I got this correctly I can edit a message to a paginator with paginator.edit(interaction) in an interaction or how does it work?
threads (What forum channels use) are made to be created/deleted within short amounts of time. They have higher ratelimits than normal channels. Plus it does not clog up the support/staffs channel list.
Hey peeps ((:
I'm desperately searching WhY i can't manage to see some options I added to a slash command...
Totally stuck on this, this is ridiculous...
Already added commands and options before, why should i sync !?! and how
I'm dying guys
You would need to pass the message object (you could try PartialMessage) not interaction. interaction.original_message() may be interesting to you.
Show relevant code.
Can you show your command that is not working. Just the decorators and function definition needed
Ok, thanks
Well, i have a generatecog.py, for a /generate command (that i added before, with 2 options)
called with self.load_extension('core.generatecog') when starting
As it is since A YEAR
Don't get why i'm stuck this way
Nor why i should implement a sync command or anything
😭
Can you like comment out the whole command
Run the bot
And uncomment it
And run the bot again
hum, i thought about something like that, then insulted myself and gave up
Pycord automatically syncs commands.
Make sure you are doing 3 things.
- Not loading cogs in on_ready or other event. Load them at the top level.
- Not calling
sync_commandsanywhere - Not overriding
on_connect() - On the latest pycord version
.
huh
Just noticed something at launch ...
No idea what to do with that. It's obviously talking about sync_commands
Not mentionning any of my file, i obviously don't have any commands with 25+ options
omg, feeling so dumb
What does it say below the invalid form body
Do you understand the error?

So in one of your command options you are giving a list of choices. The list cannot be more than 25 items. However if needed there is a way to get around this.
Yes, it's what's writen here, but my command with most options have 17
This is non sense
20*
It's happening on a fresh install of the original bot too
Here is the original repo
https://github.com/Kilvoctu/aiyabot
quite simple code
aiya.py + core files
Is your code on github or something? Or would you mind pasting it into pastebin or simi
Does this apply to you?
https://github.com/Kilvoctu/aiyabot/issues/167
Nop, i dedicated the bot for only one model, i currently have like 7-8 loras
https://github.com/wizz13150/Bot
Here are my current files
I'm playing to implement the 2 PRs in Kilvoctu repo
An improved generate command (Previous PR from me) and a progression message
(yes, messy PRs at this point, i just highly underestimated the sneaky side of discord)
((I didn't even talk about my buttons tokens.... HUUUH))
I'm also unable to keep a button alive
4th day on these issues (commands sync and buttons) and no progress.
Can you add
filename='discord.log' to logging.py
logging.basicConfig(filename='discord.log', ...
Then start the bot and show the results
Also possibly do logger.setLevel(logging.DEBUG)
Look at this example to keep the buttons alive
https://github.com/Pycord-Development/pycord/tree/master/examples/views/persistent.py
Not logging much
Yeah turn it to debug level
does pycord have any docs on creating threads etc?
.paste
huh, i noticed a line about Samplers
and can make sense cause the last webui update got new samplers, obviously exceeding 25
So it's not an option issue, but a choice issue
I love you
Need to find this list lmao
im making a ticket bot and there is a select menu that shows what category the ticket should be made in. now i want a thread to be made in the selected category but how would i do that?
i just want to know how to make a thread in a specific category
Threads are made in channels, not categoriea
would i have to have a channel in that category already to make a thread in?
is this correct?
thread = await guild.create_private_thread(name=f{interaction_4th.user.name}",overwrites=overwrites)```
Okay, i have a new one lol
(now my options are 'working'
)
Here, i want to use a flag, but it appears as options in discord
Is that a normal behavior !? 🤔
called_from_reroll
above
below
how do i set permissions/overwrites in a thread?
Just gonna #general
I have such a problem that I try to change an already changed message through await Paginator(pages=pages).edit() , but this error is sent to the console
File "/home/container/.local/lib/python3.11/site-packages/discord/ui/view.py", line 414, in _scheduled_task
await item.callback(interaction)
File "/home/container/cogs/economy.py", line 594, in button_callback
await paginator.edit(mess, suppress=False)
File "/home/container/.local/lib/python3.11/site-packages/discord/ext/pages/pagination.py", line 1073, in edit
self.message = await message.edit(
^^^^^^^^^^^^^
TypeError: InteractionMessage.edit() got an unexpected keyword argument 'suppress'```
how to check if an channel is an thread?
@commands.Cog.listener()
async def on_message(self, message: discord.Message):
You can use isinstance with the discord.Thread class to check if it is a thread
cogs not loading,
getting error:
Traceback (most recent call last):
File "c:\Users\philc\Desktop\testing\main.py", line 8, in <module>
bot.load_extension("cogs.info")
File "C:\Users\philc\Desktop\testing\.venv\Lib\site-packages\discord\cog.py", line 910, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Users\philc\Desktop\testing\.venv\Lib\site-packages\discord\cog.py", line 791, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.errors.ExtensionFailed: Extension 'cogs.info' raised an error: AttributeError: 'Bot' object has no attribute 'add_command'
pls, help
no use add_comm,and
im not.
check
import discord
bot = discord.Bot(command_prefix=".", intents=discord.Intents.all())
bot.activity = discord.Activity(
type=discord.ActivityType.watching, name="104th Battalion"
)
bot.load_extension("cogs.info")
bot.run(..)
main file
Did you install py-cord?
in the single cog file
Can you show your pip list?
you are using an environment area?
aiohttp 3.8.5
aiosignal 1.3.1
async-timeout 4.0.3
attrs 23.1.0
charset-normalizer 3.2.0
frozenlist 1.4.0
idna 3.4
multidict 6.0.4
pip 23.1.2
py-cord 2.4.1
setuptools 65.5.0
yarl 1.9.2
ofc
@heavy sky ^^
try uninstalling py-cord and installing the repo
python3 -m pip install git+https://github.com/Pycord-Development/pycord
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - GitHub - Pycord-Development/pycord: Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API
how are you defining the commands in the cog?
i have several projects all the same install in each venv, no issues in the others
what decorator are you using?
class Info(commands.Cog):
def __init__(self, bot) -> None:
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
print("Info cog is ready")
@commands.command()
i want it as a prefix command
^
import discord
from discord.ext import commands
class Greetings(commands.Cog): # create a class for our cog that inherits from commands.Cog
# this class is used to create a cog, which is a module that can be added to the bot
def __init__(self, bot): # this is a special method that is called when the cog is loaded
self.bot = bot
@commands.command() # creates a prefixed command
async def hello(self, ctx): # all methods now must have both self and ctx parameters
await ctx.send('Hello!')
@discord.slash_command() # we can also add application commands
async def goodbye(self, ctx):
await ctx.respond('Goodbye!')
@discord.user_command()
async def greet(self, ctx, member: discord.Member):
await ctx.respond(f'{ctx.author.mention} says hello to {member.mention}!')
@commands.Cog.listener() # we can add event listeners to our cog
async def on_member_join(self, member): # this is called when a member joins the server
# you must enable the proper intents
# to access this event.
# See the Popular-Topics/Intents page for more info
await member.send('Welcome to the server!')
def setup(bot): # this is called by Pycord to setup the cog
bot.add_cog(Greetings(bot)) # add the cog to the bot
from the pycord guide, commands.command()
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In type: Value must be one of {4, 5, 6, 7, 10}.
While adding an InputText to a Modal. The style is set to discord.InputTextStyle.long
self.add_item(InputText(label="Additional Comments?", style=discord.InputTextStyle.long))```
Is it possible to automatically customize the bot's About Me description without doing it through the Developer Dashboard?
For example, can you add a "Live Counter" there automatically how many servers the bot is available on ?
- no
Ok
Discord.bot doesn't support commands.command
Yup. An wrong import was causing the issues as I tried commands.Bot. And there was no attribute Bot. Hence the discord.Bot
Cheers
I'm actually not even sure but I found it interesting so I searched and stumbled upon this, might be interesting for you.
https://stackoverflow.com/questions/70350364/automatic-change-of-discord-about-me
Okay thanks, I will test it 😄
Lemme know if it actually works 👀
No working option found so far. Method not allowed 😄
Ah okay
I was wondering if it is possible to load files and pictures into the modal dialog without inserting links
Just read why
The About Me section on a bot's profile is not suitable for displaying information that changes regularly such as info about a certain song that's playing, ... because users would continuously need to refresh their clients to reload the cache and see the changes made.
Ah okay makes sense
You could just make a /info command tho
Yes
No
then i will try to collect after modal dialog submit
omg I success
@bot.command(name= "yo",description="create a game room")
async def createchannel(ctx, room_name:str):
guild = ctx.guild
channel = await guild.create_text_channel(room_name)
await ctx.send(channel)
Actually is it have a function to send a message while create the channel
mention please
Why is my emoji not displayed in the footer even though I use the string with ID?
embed.set_footer(text=f" • This is an autogenerated message. • {timestamp_str}")```
It works in the embed itself, but not in the footer
footers can't have markdown
Embed.set_footer takes an icon URL so if you can find a way to put the emoji somewhere that can be accessed via URL it would work very similar
just saw you posting the pic attached.
Is it okay to do it this way or should i change sth.?
# typical slash command start
if not ctx.user.guild_permissions.kick_members:
return await ctx.respond("some string here")
# other code
no that's fine
Thanks! 🙂
How do I fix this? Can't import commands on my vscode
uhh what
i'm trying to make a discord bot
it looks like code for azure machine learning, do note that discord bots are not generally artificially intelligent
Yea but it keeps showing me that
Yea when I write that and hits enter it changes it to that you see there
you probably have some type of text-replacement thing
I forgot what it's called in vsc
Snippets maybe?
I'm not familar with vsc to help you with that
Ooh so can I get atom then, will it stop?
@shell radish i think it's fixed it was an .py extension problem
atom is not longer getting updates
Okay no probs tho, it's fixed
@shell radish what about this one it's a problem I've been getting on two IDEs
Bot not bot
Ooh okay
Lemme change it
It showed another thing lemme screenshot
@shell radish
It says missing one required keyword
It says it's missing BotBase and I think it's missing commands and the commands wasn't imported 🤧
Pycord Docs - Intents
Discord API Docs - Gateway Intents
import discord
from discord.ext import commands
# Get specific intents for fine control
intents = discord.Intents()
intents.emojis = True
intents.guilds = True
intents.messages = True # Required for prefix commands!
...
# Get all non-priveliged intents; this excludes presences, members and message_content
intents = discord.Intents.default()
# Set priveliged intents: these must be enabled on dev portal
intents.members = True
intents.presences = True
intents.message_content = True # Required for prefix commands >= 2.0.0b5
# Get all intents; all intents must be enabled on dev portal.
intents = discord.Intents.all()
# Apply intents when creating your bot
bot = commands.bot(prefix="?", intents=intents)
?tag message-content
As of Pycord Beta 5, Discord API v10 requires message content intent to receive message content. This affects the traditional commands. Not enabling this intent will result in the messages' content, embeds, and components being empty.
You will need to enable the intent on the developer portal, as well as in your code:
intents = discord.Intents.default()
intents.message_content = True
bot = discord.Bot(intents=intents)
Docs: https://docs.pycord.dev/en/master/api.html#discord.Intents.message_content
Ooh okay lemme check it out
Tnx 🫶
But mine it shows workspace, compute target and others that are on the first screenshot
@shell radish this shows me gateway intents, but I'm searching for something related to commands?
#1132206148309749830 message
Whatever guide you are following is outdated as Slash Commands are the norm as opposed to Text-based Commands
Ooh okay someone told me to fix the client that it should be Client not client @shell radish
what
The clients on the other problem that brought me to this
Okay lemme run it and check if it works
@shell radish sorry I added the intents so how do I add the client?
If you are trying to learn how to make a Discord bot, I suggest following a more up-to-date guide, as opposed to an out-dated guide. Those tend do to so in a more logical progressions opposed to an out-dated one where many revisions are necessary
Yea I'm reading them now tnx just got a little confused there but I'll finish up and run it
But I'll just copy and paste this right?
How?
no
Aah okay but those intents given, which one am I to activate, typing and presence?
Or just leave it at default?
I recommend restarting from scratch
forget everything and start with a more up-to-date guide
is there a way to view the amount of memory used as cache by pycord
if so is there a way to alter it or clear without having to restart the bot
please remove the screenshots, they have your token visible.
when you do it like this:
with open("token.txt", "r") as file:
token = file.read()
bot.run(token)
and have nothing but the token in "token.txt" you can post full screenshots or screenshare in streams without risk someone stealing your token.
Nope
Generally when you cache, you make an opportunity costs of speed vs memory usage. Sure when you cache you increase performance, but you also increase memory usage as a result
And in fact, caching the data is arguably the only reason why you are not getting 429 bans. Because if you think about it, if you just request data constantly to the discord API, you will hit that rate limit. Do it too much and you essentially get banned by cloudflare for spam
So if you were thinking about removing caching in pycord, then don't
In fact, not only this principle can be applied to the discord API, but databases as well
This is effectively why I use Redis on my primary bot. All static config values, which are stored on Redis as JSON, will always be fetched first if found. If not, then we fetch from the db and update/rebuild the cached values instead
And you can also do this with a simple dict cache as well
And these config values are checked before running a feat that is either disabled or enabled
you guys made me curious about it! especially since I am about to change hoster and need to configer a new server soon.
Is there some avarage "expect memory usage of about xy per user/server" thing. I sure dont want the bot to mess around with swap nonsense
I also want to avoid paying for specs not needed ofc
nope some editors insert new line at the end
well, thats not hard to catch 😄
yeah str.strip()
@glad garnet pls delete that
Why is it that when you use paginator.edit() , custom_view are added to pages but they don't work (no matter how much I tried)?
(i already invalidated token)
I didn't see this :(
pages.append(Page(embeds=[embed], custom_view=self.view))
paginator = Paginator(pages=pages, custom_view = self.view)
await interaction.response.defer(ephemeral=True)
mess = await self.original_message.edit_original_response(embeds=[embed], view=paginator)
paginator.update_custom_view(self.view)
await paginator.edit(mess)```
I get this error when I try to connect the bot to a voice
RuntimeError: PyNaCl library needed in order to use voice
And I installed
pip install py-cord[voice]
Does anyone know what the problem is?
Install PyNaCl with pip
does it show up when you use pip show PyNaCl
Yes
How do you do this I thought it broke when they updates token length?
I upload to github gist to reset token
Don't worry I did it, someone tried using it
Idk what's wrong with people like this is a test bot what are they using the token for
Okay bro
someone having bot token can compromise your account
My discord account? Although discord help me reset it at first but I did it manually when I woke up
It can gain access to my account?
yes.
Why does someone need my account like they can just go to discord and open a new one
People do be crazy
discord didn't helped. tokens are reseted by Discord search service automatically when they uploaded to github (gist).
So how did you know they got uploaded to GitHub?
i upload
Upload stuff or mine?
i upload your bot token
Oohk it was you
can you render small images in embed filed names?
you can use emoji
I would love to have every command available with prefix and slash-command, I tried this but the '!' prefix doesn't work, is it possible in another way?
logging.basicConfig(level=logging.INFO)
bot = discord.Bot()```
why do you have discord.Bot and commands.Bot?
that is how I try to make prefix and slash command available, but it doesn't work
?tag cliends
No tag cliends found.
?tag clients
No tag clients found.
you mean prefix and slash in one?
nicee

Hey peeps, it's me again, lol
i'm dying again
😭
These discord librairies will literally KiLl me !
"Here is my nightmare since the last message I posted here ...
discord.errors.InteractionResponded: This interaction has already been responded to before
This interaction/message system is a joke, i'm totally stuck at this point
huh, i' would need a code review from a thug at this point. I have no idea how to deal with these buttons interactions and what i want to do ... 
Nope from what I can tell
So don't respond to an interaction more than once. >.>
ahah, didn't thought about that

anyone else ?
I read a bit trough the documentation topics, but I couldn't find anything about saving a users data. To be more specific, I would like to make a game in with my bot. Is it just as simple as creating a new savefile whenever a new user types some command and then changing the file of the user who is sending commands?
it's called using databases
SQLite is probably recommended for smaller bots, and PostgreSQL is recommended for larger ones
the drivers you should be using are asqlite for SQLite, and asyncpg for PostgreSQL
aiosqlite*
no i meant asqlite
A simple async wrapper for sqlite3. Contribute to Rapptz/asqlite development by creating an account on GitHub.
i still suggested connection pooling support for aiosqlite one month ago and yep...
anyone know why im getting this error:
Unclosed client session

your connection wasn't closed/ended correctly.
This can happen when your bots cpu usuage spikes to 100% for a moment and this "whatever makes it spike" isn't async.
It can also happen when your bot crashes and gets rebooted instantly or when you force kill the bot and instantly restart it.
can be messy code too ofc
that's all i got
do you use requests?
yeah
you know that it can break the bot?
well it works on my windows pc as well as when i host on aws
Is there a detailed guide?
and this code was literally just working and it just broke today
On using it with pycord, otherwise python?
you also could use MongoDB
await interaction.response.send_message("You clicked the button!") # Send a message when the button is clicked
self.disable_all_items()
await interaction.response.edit_message(view=self)
hmm doesnt get disabled HMMM...
Can persistent views be stopped with self.disable_all_items() or otherwise?
?
whats making issue is my send message. if i send message it doesnt self disable. all children items in the view. if i remove it it just disables normally.
sry my question wasnt related
i have a persistent view and want to know if i can stop it once it has been pressed once
you can disable it with that
it was working if I did it like that
how can i send a message, while still disabling it
without editing its content maybe deleting it?
i cant do more than two actions, edit andd then send message, it says "interaction. already has been responded to before."
you can remove the content
hmm lemme try
just edit the view
for some reason this gives me missing access, even though the bot had no issue editing its own message from within the command function
at the screenshot its not interaction
ohh
ty it works. as intented
thanks for spending your time helping us
np ^^
well even when i copy exactly what you have, i got a different error
lol
lastly can u tell me how can i make it useronly i forgot. like clickable by author only. and i think it doesnt exsist in /interactions/ui-components/buttons/
override interaction_check
show example
I don't have one handy, there should be examples in the repo
you mean on_interaction?
aight thanks ig
i think he means something liek this
async def interaction_check(self, interaction: discord.Interaction):
return interaction.user.id == self.author.id
yep exactly
oh
you want to respond though
ok ill try
wait so i do
if intereaction.user.id == self.author id.:
?
or what im kinda lost
yeah
kk
.tias
aight lol
just play with it you'll figure it out
but if you return False it won't call the button's callback
and True it will
hmm huh?
if you return False in interaction_check, the button's callback method won't be called
aighty
@discord.ui.button(label="AI Generation",row=0 , style=discord.ButtonStyle.secondary, emoji="🧠", custom_id="AI") # Create a button with the label "😎 Click me!" with color Blurple
async def ai_generation_button_callback(self, button, interaction):
self.disable_all_items()
await self.message.edit(view=self)
await interaction.response.send_message("You clicked the button!") # Send a message when the button is clicked
async def interaction_check(self, interaction: discord.Interaction):
if interaction.user.id == self.author.id:
return True
else:
return False
makes sense?
that will technically work, but you want a interaction.respond(message) in interaction_check for the False case
otherwise the user just sees "this application did not respond"
its wierd
File "/home/zeyad/Desktop/VORITEV3/vorite.py", line 18, in interaction_check
if interaction.user.id == self.author.id:
AttributeError: 'MyView' object has no attribute 'author'
now author isnt even attributed.
hmm
maybe its user?
still has no attribute
lemme just use innit and grab user
ctx.user
ctx.author
How do I do this self.value sort of thing in pycord? I did it in a different library but idk how to do it here. It doesn't seem to get past the if statement. I just want my command to know which button the user pressed.
you need to have an instance of RandomModifierButton
so py rmb = RandomModifierButton() ctx.edit(..., view=rmb) if rmb.value:
also next time send your code as code
?tag codeblock
Please put your code in a code block:
```py
Here is your Code
```
That makes reading code in Discord a lot easier:
print("This is an example.")
oh ye that makes sense
Yo tnx bro, for uploading my token on git, arigato 🙏
Xarlos also thinks you're a legend tho 🕊️
though the green button does disappear after i press it, for some reason it still doesn't get past my if statement. do you know why could that be?
do i need some other kind of await related to the view?
random_modifier_button = RandomModifierButton()
await ctx.edit(embed=embed_msg, view=random_modifier_button)
if random_modifier_button.value:
await ctx.respond("You pressed roll random modifier")
Someone know if it is possible to have 2 autocomplete options that updating the selection on discord?
my problem:
i choose option 1 that have Mining,Raid,Items
if i chose option 1 (mining) all works fine option 2 is also a autocomplete show the items from Mining
if i delete the option 1 and write Raid and go back to option 2 it show the Mining options on the select
if i delete all and reuse the command with Raid it works but only for the first selection
then i have the same issue with other category
you should add something that checks if the ones before are Noneor not
Is it possible to choose the options that will be in a select menu during a command? or do the options have to be defined in the class and cannot be changed?
You can pass the options when creating the select menu
but doesnt that mean i can't change them no matter what?
im kind of in a situation where it seems like i have to make 4 different select menu classes that do the same thing just because they need different options depending on a few factors in my command
just pass in the options in the init
@bot.command(description="create a game room")
async def notavailable(ctx, room_name:str):
guild = ctx.guild
button = Button(label="Close Channel", style=discord.ButtonStyle.blurple,emoji="")
channel = await guild.create_text_channel(room_name)
async def close_channel(interaction):
await interaction.response.send_message("")
embed = discord.Embed(
color =discord.Color.dark_purple(),
)
embed.add_field(name=f"Welcome",value="This channel is currently available for use", inline=True)
await channel.send(embed=embed)
#await channel.send(f"{member2.mention} {member3.mention} {member4.mention} {member5.mention}, this channel is now available for you to join.")
await ctx.send(f"Text channel: {channel} has been create")
Is it have a function which can delete a channel I'm trying to build a command which is similar with a ticket tool so what I am trying to do is Im going do the command and it will build a channel and the bot will automatically send an embed with an button which can delete the channel Im just create
so what I put to instead the send_message()
I think this not work because it is before anything will happen
Here i have a Video to better show
is the option in the command
@option("category", description="Choose your section!", autocomplete=get_items)
@option("item", description="Pick your item!", autocomplete=get_shops)
is the function for the options
@staticmethod
def get_shops(ctx: discord.AutocompleteContext):
"""Returns a list of animals that are (mostly) the color selected for the "color" option."""
picked_category = ctx.options["category"]
if picked_category == "Mining":
return [data["name"] for data in miningshop if data["name"].lower().startswith(ctx.value.lower())]
elif picked_category == "Raid":
return [data["name"] for data in raidshop if data["name"].lower().startswith(ctx.value.lower())]
elif picked_category == "Items":
return [data["name"] for data in mainshop if data["name"].lower().startswith(ctx.value.lower())]
else:
return ["NoSelect"]
@staticmethod
def get_items(ctx: discord.AutocompleteContext):
return [data["name"] for data in choices if data["name"].lower().startswith(ctx.value.lower())]
Why is your autocomplete not async?
it make no difference if i do
the same result, it was cause it dont show up if i do the async in class on a cogs
if i do outside of class then the async works but the same issue will happen
i see that the toolkit bot also can't handle autocomplete like that so maybe it is not possible to update a selection on edit the first option 😄
i tried it on /rtfm
Hi there!
Is there any way to know if the user is on the phone when he clicks on a button?
.rtfm Member.is_on_mobile
why?
@bridge.has_permissions(manage_server=True)
Invalid permission(s): manage_server```
it's manage_guild, not manage_server
hello
how do i add fields to an embed in a page?
To an embed in a paginator?
yes
discord.Embed#add_field
No, you can't do it like that in a paginator, that's only for normal embeds
Take a look at the example here: https://github.com/Pycord-Development/pycord/blob/master/examples/views/paginator.py
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - Pycord-Development/pycord
async def get_prefix(bot, message):
guild_id = message.guild.id
cursor = Database("prefixes.db")
prefix_db = await cursor.execute(q="SELECT * FROM prefixes WHERE guild_id = ?", param=(guild_id,), fetchall=True)
if prefix_db:
prefix = prefix_db[1]
else:
prefix = "*"
return commands.when_mentioned_or(prefix)(bot, message)
bot = bridge.Bot(intents=discord.Intents.all(), command_prefix=get_prefix)
why the bot not responding? no error on console
I'm trying to create custom prefix command for each guild
change this: prefix = prefix_db[1] to prefix = prefix_db[0]
that's return guild id
ah, ok. then, do you have any on_message event for your bot?
nope
i have another question
how do i add an image to that same embed?
i can't understand the example very well
embed.set_image(...)
is that it?
i thought it’s different in a page
It's explained like that
is there a way to set it so by default commands are not case sensitive
slash are case insensitive by default
if you're talking about text...
im asking for bridge
you can override on_message handler so it will first convert command to lowercase and then handle
that sounds like a terrible idea
it is
try to pass case_insensitive=True into your Bot init
I have it like that:
bot: Bot = Bot (
command_prefix=get_prefix,
intents=Intents.all(),
case_insensitive=True,
strip_after_prefix=True,
help_command=None,
)
case_insensitive... exists lol
im blind
and strip_after_prefix=True ;3
thanks worked
.close
Done with your help thread?
Please close your own help thread by using </close:1009144375709814897> with @rugged lodge.
Backup bot: </solved:1109625445990793246> (or
.solved) with @sly karma.
what does that do
it ignores spaces at the prefix commands
like !help would also would like ! h elp
oh
won't it affect the params?
no
does anyone know why my select menu won't show up when its supposed to? I cant get it to show up ever since passing my params into init. I don't get any errors, and it reaches the print statement print("edited message, waiting").
class RerollSelect(discord.ui.View):
def __init__(self, placeholder, min_values, max_values, options):
super().__init__(timeout=None)
self.value = None
@discord.ui.select(
placeholder=placeholder,
min_values=min_values,
max_values=max_values,
options=options
)
async def select_callback(select, interaction):
self.value = select.values[0]
self.stop()
await interaction.response.edit_message(view=None)
# my slash command
...
reroll = False
if rolled_random_modifier.name == "Re-roll 1 slot":
reroll = 1
elif rolled_random_modifier.name == "Re-roll 2 slots":
reroll = 2
if reroll is not False:
select = RerollSelect(
placeholder=rolled_random_modifier.name,
min_values=reroll,
max_values=reroll,
options=[
discord.SelectOption(label="Weapon", value="Weapon"),
discord.SelectOption(label="Armor", value="Armor"),
discord.SelectOption(label="Rig", value="Rig"),
discord.SelectOption(label="Helmet", value="Helmet"),
discord.SelectOption(label="Backpack", value="Backpack"),
discord.SelectOption(label="Map", value="Map"),
]
)
await ctx.edit(embed=embed_msg, view=select)
print("edited message, waiting")
await select.wait()
print(select.value)
You don't pass min, max, options and other stuff into your super in your custom class
And also... Creating so big dynamic views is... Inefficient at least
Yes? It's okay to create a lot of view classes. In my bot I have ~25 view classes
You can still dynamically create classes
what would be the right way to dynamically create classes?
Create options in init and create super duper callback
Just make really abstract callback which can handle your every possible scenario
well my select menu is going to do exactly the same thing no matter what the min_values, max_values, or options are. so from my understanding the callback isnt relevant, right?
All I want to know is what the user selected and do one thing, no matter what they select. It's just that the options might need to be different depending on which of those gear the user has available to reroll in the first place
And whether they get to reroll 1 item or 2 items is random
How are others handling testing? I've mocked out ApplicationContext and Interaction and have been testing my methods and callbacks that way, but I'm curious about what others do.
Wdym handling testing
I'm assuming theres not some quick/easy way to just.. make your bot leave a server
seems like you have to sorta custom write it in?
you just call guild.leave
async def get_prefix(bot, message):
guild_id = message.guild.id
cursor = Database("prefixes.db")
prefix_db = await cursor.execute(q="SELECT * FROM prefixes WHERE guild_id = ?", param=(guild_id,), fetchall=True)
if prefix_db:
prefix = prefix_db[1]
else:
prefix = "*"
return commands.when_mentioned_or(prefix)(bot, message)
bot = bridge.Bot(intents=discord.Intents.all(), command_prefix=get_prefix)
why the bot not responding? no error on console
I'm trying to create custom prefix command for each guild
*twitch*... I really really hate interaction message references.
As a response to a slash command, I send a message (ephemeral). One of the buttons should delete it. What method do I use to delete the message?
I've tried interaction.delete_original_response(), interaction.message.delete(), self.message.delete()... I always get Unknown Message or Unknown Webhook.
Use the interaction that sent the message to delete it
So something like ctx.interaction.delete_original_response()
I'm in a View, though. I thought Views had a .. uh, view ... into the interaction from the interaction param in the button callbacks?
Either way, there is no original context afaict
Then pass it in?
Definitely wish these low-level things were available by default. Having to pass in the cog (to access functions that the resulting View needs to do) and now the context is a little awkward.
But it does indeed work; thank you!
Although I guess if you're direct-instantiating a View class, it wouldn't have that. Hm.
Actually, I think this is another regression in 2.5. There's another View I haven't touched in ages that is suddenly not working.
get_prefix doesn't seem to be working with commands.when_mentioned
i tried it yesterday and got the error: command_prefix expects string or list from get_prefix return
Why haven't my slash commands registered like 12hrs since I switched its code base to pycord? I don't remember it taking that long. No errors and it works in my debug guild
Do you use discord.Bot or commands.Bot?
if you set a debug_guilds, it will only register in those guilds
Oh so I have to remove those
if you want to have the commands public, yes
do we have a git repository or something made in pycord that shows basic bot commands?
slash or prefix?
or both?
Here's the bridge commands example.
oh ty
that is both in one
tysm
Is it possible to get the type of device that uses an interaction. E.g embeds styled different for desktop and mobile so content is layed out differently
Desktop no, mobile yes
Could you elaborate a bit more
Cheers
bot.sync_commands() still causes the 'commands must be unique' error. 😐
Should I be doing something other than this?
@commands.command(name='reload', hidden=True)
@commands.is_owner()
async def owner_cog_reload(self, ctx, *, cog: str):
"""Command which Reloads a Module.
Remember to use dot path. e.g: cogs.owner"""
try:
self.bot.reload_extension(cog)
await asyncio.sleep(1)
await self.bot.sync_commands(force=True)
except Exception as e:
await ctx.send(f'**`ERROR:`** {type(e).__name__} - {e}')
else:
await ctx.message.add_reaction('👍')
why you're doing that
Because if I make a change to a slash command, I'd prefer not to restart my entire bot
Are you trying to prevent commands from functioning on cog unloading?
~~Not intentionally, no 🤨 ~~ No, that's not my goal (although it would be good to know how to do that)
I have a Cog. I update logic in a normal command; I can reload the cog and utilize those changes - ezpz. I make changes to a slash command and reload the Cog. Those changes are not reflected. My understanding is that you have to sync_commands to get that functionality, but the secondary issue is that Discord is giving 'commands must be unique'
So pretty much reload a cog to change the functionality of the commands inside of it.
Cuz that is an issue which hasn't been fixed yet.
Ah, okay. It seems to be spoken about as if it "can" be done, but is simply tempermental.
can someone explain why we have to use button parameter in our button callback even though it's not used and it makes pycharm angy?
why not mark it _
that seems to work thanks, i just dont understand it
Just like passing ctx in your commands, that's the callback signature. It may not be common to access it, but you (presumably) wouldn't have access to it any other way.
ctx isnt discord.Command
...wat. I'm just using an example of callback boilerplate
well i understand why u need ctx cos the command will fail if u dont respond to it somehow
Just loading unloading and reloading is all just a bit messed, as it doesn't really... It doesn't really change the logic of a command because the logic is cached... So it doesn't change until you restart the entire bot
##2015
in interaction case you use inter
meaning interaction, ctx is text command context (not command)
do you have the py-cord-dev?
Yes; that's what I'm currently attempting to use it with.
oh so im not the only facing this issue, been trying to reload_extension to edit cogs withtout restarting the bot but the changes are not reflected post-reload
Lmao no it's as I stated a known issue lol
Dont you have to add a command to the sync commands stuff?
how can i do a check to see if ctx.respond was used at least once? i.e. whether or not the bot has already responded to the user who did the command or not
why would you want to check that? if it doesnt go through for any reason you get an error.
edit, and you can "respond" to a slash command many many times if you want to
ctx.respond already handles responded interactions
i have a function which i use to make multiple edits to a message. i want to check if the message has been sent yet, and if not, change the first edit to a respond. if i respond and then call the function, it makes the first edit redundant
if that makes sense lol
gotcha
you could
try:
# edit x<
except discord.NotFound:
# ctx.respnd(#message here)
would that be an option?
thats what i was thinking, but im not sure if trying to edit a non existant message would cost time or something
everything costs a little time.. but its not that much and both things are awaited, so no big problem.
It seems to still raise an error and the command fails
try:
await ctx.edit(embed=embed_msg, view=None)
except:
await ctx.respond(embed=embed_msg)
even with the bare except
Weird, I could've sworn there was a property that was set when an intereaction was responded to
There's the InteractionResponded error that you can try/catch, but kinda jank
Oh. response.is_done
how do i check if pages.Paginator.on_timeout() has been called? trying to also cancel the thing when it gets timed out
Is there a way, how I can Safe Channel permissions and set them again after editing
how is the original embed posted?
Hello!
Ignoring exception in on_interaction
Traceback (most recent call last):
File "/home/container/.local/lib/python3.8/site-packages/discord/client.py", line 382, in _run_event
await coro(*args, **kwargs)
File "/home/container/.local/lib/python3.8/site-packages/discord/bot.py", line 1044, in on_interaction
await self.process_application_commands(interaction)
File "/home/container/.local/lib/python3.8/site-packages/discord/bot.py", line 736, in process_application_commands
await self.invoke_application_command(ctx)
File "/home/container/.local/lib/python3.8/site-packages/discord/bot.py", line 992, in invoke_application_command
await ctx.command.invoke(ctx)
File "/home/container/.local/lib/python3.8/site-packages/discord/commands/core.py", line 355, in invoke
await self.prepare(ctx)
File "/home/container/.local/lib/python3.8/site-packages/discord/commands/core.py", line 286, in prepare
self._prepare_cooldowns(ctx)
File "/home/container/.local/lib/python3.8/site-packages/discord/commands/core.py", line 266, in _prepare_cooldowns
retry_after = bucket.update_rate_limit(current)
AttributeError: 'coroutine' object has no attribute 'update_rate_limit'
async def misc_cooldown(message):
y = await timed_stuff_collection.find_one({"_id":message.author.id})
commonpremactive_amt = y["premium"]
if commonpremactive_amt == True:
return commands.Cooldown(1, 5)
else:
return commands.Cooldown(1, 10)
async def moneyearn_cooldown(message):
y = await timed_stuff_collection.find_one({"_id":message.author.id})
commonpremactive_amt = y["premium"]
if commonpremactive_amt == True:
return commands.Cooldown(1, 15)
else:
return commands.Cooldown(1, 30)```
i understand the problem that dynamic cooldown only works on def and not async def
but any way to to run it in async or since the await in y = await timed_stuff_collection.find_one({"_id":message.author.id}) is because of pymongo "motor" so its asynchronous
I want user_id = user and money = money in add_money_error
@commands.is_owner()
async def add_money(ctx, user: int, money: int):
user_id = str(user)
user_data = load_user()
if user_id in user_data:
user_data[user_id]['wallet'] += money
save_user(user_data)
await ctx.send(f"{user_id}號的錢包新增了{money}元\n目前有{user_data[user_id]['wallet']}元")
@add_money.error
async def add_money_error(ctx, error):
if isinstance(error, commands.NotOwner):
error.
user_id = str(error.args[0])
user_data = load_user()
await ctx.send(f"{user_id}號的錢包新增了{error.args[1]}元\n目前有{int(user_data[user_id]['wallet']) + error.args[1]}元")```
What are we supposed to help.you with
i want to get add_money's args in add_money_error
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...
how about mine xD
I mean you explained your error
Either use a sync client for the cooldown
Or cache whatever info you need
money = commands.Context.kwargs[1]```
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\Jimmy\AppData\Roaming\Python\Python311\site-packages\discord\ext\commands\bot.py", line 347, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Jimmy\AppData\Roaming\Python\Python311\site-packages\discord\ext\commands\core.py", line 942, in invoke
await self.prepare(ctx)
File "C:\Users\Jimmy\AppData\Roaming\Python\Python311\site-packages\discord\ext\commands\core.py", line 857, in prepare
if not await self.can_run(ctx):
^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Jimmy\AppData\Roaming\Python\Python311\site-packages\discord\ext\commands\core.py", line 1198, in can_run
return await discord.utils.async_all(predicate(ctx) for predicate in predicates) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Jimmy\AppData\Roaming\Python\Python311\site-packages\discord\utils.py", line 701, in async_all
elem = await elem
^^^^^^^^^^
File "C:\Users\Jimmy\AppData\Roaming\Python\Python311\site-packages\discord\ext\commands\core.py", line 2285, in predicate
raise NotOwner("You do not own this bot.")
discord.ext.commands.errors.NotOwner: You do not own this bot.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Jimmy\AppData\Roaming\Python\Python311\site-packages\discord\ext\commands\core.py", line 162, in wrapped
ret = await coro(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Jimmy\桌面\lunch-bot - 複製\main.py", line 117, in add_money_error
user = commands.Context.kwargs[0]
^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: type object 'Context' has no attribute 'kwargs'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Jimmy\AppData\Roaming\Python\Python311\site-packages\discord\client.py", line 378, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Jimmy\AppData\Roaming\Python\Python311\site-packages\discord\ext\commands\bot.py", line 387, in on_message
await self.process_commands(message)
File "C:\Users\Jimmy\AppData\Roaming\Python\Python311\site-packages\discord\ext\commands\bot.py", line 384, in process_commands
await self.invoke(ctx)
File "C:\Users\Jimmy\AppData\Roaming\Python\Python311\site-packages\discord\ext\commands\bot.py", line 351, in invoke
await ctx.command.dispatch_error(ctx, exc)
File "C:\Users\Jimmy\AppData\Roaming\Python\Python311\site-packages\discord\ext\commands\core.py", line 553, in dispatch_error
await injected(ctx, error)
File "C:\Users\Jimmy\AppData\Roaming\Python\Python311\site-packages\discord\ext\commands\core.py", line 168, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: type object 'Context' has no attribute 'kwargs'
The hell is that
You use the actual Context object
Not literally using it from the lib
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\Jimmy\AppData\Roaming\Python\Python311\site-packages\discord\ext\commands\bot.py", line 347, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Jimmy\AppData\Roaming\Python\Python311\site-packages\discord\ext\commands\core.py", line 942, in invoke
await self.prepare(ctx)
File "C:\Users\Jimmy\AppData\Roaming\Python\Python311\site-packages\discord\ext\commands\core.py", line 857, in prepare
if not await self.can_run(ctx):
^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Jimmy\AppData\Roaming\Python\Python311\site-packages\discord\ext\commands\core.py", line 1198, in can_run
return await discord.utils.async_all(predicate(ctx) for predicate in predicates) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Jimmy\AppData\Roaming\Python\Python311\site-packages\discord\utils.py", line 701, in async_all
elem = await elem
^^^^^^^^^^
File "C:\Users\Jimmy\AppData\Roaming\Python\Python311\site-packages\discord\ext\commands\core.py", line 2285, in predicate
raise NotOwner("You do not own this bot.")
discord.ext.commands.errors.NotOwner: You do not own this bot.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Jimmy\AppData\Roaming\Python\Python311\site-packages\discord\ext\commands\core.py", line 162, in wrapped
ret = await coro(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Jimmy\桌面\lunch-bot - 複製\main.py", line 118, in add_money_error
user = ctx.kwargs[0]
~~~~~~~~~~^^^
KeyError: 0
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Jimmy\AppData\Roaming\Python\Python311\site-packages\discord\client.py", line 378, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Jimmy\AppData\Roaming\Python\Python311\site-packages\discord\ext\commands\bot.py", line 387, in on_message
await self.process_commands(message)
File "C:\Users\Jimmy\AppData\Roaming\Python\Python311\site-packages\discord\ext\commands\bot.py", line 384, in process_commands
await self.invoke(ctx)
File "C:\Users\Jimmy\AppData\Roaming\Python\Python311\site-packages\discord\ext\commands\bot.py", line 351, in invoke
await ctx.command.dispatch_error(ctx, exc)
File "C:\Users\Jimmy\AppData\Roaming\Python\Python311\site-packages\discord\ext\commands\core.py", line 553, in dispatch_error
await injected(ctx, error)
File "C:\Users\Jimmy\AppData\Roaming\Python\Python311\site-packages\discord\ext\commands\core.py", line 168, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: KeyError: 0
This worked thank you
The docs state its a dict
Not a list
You have to actually read the docs and understand what it is
Otherwise you fall into basic errors like this
its possible to add a boolean checkbox to a modal?
no
get discord to add that
how
there image selection modal but it is Midjourney-only
how do you restrict bot from sending messages invoked by commands in specific channels? I tried disabling permission, the bot cannot even view the channel but he still responds to the commands in a private channel
the bot uses bot and application.commands scopes, no permissions granted by the api
app commands are never affected
bot always can respond because they are webhooks
yeah that's what I thought (I'm outdated)
so you have to go to Integrations tab in server settings
that didn't prevent the bot from sending response in #nosend channel though
what should I do? or is there some kind of delay?
how many are they?
14
@bot.slash_command(description="Veja todos meus comandos")
async def ajuda(ctx, comando : discord.OptionChoice(str, description="Escolha um comando", choices=ajuda_comandos, required=False)):
i think i used that discord.OptionChoice the wrong way tho
change discord.OptionChoice to discord.Option
the command list dont update
i got an error on console
it says the option value exceeds the maximum long value
do you have more than 25?
nah
i have 14
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In 2.options.0.choices.9.value: Option value exceeds maximum size (100)
ajuda_comandos = [
OptionChoice(name="/embed", value="Esse comando é usado para criar embeds de forma amigável para o usuário"),
OptionChoice(name="/ajuda", value="Mostra a lista de ajuda"),
OptionChoice(name="/info", value="É um comando simples, apenas mostra algumas informações básicas sobre o bot"),
OptionChoice(name="/ping", value="Mostra a latência do bot"),
OptionChoice(name="/mute", value="Muta/silência um membro. Use: `/mute <membro> <tempo> (motivo)`"),
OptionChoice(name="/unmute", value="Desmute/dessilência um membro. Use: `/unmute <membro>`"),
OptionChoice(name="/lock", value="Bloqueia um canal de texto contra usuários comuns, assim eles não podem falar."),
OptionChoice(name="/unlock", value="Desbloqueia um canal de texto contra usuários comuns, assim eles podem falar novamente."),
OptionChoice(name="/kick", value="Expulsa um membro do servidor. Use: `/kick <membro> (motivo)`"),
OptionChoice(name="/ban", value="Bane um membro do servidor, assim ele não poderá entrar novamente até você desbani-lo. Use: `/ban <membro> (motivo)`"),
OptionChoice(name="/unban", value="Desbane um membro do servidor, assim ele pode entrar de novo se desejar. Use: `/unban <usuário>`"),
OptionChoice(name="/addrole", value="Adiciona um cargo à um membro. Use: `/addrole <membro> <cargo>`"),
OptionChoice(name="/removerole", value="Retira um cargo de um membro. Use: `/removerole <membro> <cargo>`"),
OptionChoice(name="/delete", value="Deleta/apaga um canal de texto para sempre")
]
this are the options
The error is self explanatory, your option 9 (the /ban) value exceeds the 100 characters
And it indeed exceeds 100 characters
Hi, quick question.
Why do I get this error:
Traceback (most recent call last):
File "C:\Users\nuc\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ui\view.py", line 421, in _scheduled_task
await item.callback(interaction)
File "C:\Users\nuc\Documents\football-minigame\cogs\management.py", line 840, in select_filter_callback
await paginator.edit(await interaction.original_response())
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\nuc\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\interactions.py", line 348, in original_response
data = await adapter.get_original_interaction_response(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\nuc\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\webhook\async_.py", line 220, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook
this is the code at this point:
if description == '':
embed = discord.Embed(title=f'Spielerliste (gefiltert nach {select.values[0]})', description='Keine Spieler gefunden', color=discord.Color.red())
pages.append(Page(embeds=[embed]))
paginator = Paginator(pages=pages, custom_view=TradePlayerSelectionView(self.players), author_check=False)
paginator.remove_button("first")
paginator.remove_button("last")
await paginator.edit(await interaction.original_response())
page_number = paginator.children[1].label
do you replied?
yes, I think so
I have a button that creates a row of button when clicked. When I click one of the button Row I get a paginator with a select menu and when I select something in the select menu this code executes
whats the "app_commands" replacement in PyCord?
i want to use @app_commands.describe()
and this is not necesary?
That's not pycord
You pass the user to the view and compare with interaction.user
As a parameter...
As a parameter on the init
This is basic classes handling
im moving from discord.py to Pycord
py-cord doesnt have all the tree stuff
I have made a @bot.slash_command(name="commandsync") async def commandsync(ctx): await bot.sync_commands(guild_ids=[guild_id]) await ctx.respond("Synced locally")
to kinda refresh the slash commands after a bot.reload_extension, but im being hit with a
HTTPException 400: Invalid Form Body. In 7: Application command names must be unique
any ideas?
which version do you have?
?
2.4.1
check out #library-updates
alright, thank you.
worked like a charm, thank you again.
I won't help you with basic python
Plus already told you how
Plus it's something you should clearly know of you're working with OOP
#help-rules
It's not me, it's the rules
how do i create this text box?
hi
a
a




