#Basic Pycord Help
1 messages · Page 3 of 1
Here's the slash groups example.
ty
Learn all about Context Menus (User Commands & Message Commands) and how to implement them into your Discord Bot with Pycord!
thank you
does pycord have anything equivalent to discord.py's discord.ext.commands.Bot.setup_hook function?
.rtfm user.created_at
.rtfm discord.member
discord.Member.display_name
discord.Member.dm_channel
discord.Member.edit
discord.Member.fetch_message
discord.Member.get_role
discord.Member.guild
discord.Member.guild_avatar
discord.Member.guild_permissions
discord.Member.history
discord.Member.id
discord.Member.is_on_mobile
discord.Member.joined_at
discord.Member.jump_url
discord.Member.kick
discord.Member.mention
discord.Member.mentioned_in
discord.Member.mobile_status
discord.Member.move_to
discord.Member.mutual_guilds
discord.Member.name
Where can I find the stuff like joined_at, created_at etc.
It’s right there
what requirements would I need to put in requirements.txt to make sure this doesnt happen?
py-cord
like this?
And make sure that discord.py is uninstalled
Hello. How to place several embeds at once in one message?
embeds=[embed1, embed2]
Thank you
Did it work?
Yes
How to access the everyone role?
Why?
I need to assign permissions to the everyone role
Is it possible to make some kind of cooldown when pressing a button?
how do i see the id of user who pressed the button?
Are you getting any errors?
And what doesn't work with it?
yup
What error?
import discord
from discord.ext import commands
intents = discord.Intents.all()
bot = commands.Bot(command_prefix="*", intents=intents)
connections = {}
async def finished_callback(sink, channel: discord.TextChannel, *args):
recorded_users = [f"<@{user_id}>" for user_id, audio in sink.audio_data.items()]
await sink.vc.disconnect()
files = [
discord.File(audio.file, f"{user_id}.mp3")
for user_id, audio in sink.audio_data.items()
]
await channel.send(
f"Finished! Recorded audio for {', '.join(recorded_users)}.", files=files
)
@bot.command()
async def start(ctx: commands.Context):
"""Record your voice in MP3 format!"""
voice = ctx.author.voice
if not voice:
return await ctx.send("You're not in a vc right now")
guild_id = ctx.guild.id
if guild_id in connections:
vc = connections[guild_id]
else:
vc = await voice.channel.connect()
connections[guild_id] = vc
sink = "mp3"
vc.start_recording(
sink,
finished_callback,
ctx.channel,
)
await ctx.send("The recording has started in MP3 format!")
@bot.command()
async def stop(ctx: commands.Context):
"""Stop recording."""
guild_id = ctx.guild.id
if guild_id in connections:
vc = connections[guild_id]
vc.stop_recording()
del connections[guild_id]
await ctx.message.delete()
else:
await ctx.send("Not recording in this guild.")
bot.run("token")
Ignoring exception in command start:
Traceback (most recent call last):
File "C:\PySchool\3.10-32-bit\lib\site-packages\discord\ext\commands\core.py", line 178, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\rayen\OneDrive\Bureau\over power bots\newlibrarieslearning\record.py", line 38, in start
vc.start_recording(
File "C:\PySchool\3.10-32-bit\lib\site-packages\discord\voice_client.py", line 734, in start_recording
raise RecordingException("Must provide a Sink object.")
discord.sinks.errors.RecordingException: Must provide a Sink object.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\PySchool\3.10-32-bit\lib\site-packages\discord\ext\commands\bot.py", line 347, in invoke
await ctx.command.invoke(ctx)
File "C:\PySchool\3.10-32-bit\lib\site-packages\discord\ext\commands\core.py", line 950, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\PySchool\3.10-32-bit\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: RecordingException: Must provide a Sink object.```
@heavy sky
Just as the error says, you need to provide a sink object to start_recording(). Instead of just passing sink, you can pass discord.sinks.WaveSink
Also, take a look at the audio receiving example:
Here's the audio recording example.
To use MP3 you can also use discord.sinks.MP3Sink
hey I have a button that should send a paginator. The button is created in side a class. I get TypeError: Paginator.send() missing 1 required positional argument: 'ctx' I was wondering what context I need to put as an argument
Okey thnx
class GameView(discord.ui.View):
def __init__(self,idd,b):
super().__init__()
self.value = None
self.id = int(idd)
@discord.ui.button(label="1", row=0, style=discord.ButtonStyle.green)
async def button1(self, select: discord.ui.Select, interaction: discord.Interaction):
if interaction.user.id == self.id:
self.value = True
self.stop()
@discord.ui.button(label="2", row=0, style=discord.ButtonStyle.danger)
async def button2(self, select: discord.ui.Select, interaction: discord.Interaction):
if interaction.user.id == self.id:
self.value = False
self.stop()```
i have this view what is the line of code that disables specific button ?
If you want to disable button 1 for example on click, you can just add button1.disabled = True
How to send second message via interaction.response.send_message?
You can use interaction.followup.send
?
Thank you
owner = SlashCommandGroup(
name="cowner",
description="Commands owner",
checks=[
commands.is_owner().predicate
]
)
If I create this group of commands only the owner of the bot will be able to use them, but will the command be visible to all users?
How to access the everyone role?
.rtfm Guild.public_role
Target not found, try again and make sure to check your spelling.
Close enough
.rtfm Guild.default_role
Thank you
what context do I need to put in Paginator.send
it doesnt let me send it without context
The command context
but I am sending it through a button class
Anyone using mypy? I've never used it before, but the primary author on a bot we're working on is, and seeing a bunch of weird errors about discord.Option for slash commands:
use discord.Option[...] instead of discord.Option(...)
For this reason, he wants to move to decorators for slash commands ... which I think are super-unreadable, so I'm trying to avoid it 🙂 -- Anyone know why mypy is whining about instantiating a the Option class? Why would it suggest braces?
I use @discord.option()the whole time
decorators for function calls are much more difficult to read for me, so I'm hoping to keep function definition if possible.
But anyway, still trying to understand why mypy would complain about instantiating a class.
@fleet cedar havent you tried mypy?
is it possible to send a modal through a modal?
like when one modal is completed it opens a new one
Ty
Nope. Lol
No, you need to send a view with a button that opens another modal
I am trying to send a file but I get a errors about embeds. I am confuse
Ignoring exception in on_application_command_error
Traceback (most recent call last):
File "D:\Documents\bot discord\timed_role\.venv\Lib\site-packages\discord\client.py", line 378, in _run_event
await coro(*args, **kwargs)
File "D:\Documents\bot discord\timed_role\timeRoleBot.py", line 164, in on_application_command_error
await handler.handle()
File "D:\Documents\bot discord\timed_role\exceptions\ExceptionHandler.py", line 48, in handle
return await self._handle_unknown()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Documents\bot discord\timed_role\exceptions\ExceptionHandler.py", line 30, in _handle_unknown
await self.ctx.respond(embed=embed)
File "D:\Documents\bot discord\timed_role\.venv\Lib\site-packages\discord\commands\context.py", line 286, in respond
return await self.followup.send(*args, **kwargs) # self.send_followup
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Documents\bot discord\timed_role\.venv\Lib\site-packages\discord\webhook\async_.py", line 1745, in send
data = await adapter.execute_webhook(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\Documents\bot discord\timed_role\.venv\Lib\site-packages\discord\webhook\async_.py", line 221, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embeds.0.description: Must be 4096 or fewer in length.
what do you mean ?
yeah look here
File "D:\Documents\bot discord\timed_role\exceptions\ExceptionHandler.py", line 30, in _handle_unknown
await self.ctx.respond(embed=embed)
it's there where the error occurs
ooh I see, but why is it making a error in the first place ?
do I send the file the wrong way ?
the real error:
Application Command raised an exception: OSError: [Errno 22] Invalid argument: '{\n "application": null,\n "application_fee_percent": null,\n "automatic_tax": {\n "enabled": false\n },\n "billing_cycle_anchor": 1690915497,\n "billing_thresholds": null,\n "cancel_at": null,\n "cancel_at_period_end": false,\n "canceled_at": 1690947594,\n "cancellation_details": {\n "comment": null,\n ...
Some classes are just there to be data containers, this lists them. Unlike models you are allowed to create most of these yourself, even if they can also be used to hold attributes. Nearly all clas...
oooh I see, I should transform my str into a bufferIO
thank you !
I though str was consider a buffer in python 😅
perfect I just used io.StringIO() and it worked ! Thank you ! 🤩
Ignoring exception in command post:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.11/site-packages/discord/ext/commands/core.py", line 178, in wrapped
ret = await coro(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/evelone.py", line 52, in post
message = discord.Embed(title="Do you want to buy a product?", image="/home/container/buy.jpg")
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Embed.init() got an unexpected keyword argument 'image'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.11/site-packages/discord/ext/commands/bot.py", line 347, in invoke
await ctx.command.invoke(ctx)
File "/home/container/.local/lib/python3.11/site-packages/discord/ext/commands/core.py", line 950, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/container/.local/lib/python3.11/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: TypeError: Embed.init() got an unexpected keyword argument 'image'
I put my bot on the host. The host does not see the images that are uploaded to it. The path to the image is exact, the name is exact
Image is a method.
The error isn't even telling you about not finding the path
.rtfm Embed.set_image
And how to pave the way to it?
?tag localfile
Path: /home/container/buy.jpg
f = discord.File("some_file_path", filename="image.png")
e = discord.Embed()
e.set_image(url="attachment://image.png")
await messagable.send(file=f, embed=e)```
f = discord.File("some_file_path", filename="image.png")
e = discord.Embed()
e.set_image(url="attachment://image.png")
await messagable.send(file=f, embed=e)```
Ignoring exception in command post:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.11/site-packages/discord/ext/commands/core.py", line 178, in wrapped
ret = await coro(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/evelone.py", line 56, in post
file = discord.File("container", filename="buy.jpg")
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.11/site-packages/discord/file.py", line 99, in init
self.fp = open(fp, "rb")
^^^^^^^^^^^^^^
IsADirectoryError: [Errno 21] Is a directory: 'container'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.11/site-packages/discord/ext/commands/bot.py", line 347, in invoke
await ctx.command.invoke(ctx)
File "/home/container/.local/lib/python3.11/site-packages/discord/ext/commands/core.py", line 950, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/container/.local/lib/python3.11/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: IsADirectoryError: [Errno 21] Is a directory: 'container'```
I gave the exact path, changed "messagable" to "ctx" and it worked. Thank you!
Whyyy
You use somewhere tabs and somewhere 4 spaces
Use ide to automatically convert tabs to spaces or spaces to tabs
It's python thing and tbh I don't know why it works like that
¯_(ツ)_/¯
probably parser thing
Oh
This is to check every new line
any way to see how many boosts a user has given?
or can i only check for booster role to see if they've boosted at all
hey so i'm doing UI stuff and am getting this error (see attached 1). This error comes from this statement (see attached 2).
the thing is my PollSelect class inherits from discord.ui.View, which has a children attribute, and self.select inherits fromdiscord.ui.Item, so I don't understand why this is erroring.
Relevant code would be useful
you never initiated the parent class
no worries
its been a while since i've programmed in an oop language
Is there a way for deselecting the selected item in select menus?
https://docs.pycord.dev/en/stable/api/ui_kit.html#discord.ui.Select.options
https://docs.pycord.dev/en/stable/api/ui_kit.html#discord.ui.Select.values
https://docs.pycord.dev/en/stable/api/data_classes.html#discord.SelectOption.default
Some classes are just there to be data containers, this lists them. Unlike models you are allowed to create most of these yourself, even if they can also be used to hold attributes. Nearly all clas...
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...
Can you explain what should I do with these? I have already set the options and there is no default option. I want the selected option to be deselected after the user has selected it
if the option is selected, SelectOption.default would be true
iirc
It's not selected by default
I mean like in the callback of the select menu I want to reset it somehow
.
Not by default, even by the user
Ok
but if that's not true, you can "clone" the select menu and send that instead
the answer is no
i still dont know why there isn't something like that. setting things up during an on_ready event call is dangerous since it is not guaranteed to be called once
There is @client.once basically @client.event, but only called once. This is only on master branch at the moment.
check_once
Isn't there a helper to resolve/extract mentionables in a string (so that they will simply print their string equivalents)? Or did I make that up in my head?
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 ...
There also seems to be raw_*_mentions(for users, channels, and roles).
Interesting. Can I stuff a string into a PartialMessage or something like that? The intent is to sanitize incoming text from a slash command option
Yeah. Just didn't want to reinvent the wheel (e.g. copy code) if I didn't have to, but will figure something out
Came up with this, but unsure if I'm overcomplicating
def clean_content(ctx: discord.ApplicationContext, content: str) -> str:
channel_mentions = re.finditer(discord_channel_re, content)
for m in channel_mentions:
if channel := ctx.bot.get_channel(int(m.group(1))):
content = content.replace(m.group(0), f"#{channel.name}")
else:
content = content.replace(m.group(0), f"#{m.group(1)}")
user_mentions = re.finditer(discord_id_re, content)
for m in user_mentions:
if user := ctx.bot.get_user(int(m.group(1))):
content = content.replace(m.group(0), user.name)
else:
content = content.replace(m.group(0), "Unknown User")
if ctx.guild:
role_mentions = re.finditer(discord_role_re, content)
for m in role_mentions:
if role := ctx.guild.get_role(int(m.group(1))):
content = content.replace(m.group(0), role.name)
else:
content = content.replace(m.group(0), "Unknown Role")
return content
(...meh, it can't seem to get the channel by id)
Ah, I guess related to the issue of it not knowing what guild it's in.
do you have guild intents?
Oh! The guild thing is fixed - it needed to be a "bot", not just have application commands. Once I added send message ability, it now knows where it is.
Initially, it simply had application.commands because that's really all it needed. I still expected it to know where invocation was coming from, though
yeah, discord only gives you guild_id
I see, thanks
why this demo can't display font color?
Embed color isn't the font color
how can I add font-color like this?
That's just a link
OK, I see. 😅
Send your code
Hi guys simple question are discord bots able to execute slash commands on other bots?
hey for some reason I don't have persistent view even tho I gave the button a custom id and set the view timeout to none
yoo
im working on modals
and for some reason even though they take in a response and save data from the modal,
the modal doesn't close and shoes something went wrong
everythings fine tho it just shows something went wrongf.
No
Do you add the view on on_ready?
Here's the persistent example.
Are you responding?
can't do that
says it has already been responded to..
are you talking about
interaction.response.send_message ?
Yes
yea it shows an error
Show code
because
i respond to it before
@commands.guild_only()
@commands.slash_command(
name='createprofile',
description='Create a profile for Team Revenant server',
usage='/createprofile'
)
async def createprofile(self, ctx: ApplicationContext):
await ctx.defer()
data = retrieve_profile_data()
if str(ctx.author.id) in data:
return await ctx.respond("You already have a profile!\n`/profile` to view it.")
class ProfileButtonView(discord.ui.View):
@discord.ui.button(label="Create Profile")
async def button_callback(self, button, interaction):
await interaction.response.send_modal(ProfileModal(title="Profile Form", timeout=15))
button.disabled = True
await interaction.response.edit_message(view=self)
await ctx.respond("Please answer the modal within 15s", view=ProfileButtonView(timeout=15))```
on ready of the bot.event?
Move your view outside the command for everyone's sake.
And it's saying you already responded because you're sending the button and then trying to edit the message with response.edit_message
You should use interaction.edit_original_response
ah
Or a listener
ill fix the view later
it triggers me too
but i want to get the basic down first so
still shows thsi error
like its submitted
data has been filled in the file
but it still shows this
Modal code
Do you respond to the modal?
class ProfileModal(discord.ui.Modal):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.add_item(discord.ui.InputText(label="Current Valorant Rank"))
self.add_item(discord.ui.InputText(label="Peak Valorant Rank"))
async def callback(self, interaction: discord.Interaction):
data = {
interaction.user.id: {
"curr_rank": str(self.children[0].value),
"peak_rank": str(self.children[1].value)
}
}
with open('data/profile.json', 'w') as f:
json.dump(data, f, indent=4)
embed = discord.Embed(title=f"Profile Made - {interaction.user.name}", colour=discord.Colour.from_rgb(106, 0, 255))
embed.add_field(name="Current Valorant Rank", value=self.children[0].value)
embed.add_field(name="Peak Valorant Rank", value=self.children[1].value)
embed.add_field(name="Top Role", value=f"{interaction.user.top_role.name}")
embed.set_thumbnail(url=interaction.user.avatar)
await interaction.channel.send(embed=embed)```
if i respond to it well then
the button wont be disabled
and wont it clash with my button response
Why interaction.channel.send
You are not responding the modal
Interaction.response.send_message
Or interaction.response.edit_message
I get the following error when I try to click a button that sends a paginator:
File "c:\Users\Falco\Desktop\SneakerbotMain\bots\discord\pycord\discord\ext\pages\pagination.py", line 1176, in respond
msg = await interaction.response.send_message(
File "c:\Users\Falco\Desktop\SneakerbotMain\bots\discord\pycord\discord\interactions.py", line 904, in send_message
await self._locked_response(
File "c:\Users\Falco\Desktop\SneakerbotMain\bots\discord\pycord\discord\interactions.py", line 1198, in _locked_response
await coro
File "c:\Users\Falco\Desktop\SneakerbotMain\bots\discord\pycord\discord\webhook\async_.py", line 220, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction ```
I saw that response has to be up to 3 seconds, and follow up can be up to 15 minutes. how do I follow up with a paginator?
why are you doing await Paginator.respond(paginator, ...) 😭
you could do await paginator.respond(...)
thats basic python oop yk
Can Converters be used with slash command options?
just defer the interaction first. the library will handle the followup
yes
pass the converter parameter (undocumented iirc)
Oooh. So you wouldn’t change the type, just add the kwarg. Thanks
np
or wait
you probrably pass the converter as the type
💀
let me check
ok yes you pass the converter to the input type
sorry

@round heart ^
Hah okay, that makes it more consistent. Appreciate the follow up
Hello. I understand that cooldown is best done through timestamp?
Hi!
Question, how do I get button and interaction in the callback?
class Button(discord.ui.Button):
def __init__(self):
super().__init__(
label="-",
style=discord.ButtonStyle.red,
custom_id="callButton",
row=1
)
async def callback(self, interaction):
...
self is the button
And that's why learning OOP is important kids
Can't tell without more context 
so you're using types without type-hinting. great
Self doesn't need to be typehinted tho
I want to create a cooldown for commands and individual buttons. Would it be efficient to use datetime with timestamp?
For commands you could use the built in cooldown handler
You can also reuse the built in stuff for buttons with some setup
In all your examples, the callback has the button parameter. I separate my buttons from my views and I've had this problem for a while. I made a mistake but I'm trying to figure out how to fix it.
Only if you use a db as an intermediary, timestamp is useful
self is the button
in your case
When subclassing Button, self is the button
When subclassing View, self is the view 🙃
hi, stupid, I'm squid
Grrrr 
That doesn't change the fact that I can't disable it.
you have to edit the message with the updated view after disabling it
Try interaction.response.edit_message
Is it better to use built-in cooldown or a db with timestamp?
Built in cooldown is easy and customisable upto a large extent
I will try, thank you
How can I check that the entered member is a member? Should I resort to throwing a command error or using try-except?
if not member.bot:
I need to add an answer to if anything is entered instead of a participant
Just return a response?
I need to take into account several options for incorrect answers:
- Whether the entered data is a member
Is there a member on the serverIs the member a bot(this is what i decided)
Is there any way to check the first one without resorting to error "trapping"?
Like I said, just return a response
You're in a function
The return keyword doesn't execute anything below it
I'm sorry, but I didn't understand you. How can I check, for example, "aaaaa" and "deodjdn" are not users without catching errors?
You should already be typehinting discord.Member and the library does the check for you (if text commands) and throws an error.
Is catching errors a normal practice?
Yes... you should catch errors
You have to tell the user something went wrong. Or catch appropriate errors to handle the behaviour
I've always tried to avoid using error, considering all possible variations in the code but when I have to work with library models, I don't understand how to deal with the problem
🤷
I have a question that is for pymongo and not pycord
how do I find the last inserted document? I tried
client[str(interaction.guild.id)].address_profile.find_one().sort({"_id": pymongo.DESCENDING})``` and
```py
client[str(interaction.guild.id)].address_profile.find_one().sort({"_id": -1})```
but both dont seem to work and I get the error :
```TypeError: if no direction is specified, key_or_list must be an instance of list```
Don't be afraid of try/except
Is it possible to somehow respond during the cooldown?
is there anyway to create an invite to a voice channel@
in a way that like
bypasses permissions
so if someone doesnt have view & connect
but use the invite
they should br able to join
i thought this was already the case but apparently not
There's a new feature that lets people join voice without being in the server but I'm pretty sure it has to be public
I don't believe you can bypass permissions with an invite, that wouldn't really make sense
You could have them join a public channel and have the bot move them to a private one
it would tho
the idea was to create private voice channels only joinable by the link
You can do the whole "create your own VC" thing
i already got that part its just that when testin w friends i realised they cant actually join
is there a way to know if the command completed is ephemeral with on_command_completion?
Is there a way to access/specify the data type that a converter returns? Would be useful for static type-checking, and making sure I'm getting what I expect.
How to send a response message if the command is in cooldown?
With an error handler
One of the most appealing aspects of the command extension is how easy it is to define commands and how you can arbitrarily nest groups and commands to have a rich sub-command system. Commands are ...
you're probably looking for on_application_command_completetion, but you can use
await ctx.interaction.original_response() to fetch the message. I will refer to this as response_message
response_message.flags.ephemeral would be what you are looking for
specifically what type of convertor?
yeah i figured it was on_application_command_completetion after reading docs, will give this a go now. cheers!
I'm using these converters as part of a interactive input setup, for filling in forms that don't fit well in either command options (variable number of fields), or in modals (more than 5 fields).
What I'm working with:
class Context(discord.ApplicationContext):
bot: "Bot"
# --snip--
async def text_input(
self,
body: str,
title: Optional[str] = None,
embed_style: EmbedStyle = EmbedStyle.QUESTION,
converter: Optional[discord.ext.commands.Converter] = None,
):
#--snip--
coro = self.bot.wait_for(
"message",
check=lambda message: message.author == self.author
and message.channel == self.channel,
)
await self.respond(embed=embed, view=CancelButtonView(coro))
msg = await coro
return converter.convert(ctx=self, argument=msg.content) if converter is not None else msg.content # type: ignore [arg-type]
but what if on start?
Just pass disabled=True to discord.ui.button()
Can you override the checks for a group command, specifically to remove checks defined in the parent group? For example:
class ModCog(Cog):
root = SlashCommandGroup('mod', checks=[required_staff_level(StaffLevel.mod)])
@root.command()
async def warn(self, ctx, target: Member):
pass # Only mods should be able to run this command
@root.command() # ???
async def my_warnings(self, ctx):
pass # Anyone should be able to run this command
Nope. You should rather specify the checks only for the subcommands
OK. Guess I can just make my_warnings its own cmd...
Yea haha
When do i deferenciate between use ctx and interaction in a cog
because sometimes using ctx is fine sometimes it isnt
ty
hi, how to set a error handler to all select_callback?
Hi there, why should I choose Pycord over alternatives like discord.py or nextcord?
Other than ext.pages and voice receiving, the implementation of application commands is different. Pick which ever one you like
I chose Pycord for the guide pages 🙂 https://guide.pycord.dev/
Usually, there shouldn't be much difference in terms of usage for these three frameworks.
how to add description to bridge slash command option?
just how you would to normal slash cmds
@brave ore which one is the most actively maintained? I understand that Discord.py's development stopped for a long time, and resumed recently, so that's a concern.
You could test them if you work with an env
But may was saying after they switched from dpy to pycord, that pycord is way better and faster
I'm asking about maintainability, which isn't something I can test myself 🙂
Pycord is currently kinda "finishes" I would say
tbh, we are facing some issues with making pypi releases at the moment. the GitHub master branch is well maintained tho
Thanks! What are the reasons to maintain Pycord as a fork, now that Discord.py returned to active development?
Do I need to run kill 1 while working on Replit at any point? (aka restart cloud PC)
Ignoring exception in command reputation:
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 178, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\user\Desktop\Projects\Evelone\evelone.py", line 365, in reputation
await reputation.reset_cooldown(ctx=ctx)
TypeError: object NoneType can't be used in 'await' expression
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 347, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 950, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\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: TypeError: object NoneType can't be used in 'await' expression
Hello. I assigned a specific cooldown to the commands, but made sure that it was skipped in case of incorrect input. Everything works, only an error appears in the console.
The line await badreputation.reset_cooldown(ctx=ctx) works without errors in @client.command() but not in @badreputation.error
Does anyone know why my welcome message is being sent multiple times instead of just once?
here is the code :
@client.event
async def on_member_join(member):
welcome = client.get_channel(...)
if (member.guild.id == ...):
embed=discord.Embed(title="{}".format(member.guild.name), description="{}".format(member.mention), color=0xffffff)
embed.set_image(url="...")
embed.set_footer(text="{}".format(member.guild.name), icon_url="...")
button = Button(label="...", url="...", emoji="📃")
view = View()
view.add_item(button)
await welcome.send("|| {} ||".format(member.mention) ,embed=embed, view=view)
else:
pass
maybe you have other active terminal session that keeps running
that run the bot
is the same happening if you remove the () at the member.guild.id?
Also its getting triggert at every server, I had the same issue at the beginning
there are no active terminal session I've checked
it did not work
I want the bot to respond again to the buttons after the restart, which were available before the restart, but the class has arguments, so I don't know what to do
client.add_view(Name()) work if the class doesn't require arguments
What is it...
internal server error
then put arguments in there?
I don't know where to get them from in that place, they are local
async for member in ctx.guild.fetch_members(limit=None):
print(str(member.activity))```
why is this always `None`
do you have member intents?
Can you show it?
also at your bot?
wdym
where you define the bot
discord.Bot(intents=intents)
ok
weird
I get my activity
do you have it in a cog?
no
using ctx.author.activity?
member.activity
@client.slash_command()
async def test(ctx: discord.ApplicationContext, member: discord.Member):
await ctx.respond(member.activity)
I was trying is like this ^
ill try that maybe its something else going wrong
cannot send an empty message
but i have a status
does the user even playing something?
if i did ctx.author.activity it sends my status rn
but using the command u sent
it says cant send an empty message
it should send sdfdss
so yes
sort of
I got this
lemme open something and see if it wants that
its not a status
wdym
my custom status
i set calculator as my game and now it shows me the status?
but why doesnt it show me when they dont have a game
Its a activity not a status x3
Custom statuses are activities
yeah
.rtfm activity.Custom
Target not found, try again and make sure to check your spelling.
i want the custom status
what is with the raw one?
well it works now when i do the member.activity but still not this
just lots of nones
Are you sure discord.Activity has a to str method?..
Why don't you just use activity.name
because
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'name'
.rtfm Member.activity
And member.activities?
mhm
lots of ()
if it was intents wouldn't this not work either?
it also lets me use member.id but idk if you need intents for that
ah fixed it, apparently ctx.guild.fetch_members(limit=None) doesnt give activity data but ctx.guild.members does
class GameView(discord.ui.View):
def __init__(self,idd,board):
super().__init__()
self.value = None
self.id = int(idd)
self.board = board
# [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']]
emojify = []
toggles = []
for a in range(len(self.board)):
for b in range(len(self.board[a])):
curr = self.board[a][b]
if not curr == " ":
toggles.append(False)
if curr == "X":
emojify.append(":x:")
elif curr == "O":
emojify.append(":o:")
else:
emojify.append(":white_large_square:")
@discord.ui.button(emoji=emojify[0], row=0, style=discord.ButtonStyle.green)
async def button1(self, select: discord.ui.Select, interaction: discord.Interaction):
if interaction.user.id == self.id:
self.value = True
self.stop()```
code, error in `discord.ui.button` line:
```NameError: name 'emojify' is not defined```
yeah because it's defined at the __init__ scope
so what do i do?
oh i see now
i made one tab more
now it works, thank for pointing out
class GameView(discord.ui.View):
def __init__(self,idd,board):
super().__init__()
self.value = None
self.id = int(idd)
self.board = board
# [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']]
emojify = []
toggles = []
for a in range(len(self.board)):
for b in range(len(self.board[a])):
curr = self.board[a][b]
if not curr == " ":
toggles.append(False)
if curr == "X":
emojify.append(":x:")
elif curr == "O":
emojify.append(":o:")
else:
emojify.append(":white_large_square:")
@discord.ui.button(emoji=emojify[0], row=0, style=discord.ButtonStyle.green)
async def button1(self, select: discord.ui.Select, interaction: discord.Interaction):
if interaction.user.id == self.id:
self.value = True
self.stop()```
but now how do i acces the data?
what data
board
@bot.command()
async def test2(ctx, id:int):
guild = await bot.fetch_guild(id)
print(guild.members)```
whys this giving me [] if i have the members intent
what id do you give?
the id of my server
is your bot on the server which you are trying to fetch?
Do you have intents in your code and in discord devs portal?
In devs portal and passed as argument to your bot class?
because the API doesn't provide that info
oh so theres no way to get it?
the thing im trying to make ive seen other bots do it so idk how they do it
Is it normal practice to make a regular command and its copy in slash commands?
Here's the bridge commands example.
Not everyone likes the way dpy has implemented app cmds. And dpy doesn't have ext.pages, audio receiving etc
What is their essence?
idk how they work i just know they exist
Here's the bridge commands example.
Single cmd that is both, a slash cmd and prefix cmd
I have this as a command, instead of returning it like this how would i just get the name of the role
this is my current code
role_string = ""
for role in roles:
role_string += role.name
await ctx.respond(role_string)
You can do this in one line, but I did it this way for clarity
wouldnt that put them in one long line with no spaces
yeah that was something I was testing OP to do
oh ok
That stuff rarely happens 
I just figured it out as you sent that message
thank you though!
class GameView(discord.ui.View):
def __init__(self,idd,board):
super().__init__()
self.value = None
self.id = int(idd)
self.board = board
# [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']]
emojify = []
toggles = []
for a in range(len(self.board)):
for b in range(len(self.board[a])):
curr = self.board[a][b]
if not curr == " ":
toggles.append(False)
if curr == "X":
emojify.append(":x:")
elif curr == "O":
emojify.append(":o:")
else:
emojify.append(":white_large_square:")
@discord.ui.button(emoji=emojify[0], row=0, style=discord.ButtonStyle.green)
async def button1(self, select: discord.ui.Select, interaction: discord.Interaction):
if interaction.user.id == self.id:
self.value = True
self.stop()```
how do i get board in the middle of code
probably an xy question. I think there is a better way to go about achieving this
?tag xy
An XY problem is when you're trying to ask about your attempted solution, rather than your actual problem.
You are trying to solve problem X, using solution Y. Instead of asking for help with X, you ask about Y. This only results in frustration as whoever is trying to help you needs to ask several questions before even beginning to help you with your actual issue, wasting both their own, and your time. Always include as much information as you can about your problem, including attempted solutions. If there are solutions you've ruled out, include them along with an explanation as to why you've ruled them out.
@bot.event
async def on_presence_update(before, after):
print(after.status)```
why is this saying `idle` when im going offline
is that discord being weird
It can take some time to change
?
it triggers when it changes no?
if i go online -> offline it says i went online -> idle
Weird
Is it possible to send modal via command with prefix?
Nope. Modals can only be sent as responses to interactions
such as a message with a button
Time to learn slash_commands :]
Thank you
they are like the normal prefix commands
Here's the slash basic example.
@grim estuary check this out ^
Thank you. I can't find a parameter that will allow me to put a certain choice
- leaderboard
- by experience
- by level
- ...
Here's the slash options example.
@grim estuary ^
Thanks
Task exception was never retrieved
future: <Task finished name='discord-ui-view-timeout-4d58a3cf920547406e31fb5a0f3ba5a2' coro=<Profile.on_timeout() done, defined at C:\Users\user\Desktop\Projects \Evelone\evelone.py:697> exception=AttributeError("'NoneType' object has no attribute 'edit'")>
Traceback (most recent call last):
File "C:\Users\user\Desktop\Projects\Evelone\evelone.py", line 701, in on_timeout
await self.message.edit(view=self)
AttributeError: 'NoneType' object has no attribute 'edit'```
I don't understand how to access the message without using `message` inside `View`
You can pass in the message when you make the view
Unfortunately, I passed the message using ctx.message to View, but the error still appears
It started showing up after I changed the command to slash-command
Hello,
I would like to display only certain roles in an autocomplete (or is there also Choice?).
For this I have a list with the role ID's.
Now I want to check which role the user already has and then only all roles above this role should be displayed for him.
If he owns role 2, only all roles from role 3 should be displayed for him and be selectable.
Somehow I can't find a solution.
Here is my approach, maybe someone has an idea how I can implement this well?
Roles = [
ROLE_1_ID,
ROLE_2_ID,
ROLE_3_ID,
ROLE_4_ID,
ROLE_5_ID,
ROLE_6_ID,
]
async def select_role_autocomplete(self, ctx: discord.ApplicationContext):
guild = self.bot.get_guild(GUILD_ID)
# Liste der verfügbaren Rollen in aufsteigender Reihenfolge
roles = [guild.get_role(role_id) for role_id in Roles]
print(roles)
@slash_command(
name="promote_me",
description="Promote",
)
@option(
"role",
description="Select",
autocomplete=select_role_autocomplete,
required=True,
)
async def promote_me(self, ctx: discord.ApplicationContext, role: discord.Role):
Slash cmds dont have ctx.message
Which pycord version are you using?
The library will handle view.message for you
Sorry, but how can I watch this?
discord.__version__
v2.4.1
Does anyone have an idea how I can implement this? 🙂
@bot.event
async def on_presence_update(before, after):
print(after.status) # outputs idle
member = await after.guild.fetch_member(int(after.id))
print(member.status) # outputs offline```
im still confused if this is a bug or not but if i go on invisible/offline, `after.status` outputs `idle` which is wrong clearly
do i just have to do it the other way or am i doing something wrong
Does it still take an amount of time for slash commands to become available or should they be available immediately?
I think the SLA is still an hour but they can show up faster
What am I doing wrong so that the appropriate roles are displayed in the autocomplete?
async def select_role_autocomplete(self, ctx: discord.ApplicationContext):
guild = self.bot.get_guild(GUILD_ID)
# Liste der verfügbaren Rollen in aufsteigender Reihenfolge
roles = [guild.get_role(role_id) for role_id in Roles]
print(roles)
filtered_roles = []
found_user_role = False
for role in roles:
if role in ctx.interaction.user.roles:
found_user_role = True
if found_user_role:
filtered_roles.append(role)
# Erstelle die Liste der Rollen für die Autocomplete-Antwort
return [
role for role in roles if role.name.lower().startswith(ctx.value.lower())
]
@slash_command(
name="promoteme",
description="Promote.",
)
@option(
name="role",
description="Rolle",
autocomplete=select_role_autocomplete,
required=True,
)
async def promote_me(self, ctx: discord.ApplicationContext, role: discord.Role):```
yeah, but i actually am stupid and think i found the problem
the file with the code I was editing was in a different spot than the code i was running, lol. I was getting frustrated wondering why nothing was changing/working right!
That loop logic is a little bonkers
I am always shown all roles from the server and not just the filtered ones from the function.
The print also does not come at all when I call the slash command.
You can remove it and do return [role for role in roles if role in user.roles and role.name.lower()...]
Discord caches the autocomplete value for some reason
So it doesn't fire every time
no, they register immediately after Backend v2, which was like a year ago
I did it now but I still see all roles from the server.
async def select_role_autocomplete(self, ctx: discord.ApplicationContext):
guild = self.bot.get_guild(GUILD_ID)
user = ctx.interaction.user
# Liste der verfügbaren Rollen in aufsteigender Reihenfolge
roles = [guild.get_role(role_id) for role_id in Roles]
print(roles)
# Erstelle die Liste der Rollen für die Autocomplete-Antwort
return [role for role in roles if role in user.roles and role.name.lower().startswith(ctx.value.lower())]```
It is correct that I specify here that it is about roles or is the error here?
async def promote_me(self, ctx: discord.ApplicationContext, role: discord.Role):```
I hate it when that happens
i copied it to two places last night and for some reason opened one in vsc and the other in conda lol
now comes the fun part of converting my code from text commands to slash commands. so many places i have to replace "ctx.message" properly
wasn't there some secondary decorator you can use along with @bot.command() to limit the channels/servers the command shows up in (or can be used in)
ooh nice, easy enough
There's also permissions you can limit it to, but I don't think there's a decorator for channels
hmmm
i WAS running a block like this
i can probably just include that for the channel thing
slash command ctx still use "author"? like if i wanna pull the nick/id of the user it'd be ctx.author.id and ctx.author.display_name?
Yes
nice
so most of this is probably just going to be me deleting .message from a bunch of strings :D
Search and replace
naw i'm doing it by hand so i dont miss oddball cases
i prolly should rewrite this and use cogs or something, since that seems to be the organizational structure provided lol
but like ctx.channel.send(embed) will still work, right
Sorry I'm just trying to double check a few things as I go to make sure its gonna work as expected (or not)
You should definitely use cogs
Even if you throw everything in one cog
Having it in a class, with self, and instance variables instead of using global... Highly recommend
after.status says idle instead of offline for only certain people why is it being weird.
i thought it was everyone but ive seen it say offline for 2 pepole now
Ask discord
probably a dumb question but im new to coding n idk why this error is popping up
ctx.respond()
is there any specific reason why its that or is it just basic
Its just basic
You're responding to an interaction, not replying to a message
yeah I may do a whole rewrite of it
I dont fully understand cogs so i gotta figure out what they are even lol
right now my bot is basically a list of commands and then also functions that create embeds, and then a few files of settings/functions that get imported into the main file
does use a bunch of global vars though. like, it's a game with a timer, and I abuse dictionaries for everything
like game_is_active[server_id] = True/False
Love dictionary abuse
and yeah, def lol
this thing uses tinydb for its persistent score database
the other stuff idc about persistence
Never heard of tinydb
its just a db format
i picked it cuz its what google told me lol
works fine, its just a list of dicts more or less
soo, ofc i like it
how might i update an embed with new values on a command?
i have a command which sets up like this https://cdn.discordapp.com/attachments/1073286715151765604/1137189398660784198/image.png
and in the usage of a different command, I want those values such as budget and players on the team to update
im trying to figure out how to edit the message effectively without rewriting the whole list of embeds every time I want to update
Anyone have a code to get the guilds number of active members
Like this:
You need to use discord.Option and specify autocomplete
Autocomplete can only be string type
You should return a list of discord.SelectOption with name as role name and value as role id
Hello. Is it possible to write a separate line of code if the participant opened the modal but canceled the submission?
Like this?
return [{"name": role.name, "value": role.id} for role in filtered_roles]
async def promote_me(
self,
ctx: discord.ApplicationContext,
rolle: Option(discord.Role, autocomplete=select_role_autocomplete),
):```
So it doesn't work either because every role from the server is displayed:
discord.ext.commands.Bot not automatically sync slash commands
Why?
@bot.command(description="Sends the bot's latency.")
async def ping(ctx: c):
await ctx.send(str(bot.latency))```
Input type should be str
.rtfm discord.selectoption
@bot.command(...) is a prefix command when using ext.commands.Bot
Why do you use commands.Bot for only slash commands?
Use @bot.slash_command(...)
Discord doesn't send any event if user cancelled the modal. You will need to use on_timeout in the modal class
is there any better way to edit an embed rather than fetching the id of the message and editing it like that
its really slow
i have a command which sends multiple embeds
and i have another command which edits them but it fetches the embed message by id first
this usually has like a 5 second delay between the edit and the command
any faster way to do this?
Thank you. And one more question. How to change the cooldown of a certain person?
because i want use and @bot.event on_message and slash_command
?
?tag clients
No tag clients found.
?tag client
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
bridge.Bot # above + bridge commands (application commands and text commands in one)
@south sinew ^
is there a faster way of editing a message than getting it by id and editing it?
when i do a command, i want to edit embeds sent from a previos command
currently i fetch the embed message by id but this poses a 5ish second delay between the command and the edit of the embed
is there a more efficient way?
My discord.Bot does not see message.content in the on_message event. For this reason I used Commands.Bot
If I do it this way I get an error
async def select_role_autocomplete(self, ctx: discord.ApplicationContext):
return [{"name": role.name, "value": role.id} for role in filtered_roles]
async def promote_me(
self,
ctx: discord.ApplicationContext,
rolle: Option(str, autocomplete=select_role_autocomplete),
):```
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body```
Is it possible to select multiple channels option?
Why discord.Bot does not see message.content in the on_message event?
Show code
@bot.event
async def on_message(message: discord.Message):
print(message.content)
if message.author.bot:
return
await message.channel.send("Hello!")```
Show your intents
and content is empty
intents = discord.Intents().all()
intents.message_content = True
client = discord.Bot(intents=intents)
@client.event
async def on_message(message):
print(message.content)
if message.author.bot:
return
await message.channel.send("Hello!")```
The line intents.message_content = True is not needed
Just a minute ago I was doing the same thing and it wasn't working for me. Thanks again - that solved all my problems 😁
could anyone help me with some message editing?
when i do a command, i want to edit embeds sent from a previuos command
currently i fetch the embed message by id but this poses a 5ish second delay between the command and the edit of the embed
@client.slash_command(description="description")
@commands.cooldown(1, 86400)
Using this, cooldown is one for all. How to issue an individual cooldown?
@commands.cooldown(1, 2, commands.BucketType.member)``` try this?
class GameView(discord.ui.View):
def __init__(self,data): # get
super().__init__()
self.value = data
data = data + "" # refactor
@discord.ui.button(label=self.data, row=0, style=discord.ButtonStyle.green) # acces
async def button1(self, select: discord.ui.Select, interaction: discord.Interaction):
if interaction.user.id == self.id:
self.value = True
self.stop()```
I have this view, and how do i get, refactor and use variable in the `@discord.ui.button()` line.
i tried storing the message in a variable and using that variable.edit in other commands but it didnt work
await updembedMC1.edit(embed = updembedMC2)
NameError: name 'updembedMC2' is not defined
.tag partial
Partial Objects
These can be used to make API calls when you have channel id and/or message id, and you don't want to rely on the cache to have their objects.
Methods which can be used on them are -
- Partial Messageable (analogus to a Channel) : https://docs.pycord.dev/en/stable/api/models.html#discord.PartialMessageable
- Partial Message (analogous to a Message): https://docs.pycord.dev/en/stable/api/data_classes.html#discord.PartialMessage
Example Usage:
async def star_message(channel_id: int, message_id: int):
# Get Partial Messageable object. Docs-
# https://docs.pycord.dev/en/stable/ext/commands/api.html#discord.ext.commands.Bot.get_partial_messageable
partial_channel = bot.get_partial_messageable(channel_id)
# Get Partial Message. Docs-
# https://docs.pycord.dev/en/stable/api/models.html#discord.PartialMessageable.get_partial_message
partial_message = partial_channel.get_partial_message(message_id)
# Add a reaction
await partial_message.add_reaction(":star:")
You just need the message id and channel id
im trying a different method
or at least trying to get it to work
updembedLV1 = await ctx.channel.send(embed=updembedLV)
this is in one command
await updembedLV1.edit(embed = updembedLV2)
this is in another command
why do i get this error?
name 'updembedLV1' is not defined
Variable scoping
i tried making it a global var
Bad idea
how else would i do it?
Multiple users could be using your bot, how will you determine which message is for which user?
wdym
Do it in the init. Remove the label parameter from the decorator
Then do self.button1.label = data in the init
Two people are using the commands, how will you distinguish which message to edit when both of them use command 2
in the command you have to input a 'team'
and based on that team it'll edit the message
Return discord.OptionChoice, not a dict
(Sorry I confused it with SelectOption earlier)
regardless, im the only one that will be able to use this command
Need to keep track of a variable between functions? No problem!
⚠️ Careful what you name it though, else you might overwrite something ⚠️
Just add it to your commands.Bot or discord.Client instance like so:
bot = commands.Bot(...)
bot.my_variable = 0
async def foo():
bot.my_variable += 1
# In a cog
@commands.command()
async def counter(self,ctx):
await ctx.send("Current Counter is at {}".format(ctx.bot.my_variable))
This also allows you to access this from other cogs/extensions/functions. Anywhere you have access to the bot instance
how would i store something like this in it?
without it being sent
is there any way to make the command visible to those with permissions, the only thing I have found is to limit it and show an error message in case they don't have it, @fleet cedar
Wdym by "without it being sent"
You can use default_permissions
Here's the slash perms example.
like this you mean?
yes I know, but it is still visible to the users in my case I am using it like this
@discord.slash_command(name="config", description="Configure the server")
@discord.default_permissions(
administrator=True
)
async def config(self, ctx):
bot = discord.Bot(intents=discord.Intents.all())
bot.value = my_value
thats what i did no?
and why don't you save only the embed content?
wdym
oh because i want to be able to do bot.updembedSN1.edit anywhere
what would i do about the 'await' and 'ctx' problem?
?
is this within a function or outside?
inside
can bot.embed be referenced in other functions?
like bot.embed.edit?
in other functions
look at the example
oh

:)
would it be ctx.bot.updembedMU1?
What you are trying to store is a message impression, you are aware of that, aren't you?
yeah
and im trying to edit that message in a different command
just want to edit a message?
Anyone have a code to get the guilds number of active members
then save only the Embed object
yes
you also need the message object in order to edit it
yeah
it can be reset by admins from the guild settings page
so make sure that is correct

now I look at it
yeah default_permissions can be changed by admins
otherwise use local checks like (ext.)commands.has_permissions
in the case that I only want to make a command visible to the bot owner I use the @commands.is_owner()
I want to make an individual cooldown that depends on the role used.
I use this to set the main cooldown.
@commands.cooldown(1, 43200, commands.BucketType.member)```
I use this to reset the cooldown in case of an error.
```py
await command_name.reset_cooldown(ctx=ctx)```
But it is considered as `NoneType` in `Modal` and `View`.
I use this line to update the cooldown according to the role.
```py
command_name.cooldown.per = cooldown```
But it certainly changes the cooldown value for everyone.
What should I change?
anyone know why this isnt removing anything
with open("data.json", "w") as json_file:
data["playerrosters"][index].remove(player.display_name)
print(index)
json.dump(data, json_file)
?tag nojson
Why not to use json files for data storage
JSON files are commonly used to store data that is read by a program, however, they are unsuitable for storing dynamic data due to a number of reasons.
It is recommended to use a DBMS (Database Management System) as they come with optimized technologies for storing and retrieving information.
Advantages of using a database:
- Database tables can be related, making it easy to separate your information into multiple tables and only fetch what you need
- Databases allow you to use a query/data processing language to make complex data operations easier with less code
- One misplaced character will corrupt an entire file. A database very rarely experiences corruptions due to their automatic handling of data integrity
- Transactions in SQL databases allow you to revert unwanted changes and prevent data corruption in the case of an error
- Databases have support for indexes, allowing retrieval of some data to be extremely fast
- It is very easy to update existing data in a database, as opposed to re-writing a file
- Databases are reliable
Popular database management systems:
- SQLite3
- MongoDB
- PostgreSQL
- MySQL
- MariaDB
- Microsoft Access
also dont use name, use the user id
i display the name in an embed i send
If this cannot be fixed, then I will switch to a cooldown through the databases
@{group_name}.command before your command
Im not sure if it works with slash and message command in one?
yes
That would make it visible to others too, but only you will be able to use it.
Rather specify a private guild's id, which only you are a member of
Context menu Message commands don't have groups
Use dynamic cooldown
Here's the cooldown example.
Thank you
how do i give a name (with spaces) to a slash command
Afaik you can't add spaces to command names, but if you mean something like the screenshot, then you can use command groups https://guide.pycord.dev/interactions/application-commands/slash-commands#sub-groups
Learn all about Slash Commands and how to implement them into your Discord Bot with Pycord!
kk thanks
can i make a param that receives discord.member class data but still input ID when invoking the command
Does anyone know why my welcome message is being sent multiple times instead of just once?
here is the code :
@client.event
async def on_member_join(member):
welcome = client.get_channel(...)
if (member.guild.id == ...):
embed=discord.Embed(title="{}".format(member.guild.name), description="{}".format(member.mention), color=0xffffff)
embed.set_image(url="...")
embed.set_footer(text="{}".format(member.guild.name), icon_url="...")
button = Button(label="...", url="...", emoji="📃")
view = View()
view.add_item(button)
await welcome.send("|| {} ||".format(member.mention) ,embed=embed, view=view)
else:
pass
- And I changed the bot token several times, but this problem is only in a certain server, there is no problem in other servers, could this problem be from Discord or server settings?
found my answers
@shell radish I officially switched to discord.py and have no plans of switching back 
Ty for all your help
I'm using Replit, and when I install Pycord, it installed discord and discord.py
So, I uninstalled them.
Now, I'm getting
AttributeError: module 'discord' has no attribute 'Bot'
?tag replit
?tag replit
Installing Pycord with Replit (only use replit as a last resort) - pycord-replit-install.md
Installing Pycord with Replit (only use replit as a last resort) - pycord-replit-install.md
I am using Docker with a start.sh and when I use -u it shows me all the logs. Does this have any changes or problems or something. Without -u it doesn’t show the logs
error:
AttributeError: '_EnumValue_ButtonStyle' object has no attribute 'disabled'
code snipped:
self.button1.disabled = toggles[0]```
toggles[0] = True
Can you show your code? If you're disabling the button in the callback, just do button1.disabled = toggles[0]
i am disabling them in the __init __
is there an easier way to see if a slash command has been executed on the bot and then send a log message via webhook, other than setting the log message directly after the ctx.respond() in each individual cog file?
possibly an on_slash_command event?
on_interaction and interaction.type
.rtfm on_interaction
thanks!
with buttons that should surely work too, right?
Is there a way I can count a specific message keyword in a channel?
I installed Python 3.11 with pip, added the link to pip in PATH, but it still doesn't see it on the command panel. How can I fix this?
i like accidentally installed discord.py so i uninstalled it and now pycord dont work
File "bot.py", line 2, in <module>
from discord import option
ImportError: cannot import name 'option' from 'discord' (unknown location)
and installing it again just saying its already installed
can you show the full pip list?
pip freeze > pip.txt
i just uninstalled pycord and reinstalled it and i think it worked?
pycord or py-cord?
py-cord
Hi can u help me?
I got error Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
when i use this command
async def rolee(ctx, first: discord.Option(discord.Member), second: discord.Option(discord.Role)):
await first.add_roles(second)
await ctx.respond("Yep")```
Missing Permissions
But bot is admin
yes, try to reinvite
Is your bot's role above the role you're trying to add?
Reinvite didn't help. Any roles do not work, not Admin or Mute
Your bot's role needs to be higher in the list
It can't assign roles above its own role
Does the order of roles matter? omg its realy work
yes
on_application_command 😭
how to differentiate nitro with non nitro users man 🙃
How would I grab the server id without ctx?
Can you elaborate?
I need to grab the guild id of a server but only the guild id as i am using for storing configs
you can access bot.guilds
it doesnt work though as it just responds with: AttributeError: module 'discord.guild' has no attribute 'id'
Can you send the code
def check_near(place):
townSpawn = requests.get(EarthMC_API + "v2/aurora/towns/" + place).json().get("coordinates").get("spawn")
onlineHunters = check_online_hunters()
nearbyHunters = []
with open("config.json", "r") as f:
config_data = json.load(f)
for hunter in onlineHunters:
if math.isclose(townSpawn.get('x'), hunter.get('x'), abs_tol=config_data.get(discord.guild.id).get('radius')) and math.isclose(townSpawn.get('z'), hunter.get('z'), abs_tol=1000):
print("Hunter Spotted! Name: " + hunter.get('name'))
nearbyHunters.append(hunter)
print(nearbyHunters)
return nearbyHunters
?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.")
sorry
Yeah discord,guild.id isn't going to work, can you pass in your bot to that method?
What calls that method
i can pass it in
its being called from a task
I have the database in mongoDB, is it better to use motor, to use it asynchronously than to use pymongo?
so if I pass a ctx object to another python file (like if i have bot.py and game1/functions.py and i do game1.functions.checkanswer(ctx) will game1.functions be able to access the properties/methods associated with ctx without having to import discord? I'm assuming once it's been made, the vars/functions etc are attached to the object itself
granted I could just import discord into every file in this thing to be sure but I don't think i NEED to? feels messy
like I feel like i would only need to import discord if I wanted to use functions/constructors in the discord module, but not objects already created
though i guess if i'm importing submodule.py into main.py and running submodule.function() it's running submodule.py code in the context of main.py anyways? hmm. sorry, more of a general python question than a pycord question i guess
yes otherwise your bot's performance will decrese drastically.
pymongo is blocking meaning no other operations can occur whilst pymongo is doing something
reading doc, updating doc etc
how would i edit an embed with an image thats saved to my computer?
currently im trying this
lineupLV1.set_image(url="liverpool.png")
but im getting this error
400 Bad Request (error code: 50035): Invalid Form Body
afaik you can't put local images into embeds
so you either upload it to discord yourself and copy the link or put it on a website
you can
i tried it never worked for me
?tag localfile
f = discord.File("some_file_path", filename="image.png")
e = discord.Embed()
e.set_image(url="attachment://image.png")
await messagable.send(file=f, embed=e)```
yea that didnt work when i tried it but maybe it does
and if you try it with first the embed and then the file?
do i do attachment://liverpool.png
you reckon that would work?
Its working fine for me
Hi! Can anyone please tell me a way to create a dm-only commands for bot?
Regular bot.command() ones only seem to work in guilds
there is no dm-only commands, but you could read the message content and respond accordingly?
Via on_message event?
yes
So it is only possible with message content intent?
to my knowledge yes
Alright, thanks
there is a decorator for it @upper flint
whats the decorator?
same for guild_only
I see, good. But is there a way to hide it from guild commands?
Right now i can see it when typing in bot dm and in any guild the bot is in
What's the routine to edit the message containing the select menu, i.e. select > edit the message. I have tried both:
discord.Interaction.edit_original_message discord.Interaction.edit_original_response
with no luck (these both edit the interaction response, not the original message)
discord.File(f, filename="attachment://napoli.png") like this right?
lineupSN1 = discord.Embed()
with open("napoli.png", "rb") as f:
pictureSN = discord.File(f, filename="attachment://napoli.png")
lineupSN1.set_image(url=pictureSN)
this is my code
im getting the same error
filename in discord.File should be napoli.png only
the url should be attachment://napoli.png
so i dont need with open?
pictureSN = discord.File("napoli.png", filename="attachment://napoli.png")
uh no
oh wait
im silly hold on
pictureSN = discord.File(f, filename="napoli.png")
lineupSN1.set_image(url="attachment://napoli.png")
like that?
yess
perfect
alright let me try it
you can let discord.File open it for you. that way you can skip the with open
you will need to pass the path instead of f
could i just put "napoli.png" since the code and image are in the same folder
or
.tias
will mostly work
alright
if with open("napoli.png", "rb") works then this ^ should work too
have you already sent a response but also want to edit the message the select menu is attached to?
use interaction.message.edit
Still not quite working...
return [
discord.OptionChoice(name=role.name, value=role.id)
for role in filtered_roles
]```
In data.choices.0.value: Could not interpret "1132358908522434640" as string.
In data.choices.1.value: Could not interpret "1131968976482865448" as string.
In data.choices.2.value: Could not interpret "1131969634553267250" as string.
In data.choices.3.value: Could not interpret "1113454359431590701" as string.
In data.choices.4.value: Could not interpret "1131969155345198561" as string```
uh thats weird
that usually works
how about str(role.id)
Yes, thank you!
This is what works. In the function I then have to convert it back to int to search for the role
also
in this line pictureSN = discord.File(f, filename="napoli.png")
would i need to reference pictureSN anywhere else?
should be trivial 🤷♂️
i think thats why it probably isnt working
lineupSN1 = discord.Embed()
pictureSN = discord.File("napoli.png", filename="napoli.png")
lineupSN1.set_image(url="attachment://napoli.png")
await ctx.bot.setupembedSN1.edit(embed = lineupSN1)
f = discord.File("some_file_path", filename="image.png")
e = discord.Embed()
e.set_image(url="attachment://image.png")
await messagable.send(file=f, embed=e)```
this sums it up pretty much
oh so
.edit(file=pictureSN, embed=lineupSN1)?
yes iirc
Thank you!
anyone know anything about pillow?
i emailed discord abt the whole on_presence_update saying idle instead of offline and they told me to ask in the discord devs server and they just said its probably not discord or pycords fault so what am i meant to do
@hallow copper made their music player with pillow iirc
I did:)
do you mind helping me out with some issue i have?
I'm a lil busy but you can dm me and I can see wut I can do!
👍
hm. is there a good way to go from a userID back to a nickname? this is after its been separated from ctx so I can't just go ctx.user.name
or whatever it is
.rtfm fetch_user
discord.ext.commands.Bot.fetch_user
discord.ext.commands.Bot.get_or_fetch_user
discord.ext.commands.AutoShardedBot.fetch_user
discord.ext.commands.AutoShardedBot.get_or_fetch_user
discord.ext.bridge.Bot.fetch_user
discord.ext.bridge.Bot.get_or_fetch_user
discord.ext.bridge.AutoShardedBot.fetch_user
discord.ext.bridge.AutoShardedBot.get_or_fetch_user
discord.Client.fetch_user
discord.Client.get_or_fetch_user
discord.AutoShardedBot.fetch_user
discord.AutoShardedBot.get_or_fetch_user
discord.AutoShardedClient.fetch_user
discord.AutoShardedClient.get_or_fetch_user
discord.Bot.fetch_user
discord.Bot.get_or_fetch_user
.rtfm get_user
discord.ext.bridge.Bot.get_user
discord.ext.bridge.AutoShardedBot.get_user
discord.ext.commands.Bot.get_user
discord.ext.commands.AutoShardedBot.get_user
discord.Client.get_user
discord.sinks.Sink.get_user_audio
discord.sinks.MP3Sink.get_user_audio
discord.sinks.MP4Sink.get_user_audio
discord.sinks.M4ASink.get_user_audio
discord.sinks.MKVSink.get_user_audio
discord.sinks.MKASink.get_user_audio
discord.sinks.OGGSink.get_user_audio
discord.AutoShardedBot.get_user
discord.AutoShardedClient.get_user
discord.Bot.get_user
discord.Invite.target_user
discord.sinks.WaveSink.get_user_audio
@torpid ivy ^
so you're saying there's not
I just linked documentation to them...
yeah that was sarcasm lol. thanks!
🤥
i'm reorganizing my code in a new way, plus trying cogs. so I'm having to learn a bit about how a bunch of new stuff works
plus my old bot was written on discord.py instead of py-cord so thats fun too
yeah
i love how well slash commands just work though
they're so nice
on the old library I was just using $guess and having the bot delete messages as soon as it processed the guess
so you'd still see it for a split second. this solves that entirely :D
This'll be vague as heck, unfortunately, but one of my bots just stops responding starting today. No update in a week, zero error messages in the log, just stops responding to interactions. Is anyone aware of any issues going on that might be causing this? Is there some API change that necessitated the post in #library-updates ?
no
Not even the new username stuff?
no
Okay, thanks
Is there an on_application_command() equivalent that's guaranteed to run before the command itself runs?
I worried it might be that. Next question, then: how might I construct an ApplicationContext in there? Looking at the docs, it seems it should be ctx = ApplicationContext(bot, interaction), but ctx.command is None when I do that
interaction.type
Is there a way to return a value out of a discord.ui.View?
I want to do something along the lines of:
- A Cog defines a slash command
- When a user invokes the slash command, a View is created with a select menu to get
foofrom the user foogets passed back to the calling slash-command function, where some Cog-level functions do some post-processing onfoocombined with other information from the context- The output of the post-processing gets sent as a response to the user
But the issue I'm having is that the examples in the Guide don't go beyond using foo right in the callback function of the select menu where it was asked for. I could theoretically return foo, but I don't know where or how that return would get passed up the call stack, or how I would catch it.
The issue I'm having, basically, is that I need to either inject the context and some other dependencies into the View (yucky) or else get foo back out of the View somehow (I don't know how).
add an attribute?
Like... I can do that, but then I have to do all the post-processing from within the View, don't I?
That'd mean that instead of being able to call post-processing functions that live at the Cog level (and get called in other places), I'd have to duplicate those functions into the View, it sounds like.
no?
I feel like I'm missing something dumb
In this example (from https://guide.pycord.dev/interactions/ui-components/modal-dialogs):
class MyModal(discord.ui.Modal):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.add_item(discord.ui.InputText(label="Short Input"))
self.add_item(discord.ui.InputText(label="Long Input", style=discord.InputTextStyle.long))
async def callback(self, interaction: discord.Interaction):
embed = discord.Embed(title="Modal Results")
embed.add_field(name="Short Input", value=self.children[0].value)
embed.add_field(name="Long Input", value=self.children[1].value)
await interaction.response.send_message(embeds=[embed])
@bot.slash_command()
async def modal_slash(ctx: discord.ApplicationContext):
"""Shows an example of a modal dialog being invoked from a slash command."""
modal = MyModal(title="Modal via Slash Command")
await ctx.send_modal(modal)
If I wanted to call another function from modal_slash, based on the input captured in the modal, do I just wait until after await ctx.send_modal(modal) has completed, and then look at the attributes of modal, which will have been updated?
yeah
Okay, that makes sense; I was kind of locked into expecting some kind of return-based flow. Cheers
yay
i cant seem to make choices work here
@permissions.command(name="list", description="Lists all users in a permission group")
async def list(self,
ctx: discord.ApplicationContext,
permission_group: discord.Option(str, choices=['owners', 'managers', 'members'])
):
any ideas why?
Can you show the pip list?
Also is it still like that after a dc refresh?
ah wait nevermind i solved it
i just, forgot to include myself in the permission list
😭 sorry!
i have no idea why it would work like that though?
wait no that wasnt it
its there an internal cooldown for choices to update?
that is pretty weird, thank you!
I want to let my bot to print out the tag of the channel (something like this #general )
but I don't know why the code is nothing print out
What is get_channel.id() supposed to be?
And you need the channel.mention attribute
Read the docs
to get the channel id becasue I try to just put id(0123456789) and its error
it just print those num for me
It's get_channel()
get_channel is the method
Do you know how oop works?
.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
how do i turn an integer into an actual username? (given the integer is an actual userid with a real user behind it)
.rtfm bot.get_user
.rtfm bot.fetch_user
thank you!
hi all, have any ideas for implementing a shopping cart using Discord?
what?
what am i doing wrong here?
test = self.bot.get_user(get_members('owners')[0])
print(get_members('owners')[0])
print(test)
do you have members intent?
ah ill go check
A shopping cart. Duh. 🛒
this fixed it, thank you!
select some goods use clock button, and update embed for selected goods list, then click the "Checkout" button will open a new channel for manual settlement. is this a good way?
Are there any other better ideas?
I mean you just gotta work with Buttons and selects and some methods
Not impossible
whatd i do wrong 💀
you can use
members.append(self.bot.get_user(member).mention)
``` instead
I also suggesting using *members when sending the message instead of just members
was there any reason why it was normal here? (printed out imsisig#0 in console instead)
__repr__ and __str__ are different
python uses __repr__ for print
and __str__ for ... string stuff
Is there a way to create a link in discord that calls another slash command ?
</command name:command_id>
</roblox play:1131169592761385001>
Or do slash_command.mention
Pretty sure it was slash cmd id and not application id
yup
How to request to speak in a stage channel, i checked docs, it said to use this method:
stage_channel = await channel.connect(timeout=10)
await request_to_speak()
Error while joining stage channel: name 'request_to_speak' is not defined
is there a way to make a basic help command that lists all commands under cogs with their description?
@commands.slash_command(
name="help", description="Display a help command with help on the bot"
)
async def help(self, ctx):
embed = discord.Embed(title="Help", color=0x86DB98)
commandnum = 1
for command in self.bot.commands:
embed.add_field(
name=f"__**{commandnum}**__ - </{command.name}:0>",
value=f"Info: `{command.description}`",
inline=True,
)
commandnum += 1
embed.set_footer(text=defaultfooter)
button = discord.ui.Button(label="Support Server", url=supportserver)
view = discord.ui.View()
view.add_item(button)
await ctx.respond(content=f"made by whatisyourname.", embed=embed, view=view)
thank you!
Any helpers?
You need to do await stage_channel.request_to_speak()
I tried that
Also didn’t work
What error do you get?
Let me send error
“await stage_channel.request_to_speak()” says voice voiceclient object has not attribute request to speak
It’s in docs
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 ...
Saw that now, my mistake
All good
Do channel.request_to_speak instead
Already tried that
I’ll try again but I already tried
Can you show all the relevant code?
Ok
Channel also has same error but instead it’s “stagechannel” object
async def join_voice_channel(channel):
try:
channel = Bot.get_channel(channel)
stage_channel = await channel.connect(timeout=10)
await channel.request_to_speak()
Bot.loop.create_task(play_music_loop(stage_channel))
except asyncio.TimeoutError:
print(f"Timeout occurred while trying to join stage channel {channel.id}.")
except Exception as e:
print(f"Error while joining stage channel: {e}")
I fixed it
The docs clearly say discord.Member.request_to_speak
It's a method of the member object
That's why you read the docs carefully
how to make the button disabled after pressing it
Learn all about implementing buttons in your Discord Bot using Pycord.
@client.command()
async def test(ctx):
image = Image.open("image.png")
await ctx.send(file=image)```
I started looking into the Pillow library and ran into a primitive problem: I don't understand how to display an image in a message.
haven't worked with pillow, but what does Image.open return
It opens a file on my laptop
But it's not in the message
is image.png a local file?
It is in the same folder as the code. This is a local file
Why do you need pillow to send a local image
I want to understand how to send files first to work with their change
to send a file, you need to open a file in binary-read mode and pass it to create a discord.File object
I will try. Thanks
hey! Quick question, does anyone know how to set the author property on a paginator embed? Thanks!
.rtfm embed.set_author
no, because that's a funcion
I need it in my
Page(
embeds=[
discord.Embed(
description=f"> Nom de la carte: **{card.name}**\n> Rareté la carte: **{card.rarity}**\n> Valeur: **{card.price} €**\n> Carte en circulation: **12**",
colour=user.accent_color,
timestamp=datetime.now(),
)
]
)
Page(
embeds=[
discord.Embed(
description=f"> Nom de la carte: **{card.name}**\n> Rareté la carte: **{card.rarity}**\n> Valeur: **{card.price}€**\n> Carte en circulation: **12**",
colour=user.accent_color,
timestamp=datetime.now(),
- )
+ ).set_author(name = "nerd")
]
)
