#Basic Pycord Help (Quick Questions Only)
1 messages · Page 77 of 1
probably 
do you know if there is a doccumentation for type in @option?
can you make your description into a kwarg
i.e. description=...
@commands.slash_command(name="mute", description="Permet de mute un utilisateur")
@option("user", "L'utilisateur que l'on souhaite mute", required=True, type=discord.Member)
@option("reason", "La raison du mute", required=False, type=str)
async def mute(self, ctx, user, reason='L\'admin n\'a pas donné de raison'):
the description after @commands.slash_command?
no, the 2nd arg of your option decorator
that description
you can leave the type part in
im just asking you to add description= to the 2nd args
I dont get it but it works, ty so much
sorry if im a little bit slow, im into medication + im not english
all good, i'll explain; the @option decorator defines the first positional argument as name, and the 2nd positional argument as optional type py def option(name, type=None, **kwargs):
because you didn't use it as a kwarg, it assumed the description you set was the type
OH I GET IT, so it was thinking that the type was my description?
mhm
Does the execution speed decrease if the variable assignment is done in one line?
Before:
variable1 = ...
variable2 = ...
... = ...
After:
variable1, variable2, ... = ..., ..., ...```
so then when you tried to do type=.. later, it broke because you passed type twice
negligible
allgood
the thing is that this is the opposite of Option
because the first arg in Option is input_type and the 2nd arg is optional description
but it's too significant to change at this point
ok last question for tonight buddy:
@bot.event
async def on_member_remove(member):
rank.remove_user(member.id)
le_serv = bot.get_guild(923316085950918656)
mention=member.mention
guild=member.guild
user_num = len(le_serv.members)-4
embed=discord.Embed(title=str("*** Quelqu'un s'en va! ***"),colour=0x6BFF33,description=str(f"Malheureusement, {mention} a quitté le {guild}, à bientôt!").format(mention=mention, guild=guild))
if member.avatar != None:
embed.set_thumbnail(url=f"{member.avatar}")
embed.set_author(name=f"{member.name}",icon_url=f"{member.avatar}")
else:
icon = 'https://imgs.search.brave.com/8q2vzpdFmkVX8pvFePnT9a0xfU-i8HKXE7ozolyxSLs/rs:fit:1024:1024:1/g:ce/aHR0cHM6Ly9pLmlt/Z3VyLmNvbS9QUTdE/OUt2LnBuZw'
embed.set_thumbnail(url=f"{icon}")
embed.set_author(name=f"{member.name}",icon_url=f"{icon}")
embed.set_footer(text=f"{member.guild}",icon_url=f"{member.guild.icon}")
embed.add_field(name="Nom d'utilisateur:", value=member.display_name)
embed.add_field(name="Nom du serveur:",value=guild)
embed.add_field(name="Membre numéro:", value=user_num)
await guild.system_channel.send(embed=embed)
sometimes, when someone leave, this function just don't activate, like it work... sometimes.
Am I making smth wring?
maybe I should use on_raw_member_remove instead of on_member_remove?
on_member_remove should be fine
what are your intents?
intents = discord.Intents.all()
intents.emojis = True
intents.guilds = True
intents.messages = True
intents.message_content = True
intents.members = True
well sometimes the member is not available in cache
yes you could use that, but you wont get the member object then
it ask a payload, what is it pls?
that last line
that class will be returned
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 ...
it dont feel safe to use
lol why not
idk, when I click on the doc, it put warning
the non-raw version just does bot.get_guild(payload.guild_id).get_member(user.id) thats all
and my poor english makes me scared of coding smth that I dont understand
that is for creating them yourself, which you arent, the library is creating it for you
Its weird because for me the normal on_member_remove works fine
sometimes it does for me too, but sometimes, nothing
yea but sometimes it wont. thats because of how the cache works
oof
anyway
thanks for your help @proud mason@young bone@cyan quail, it help me a lot!
💙 💙 💙 💙
yup typing made it work, almost looks the same but typing does make it look better, and still lets the user know the bot is working :)
How can I get a list of the IDs of the roles the author has?
You need to access the roles attribute of the Member object and use a list to extract the IDs
how can I do that?
I suppose you do that a bit like this;
role_ids = [role.id for role in member.roles]
yes
(if you're using that in a command ofc, you can also use ctx.author.roles)
ctx.author.roles?
yes
yeah was about to say lol
^^
its kinda the same for interaction
ig just first thing that came up into my mind
Does on_application_command gets executed before the command or at the same time as the command?
If it is at the same time, is there a way to make the on_application_command run first?
what?
eg.: Someone sends a command to the bot, and I want the on_application_command to be executed before the command that the user called. Main purpose of that is to update the user data before he runs the command in question.
I will try something called @before_invoke
That is after
But yeah before_invoke is what you want
I am trying to setup a virtual environment with pycord and I installed the base dependency, but it says there is no module called discord, what do I do?
Can you show the pip list?
I'm using a venv so it's really just py-cord
and all the dependencies
huh wait
using the venv instead of just a requirements folder changes stuff
can i have discord link where i can have basic templet of runing the bot
class MyView(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.select(
placeholder="Выбирете роль",
min_values=1,
max_values=1,
custom_id="role",
options=generate_menu()
)
async def select_callback(self, select, inter: discord.Interaction):
print(select.values)
role = inter.user.roles
for i in role:
print(role)
print(i.id)
if i.id == int(select.values[0]):
await inter.user.remove_roles(get(inter.guild.roles, id=int(select.values[0])))
await inter.response.send_message(f"Вы выбрали роль <@&{select.values[0]}>. Успешно забрана!")
else:
await inter.user.add_roles(get(inter.guild.roles, id=int(select.values[0])))
await inter.response.send_message(f"Вы выбрали роль <@&{select.values[0]}>. Успешно выдана!")```
Error:
discord.errors.InteractionResponded: This interaction has already been responded to before
I can't seem to get the bot to play a simple local audio file... And I'm having trouble debugging it because it successfully connects and then just freezes and reports "The application did not respond". No errors in the console. I added some print statements, and it never gets to the second one:
# Join the user's voice channel
print("I get here!")
voice_channel = ctx.author.voice.channel
voice_client = await voice_channel.connect()
# Load the local audio file
print("I don't get here?")
audio_source = discord.FFmpegPCMAudio(AUDIO_DIR + file)```
If I run the command again it throws: ClientException: Already connected to a voice channel.
Update to 2.4.1
Omg... Tysvm... I had py-cord >= 2.3.2 in my requirements.txt file thinking it would "install any version above that value" 
why are you sending a message for every role in user.roles?
that code logic is very scuffed
i suggest you do smth like this instead of the loop-
role = member.guild.get_role(int(select.values[0]))
if role in member.roles:
# remove it
else:
# add it
this will be much faster and much more efficient
and this will actually work
button parameter goes before the interaction parameter
self, button, interaction
like that
class BaseView(View):
def __init__(self, interaction: discord.Interaction, game: BaseGame) -> None:
super().__init__(timeout=15.0, disable_on_timeout=True
self.interaction = interaction
self.game = game
async def on_timeout(self) -> None:
await self.interaction.edit_original_response(content="Game stopped due to timeout")
self.stopGame()
def stopGame(self) -> None:
self.disable_all_items()
self.stop()
self.game.stopGame(self.ogPlayer.id)```
Any idea why the on_timeout doesn't disable the items but when my button does view.stopGame() it disable the items ?
Maybe there's something i didn't understood about the on_timeout 🤔
call stop game before editing, and pass view=self to the edit
disable_on_timeout=True is ignored if you override the on_timeout method
Yeah, i know for this one it's just here by default x)
And yeah thanks, forgot the view=self
lol np
Can I use the on_member_update function to access whether or not a new user has accepted Discord's "Accept Rules" themselves and then assign them a role accordingly? 🙂
.tias
The docs pretty much answer your question.
When accepting rules the pending changes or am I reading this wrong from the docs?
Yes, get triggered when it changes
Okay then it should work like this or ?
@commands.Cog.listener()
async def on_member_update(self, before, after):
if before.pending and not after.pending:
for role in ROLES:
await after.add_roles(role)
add_roles can take a list of roles afaik
Okay then can I just pass the list like that?
@commands.Cog.listener()
async def on_member_update(self, before, after):
if before.pending and not after.pending:
await after.add_roles(ROLES)```
Yes
Can I send ephemeral messages in an on_message event?
no. ephemeral can only be sent to interactions
how can i get number of bans in server?
never mind i got it
Audit logs?
i just check the docs xd
How to create such a message?
ephemeral select menu
Learn all about implementing Select Menus or Dropdowns in your Discord Bot with Pycord.
(the that only you can see it is called an ephemeral)
Thanks
hi, sorry to disturb, but I want to know smth:
with / commands and @options, how can I do that my user can mention many users in once.
actually, I have this:
@commands.command()
async def invite(self, ctx, *args):
"""
Permet d'inviter un/plusieurs utilisateur(s) dans son salon vocal privé
discord.Member : *args -> les/la mention(s) faite(s) par l'utilisateur de la commande (l'auteur)
"""
is_there = False
members = (
ctx.message.mentions
) # je récupère la liste des mentions (sous forme de discord.Member)
and I want to transform it into a slash command:
@commands.slash_command(name="invite", description="Invite un ou des utilisateurs dans ton salon privé!")
@option(name="user", description="Les utilisateurs à inviter", type={?????}, required=True)
async def invite(self, ctx, *args):
"""
Permet d'inviter un/plusieurs utilisateur(s) dans son salon vocal privé
discord.Member : *args -> les/la mention(s) faite(s) par l'utilisateur de la commande (l'auteur)
"""
is_there = False
members = (
ctx.message.mentions
)
thanks
discord.errors.InteractionResponded: This interaction has already been responded to before
(self, ctx, user: discord.Member)
but I want it to be one or more
right... you can only have 1 response to that, if you could provide your entire command it might be easier to tell you what you're doing wrong :P
@opaque needle if you want to send multiple messages, use interaction.followup.send()
Heya, i have question, how i can integrate button in prefix command😅
view=thebutton, with a class it would be view=thebutton()
thanks, it remains to create a function for this and call the button
This suggests that you should not write in every output ctx.respond u need one respond and next send
Ty, I'll look into this later
async def select_callback(self, select, inter: discord.Interaction):
role = inter.user.guild.get_role(int(select.values[0]))
if role in inter.user.roles:
await inter.user.remove_roles(get(inter.guild.roles, id=int(select.values[0])))
resp = "Роль убрана!"
await inter.response.defer()
else:
await inter.user.add_roles(get(inter.guild.roles, id=int(select.values[0])))
resp = "Роль добавлена!"
await inter.response.defer()
await inter.response.send_message(resp, ephemeral=True)```
?
do you have multiple instances running?
also, defer at the start of the callback, instead of doing it inside the if blocks
and just pass role to add/remove_roles ??
async def select_callback(self, select, inter: discord.Interaction):
role = inter.user.guild.get_role(int(select.values[0]))
if role in inter.user.roles:
await inter.user.remove_roles(get(inter.guild.roles, id=int(select.values[0])))
resp = "Роль убрана!"
await inter.response.defer() #1 pespond
else:
await inter.user.add_roles(get(inter.guild.roles, id=int(select.values[0])))
resp = "Роль добавлена!"
await inter.response.defer() #1 respond
await inter.response.send_message(resp, ephemeral=True)# 2 respond```
Umm i see 2 cases respond
they are inside if else blocks
oh right
im sorry
yes 2nd should be interaction.followup.send
therefore only 1 conflict and not 2
||i thought you were talking about the 2 defers
||
I myself once wrote a bunch respond on the authomatical
and then I thought it was wrong
if == ...
await ctx.respond("first")
else:
await ctx.respond("second")
await ctx.send("dont use respond here")```
Thanks!
Не за что
Why are all members always shown as offline although some are online?
intents.members = True
intents.guilds = True
guild = ctx.guild
for member in guild.members:
print(member.status)```
Because that is their status?
Is there an autocomplete example for mentionables? I thought it was in Guide or examples folder, but failing to find it
https://github.com/Pycord-Development/pycord/blob/master/examples/app_commands/slash_autocomplete.py
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/slash_autocomplete.py at master · Pycord-Development/pycord
How can I then get the online status out ?
I was just on that. That does not have Mentionable autocomplete (e.g. Roles, Channels, Users)
Whoops my bad, i doubt there is an example
Actually there is. I can extrapolate from https://github.com/Pycord-Development/pycord/blob/master/examples/app_commands/info.py#L16
What do you mean by "get the online status out"
you want SlashCommandOptionType.mentionable
however, discord only defines it as users and roles
you won't get channels there
You need presence intent
ooh. Okay. How is that different from typehinting the Member or Role from the example I linked?
it's just the direct type that discord uses
when you typehint member/role, it's converted to SlashCommandOptionType internally
ahhhh. Gotcha! pycord magic 🪄
(you probably still need to use Option though)
It's not meant to be anything too robust, so this'll work. Thanks for helping.
I did not seem to need option; I essentially copied the exact signature from
https://github.com/Pycord-Development/pycord/blob/master/examples/app_commands/info.py#L15-L16 and changed Member to Role, and it works as expected.
oh i meant specifically for SlashCommandOptionType
Ah, I see
Unrelated, how can we get things like ctx.respond to have IDE autocompletion. I'm always afraid I'm going to misspell ephemeral 😛
i can't really comment because autocomplete has always worked for me by default
Not really possible iirc. ctx.respond uses *args and **kwargs
Thank you 🙂
Hello, guys!
How can i check, if a member join a voice channel or leave a voice channel in the https://docs.pycord.dev/en/stable/api/events.html#discord.on_voice_state_update event?
I would be really happy if you could help me
if before.channel is None and after.channel is not None, then member joined a channel
The opposite if member left
thx
How do I have a new line in an embed?
use \n
yea lol
not like inline=True or False?
uh pretty sure they meant in the description
inline is for fields
ye
@livid wolf you were asking for the description right? or fields?
Fields
@livid wolf
Thanks
ok im prolly dumb but
I would never say that but ok
using one of the quickstart sripts here
Installing Pycord with Replit (only use replit as a last resort) - pycord-replit-install.md
and i get
is discord.py uninstalled?
good question
also check this
just create a new project and do the stuff
yeah
its probably way easier to do it like that xd
what?
let me cook actually i think im just 0 iq
#app-commands message
this maybe?
I use a Raspberry Pi
can you show the py-cord version?
wdym
Do you know basic python?
kinda
i have an already working bot
but i was trying to go through pycord instead
whats weird is my previous one worked with bot = commands.InteractionBot() to initialize but bot = discord.Bot() doesn't
for which one
the one who is not working
numpy 1.24.3, flask 2.3.2, urllib3 2.0.2 py-cord 2.4.1, discord 2.2.3
discord is installed
yes
- Uninstall discord.py or any other forks of discord.py you might have with the namespace
discord.
python -m pip uninstall discord.py discord -y
2a. Install py-cord
python -m pip install py-cord
2b. Update py-cord
python pip install -U py-cord
Installing other builds:
Note: You need to have git installed. Use ?tag git to find out how to install git.
Updating the module to master branch (unstable):
pip install -U git+https://github.com/Pycord-Development/pycord
did you also uninstall py-cord and reinstall it?
How is it possible to dynamically create the buttons depending on how many values are present in self.specc?
for specc in self.speccs:
self.add_item(discord.ui.Button(label=specc, custom_id=specc, style=discord.ButtonStyle.green))
@discord.ui.button()
async def button_click(self, button: discord.ui.Button, interaction: discord.Interaction):
specc = button.custom_id```
do all those buttons have largely similar callback? then subclass button
The buttons all have the same callback
and instead of adding discord.ui.Button(...), add your subclass. like self.add_item(MyButton(...))
yea much better to subclass Button
Ah thank you! 🙂
ah finally i got it work tysm 
I can maximum 25 buttons correct?
yes
Is there any way i could categorize my slash commands?
How can i edit only the field of an embed without need to rewrite all the embed? if this is even possible.
yes
Maybe can you explain me how to do that?
I cannot explain it because I dont know how to do it xd
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...
but maybe this can help you
ty, i'll try
check out embed.set_field_at
.rtfm set_field
yeah, already found this. thanks anyway
Since when does ctx.author.id not work???
await ctx.respond(f":tick: <@{ctx.author.id}> has been vouched `{lines}` times", file=discord.File(f"Reputation/{member.id}.txt"))
AttributeError: 'NoneType' object has no attribute 'id'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/pacity/.local/lib/python3.9/site-packages/discord/bot.py", line 1114, in invoke_application_command
await ctx.command.invoke(ctx)
File "/home/pacity/.local/lib/python3.9/site-packages/discord/commands/core.py", line 375, in invoke
await injected(ctx)
File "/home/pacity/.local/lib/python3.9/site-packages/discord/commands/core.py", line 132, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'NoneType' object has no attribute 'id'
ping when replying
can you show the code?
you probably didn't get member properly
Hi! I have this code to check if the user is registered in the bot and I cant figure out how to stop it from executing when the user isn't registered
async def on_command(ctx):
#if user not is registered
#cancel the command```
you can do it with if else
i know but i need to cancel the command with pycord
when someone calls any command it goes first in this function
i want to cancel the command somehow
you could use check
how
@commands.check()
what does it do?
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 do i make a slash command arguement mandatory?
theyre required by default unless you provide a default argument
ah ok
what events covers when the bot is pinged?
only on_message
hi there, i'm having a little issue, this is my code:
@bridge_command(description="Get useful info about Books and eBooks")
@discord.option("book_name",description="Enter a book name (Optional tip: add authors to get better results)")
async def bookinfo(self, ctx, book_name):
The problem that is only reciving one argument, anyone knows how to get more arguments?
add another discord.option and argument to the function
@bridge_command(...)
@discord.option(option1,....)
@discord.option(option2,....)
...
async def command(self, ctx, option1, option2, ...):
you can add up to 25 options
What are the benefits of using a Sharded Bot with a bot that is in over 700 servers? Currently I am using the standard commands.Bot
none yet
there aren't
sharding only starts to make a difference closer to 1500 or so? maybe less
if you want your bot to run smoother then that's on the specs it's running on
Ah ok
the reason it exists is mainly to split events across several instances
Are variadic slash commands a thing? ie smth like python async def authorize_users(self, ctx, members: [discord.Member] = None):
Uh slash commands? Or prefix?
slash, but if its different between the two I'd be curious to know anyway
Yea you can do it in prefix commands
The library will manage everything for you
You can even accept a list of a type between other parameter
Like async def cmd(ctx, name: str, users: list[discord.Member], reason: str)
This isn't possible for Slash commands as i remember
Because the discord.Member option only let's you pick 1 member
got it, ty
you might be able to do some tricks by accepting a string and using Converters
Although im not quite familiar with how that would work
Is there a way to check if a member is timeouted?
.rtfm member.timed
Thank you i haven’t founded it in the docs
anyways I did it like this
format_exc won't work like that
Use traceback.format_exception(error)
On python <3.10, you might need to pass some extra args like error.__class__, error.__traceback__ and stuff
Search Google for examples
@discord.Cog.listener()
async def on_application_command_error(self, ctx, error):
# Get the guild and the channel where you want to log the errors
guild = self.bot.get_guild(GUILD_ID) # Replace GUILD_ID with the ID of the guild
channel = guild.get_channel(CHANNEL_ID) # Replace CHANNEL_ID with the ID of the channel
# Create an embed to log the error
em = discord.Embed(title='Error', color=em_red)
em.add_field(name='Error Type', value=type(error).__name__, inline=False)
em.add_field(name='Error Message', value=f'`{error}`', inline=False)
em.add_field(name='Exception', value=f'`{traceback.format_exc()}`', inline=False)
await channel.send(embed=em)
There is any benefit in using @option, instead of defining them in the parameters?
yeah use traceback.format_exception(error)
I'm using youtube_dl and I get this error after half playing a 3 minutes song,
if any of you had this same issue, what solution did you use to solve it? I tried different ways and it never worked. 
you know this server is for py-cord help and not youtube_dl?
How would I make the bot respond in a whisper
Ephemeral/hidden? Use ephemeral=True when responding to an interaction.
.rtfm InteractionResponse.send_message
.rtfm ApplicationContext.respond
Ahh ty
What's the canonical way to define a slash command that deliberately does not send a response message, and doesn't cause a timeout error?
or would my best bet be 'send it anyway, and delete it after/make it ephemeral' if that's not possible
There isn’t one. It is always better to acknowledge that this did happen.
It’s always better to say something like “Done!” than to say nothing at all.
Does anyone know how to use a local file for the url parameter of discord.Embed.set_image()? Or if it's possible?
My bot hit 2500 servers, so I just enabled sharding via commands.AutoShardedBot. I'm getting the following warning every minute:
WARNING:discord.gateway:WebSocket in shard ID 0 is ratelimited, waiting 60.00 seconds
The bot seems to work fine, though on_ready() hasn't fired. Is this something to worry about?
Ah! It just ticked up to shard ID 1 after 11 minutes. Progress, perhaps
?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)```
if you have members intent, it will take a while for the bot to be ready
Yeah, I'm used to that, just not to receiving this particular shard ratelimit warning
If that's all that's happening, then cool
yeah that’s just the library fetching all the members
Thank you, no idea how I didn't see this.
file = discord.File(f"attachments://assets/test.png", filename=f"test.png")
embed.set_image(url="attachments://assets/test.png")
await message.edit_original_response(content=content, embed=embed, view=SetupButtonsView(), file=file)
I apologize if I may be misunderstanding how to do this.
should just be attachments://test.png iirc
I will try that when I get home, thank you
Hey, Is there a way to wait until msg is sent in order to add emojis to it?
y'know, standard dealing with 'NoneType' object has no attribute 'add_reaction'
can you show some code?
oh, this might be what I need, lemme check it out
what event handler is for when someone replies to the bot?
still part of on_message
how would i format it
.rtfm message.reference
i don't see it
you can try getting/fetching the message reference ID and getting the author attribute of it
the MessageReference class doesn't have an author attribute
ah
you should use the id attribute and get/fetch the actual message instead
okay, that helped
but there's another issue - wait_for doesn't give the expected result
@discord.slash_command()
async def register(self, ctx: discord.ApplicationContext):
def check(reaction_: discord.Reaction, user_: discord.Member):
return user_ == ctx.author and reaction_.message == message and str(reaction_.emoji) in answer_emoji
answer_emoji = ('\U0000274E', '\U00002705') # no, yes
#some code
interaction = await self.bot.send_privacy_policy(ctx, registration=True)
message = await interaction.original_response()
await message.add_reaction(answer_emoji[1])
await message.add_reaction(answer_emoji[0])
try:
reaction, user = await self.bot.wait_for('reaction_add', timeout=60.0, check=check)
except asyncio.TimeoutError:
await ctx.respond("Registration canceled due to lack of response")
await message.delete()
return
else:
if str(reaction.emoji) == answer_emoji[0]:
await ctx.respond("Registration canceled due to rejecting privacy policy")
await message.delete()
return
# some code in case the answer_emoji[1] is selected
getting 'Message' object has no attribute 'MessageReference' @silver moat
it's message.reference
ooooh
could you perhaps, clarify on what I am supposed to look at?
even a comment like # LOOK HERE could help
Sorry, I was in the process of editing it
basically, I expect the user to click on the emoji depending if they agree with the bot's privacy policy or not
the emojis display as expected, but the bot doesn't react on that and defaults to the except clause
the #look here is this line reaction, user = await self.bot.wait_for('reaction_add', timeout=60.0, check=check)
and also what are you trying to do and what isn't working
@silver moat okay, now it's cleared up
alr i got the id of the reference message, how do I find the author of that message
get/fetch it
.rtfm get_message
.rtfm fetch_message
discord.abc.Messageable.fetch_message
discord.PartialMessageable.fetch_message
discord.TextChannel.fetch_message
discord.ext.commands.Context.fetch_message
discord.Member.fetch_message
discord.VoiceChannel.fetch_message
discord.ext.bridge.BridgeExtContext.fetch_message
discord.Thread.fetch_message
discord.Webhook.fetch_message
discord.ext.bridge.BridgeApplicationContext.fetch_message
discord.SyncWebhook.fetch_message
discord.ApplicationContext.fetch_message
discord.User.fetch_message
discord.DMChannel.fetch_message
discord.GroupChannel.fetch_message
wait
will str(reaction_.emoji) work on ('\U0000274E', '\U00002705')?
.tias
:/
I wrote my intent badly, I meant - since the whole thing doesn't work, is it possible that's the possible culprit?
but ig that answers the question as well :p
test = await message.channel.fetch_message(message.reference.id)
object has no attribute 'id'
doesn't work with message_id either
guys is anyone here familiar with the tasks.loop parameters? I have a list containing the hour and minute of the time I want the loop to run at. My code used to run in discord.py but now that I try to migrate it to pycord (for slash commands mostly) It seems to not work anymore and I either get a typeerror : can't compare offset-naive and offset-aware times
or the loop just doesnt execute and when checking for the remaining seconds it just returns None
from dateutil.tz import gettz
... @tasks.loop(count=1,time=dt.time(tzinfo=gettz("Europe/Berlin"), hour=int(timeS[0]), minute=int(timeS[1])))
async def timer():
await self.reminder()
return timer
I check with timer.seconds , after using timer.start() later in the code
okay, apparently it's reaction_.message == message that's at fault
but... it's the message that gets the reactions attached to...?
okay, I needed to compare their IDs
because discord.Message doesn't have an __eq__ method (I think)
If there isn't one, then Python will compare their memory locations, which are different.
gotcha
try just setting the time to a naive UTC time.
do you mean with tzinfo=None as the time parameter? It avoided the error but the loop didnt execute on time and i couldnt figure out how it would
UTC = universal time-coordinated or greenland mean time (GMT) or GMT+0
or in other words, subtract 2 hours from the time since berlin is GMT+2
so there isnt a way to just use GMT for that?
actually time-changing stuff exists. I'm not particularly skilled in time conversion stuff, but I think you can just use https://docs.python.org/3/library/datetime.html#datetime.datetime.utcfromtimestamp
thank you, I will take a look at it tomorrow
Is it possible to pass a slash command parameter to a before_invoke decorated function?
Please help
TypeError: Invalid permission(s): Administrator
I use @has_permissions(Administrator = True)
from discord.ext.commands
Try a in lowercase
nop
you could probably do something like accessing ctx.selected_options, but you won't get the direct variables/args from the command.
Hi, is there an equivalent of @bot.event for @commands pls?
@commands.event
AttributeError: module 'discord.ext.commands' has no attribute 'event'
Pretty sure that's just the callback lol
What are you trying to do?
on_member_join
no
@commands.event
async def on_member_join(member):
await rank.add_user(self.member.id, member.name,1,1)
add into database user when join
Oh wait are you trying to add an event listener in cogs?
Use @commands.Cog.listener()
@commands.Cog.listener()
@commands.event
async def on_member_join(member):
await rank.add_user(self.member.id, member.name,1,1)
like this?
Not the @commands.event
Just this
I am trying to make an error handler for my bot... yet I am struggling on how to do this most efficient.
Basically I have the default
on application command error stuff
with if isinstance ...
But now I am trying to make some custom embed errors which I can just call... because as of right now I have a cog with a lot of try and except statements some with literally the same embed made on multiple places and its taking up unnecessary space...
I was trying to do this in my error_handler.py cog but I am not sure how to do this, if I should somehow make custom errors which get put into isinstance or just custom classes which get called on the except statement in the (extra large cog, because of the amount of embeds).... any ideas?
Indeed, the standard method would be to subclass another error class and check with isinstance
You can also have error handlers for each specific cog
Perhaps check out https://github.com/Pycord-Development/pycord/blob/master/discord/errors.py to see what custom errors would look like
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/errors.py at master · Pycord-Development/pycord
What do I need to make bots on my PC?
Your PC
Xd
Everything else is online, i.e Discord Account, Code editor, Python installed
Do you know basic Python?
Yes
so basically I could just import Forbidden from discord.errors and customly change the errors myself by subclassing them?
Mhm
mh that just enlightened my thoughts, thank you very much :)
Well, probably not forbidden
that was an example eheh-
? such as?
Well if you look In the file
HTTPException requires a request response from discord
You want to use an error that can be initialised freely
hi 
does someone have an idea of why this thing doesn't get execute:
class CommandErrorHandler(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_command_error(self, ctx, error):
traceback_str = ''.join(traceback.format_exception(type(error), error, error.__traceback__))
print(traceback_str)
print(error)
if "You do not own this bot." in traceback_str:
await ctx.reply("T'as pas le droit de faire ça :).")
console = await self.bot.fetch_channel(1070805582447136819)
if "is not found" not in traceback_str:
await console.send(f'L\'utilisateur <@{ctx.author.id}> a effectué la commande `{ctx.message.content}` dans le channel <#{ctx.channel.id}> à {datetime.now().strftime("%H:%M:%S")} le {datetime.now().strftime("%d/%m/%Y")}.')
await console.send(f"Erreur:")
await console.send(f"py\n{error}\n`")
await console.send(f"Traceback:")
await console.send(f"py\n{traceback_str}\n\n\n\n")
Like it's not getting call when there is an error
mh ok
Slash error?
Or regular command
you know that you have a big brain?
Apparently
on_application_command_error
ty, imma try
oh well that makes my life easier
but is there a thing for all of the errors? like all traceback with a @commands.Cog.listener()
It has the error arg
I know, but the error arg send only if there is an error with my command
I am looking for all of the errors
it's existing?
Though idk if that actually has the error arg
sorry for my poor english ahah
seems not working
on_error needs special handling
wdym?
you dont get ctx with it
discord.on_error
discord.Bot.on_error
discord.Client.on_error
discord.ui.View.on_error
discord.ui.Modal.on_error
discord.AutoShardedBot.on_error
discord.ext.bridge.Bot.on_error
discord.ext.commands.Bot.on_error
discord.AutoShardedClient.on_error
discord.ext.pages.Paginator.on_error
discord.ext.bridge.AutoShardedBot.on_error
discord.ext.commands.AutoShardedBot.on_error
im sorry I dont get it
notice how on_command_error and other error events have a parameter called error
thats the error object
yes yes
but on_error doesnt have it
I have it
you can get the error object using https://docs.python.org/3/library/sys.html#sys.exc_info
yea but that is on_application_command_error
that is different from on_error
hm
this is an event that is called when an error is raised anywhere in the bot
unless it gets handled by try except
so a thing like this should work?
still have error on my console, I think that I dont get it, im sorry
you will need to override the built in one
i dont think you can register that event as a listener 
needs to be @bot.event or override by subclass
Out of curiosity, what other errors are you trying to catch?
probably event listeners?
the idea is to get all of them
i believe exc_info() returns a tuple
yep (type(e), e, e.__traceback__)
e is the error object
thats what I was doing before!!
traceback_str = ''.join(traceback.format_exception(type(error), error, error.__traceback__))
oh yea so you can directly unpack the tuple into it
error_tup = sys.exc_info()
and then format_exception(*error_tup)
or yk what
there is a built in method for this
traceback.format_exc()
simple
this?
👌
does it print all exceptions or only pycord one
what, oh no- this was my custom error messager
oh yeah sorry im tired
lol no worries.
yes
question, did you import commands from discord.ext ?
fr? why 😦
this is what it looks like for me

why is white?????
oh idk
pip list?
Package Version
---------------------- --------------
aiohttp 3.8.4
aiosignal 1.3.1
async-class 0.5.0
async-timeout 4.0.2
asyncio 3.4.3
attrs 20.3.0
beautifulsoup4 4.12.2
blinker 1.4
certifi 2020.6.20
chardet 4.0.0
charset-normalizer 3.1.0
cloud-init 20.4.1
configobj 5.0.6
cryptography 3.3.2
dbus-python 1.2.16
distro-info 1.0
fail2ban 0.11.2
frozenlist 1.3.3
gyp 0.1
httplib2 0.18.1
idna 2.10
importlib-metadata 1.6.0
Jinja2 2.11.3
jsonpatch 1.25
jsonpointer 2.0
jsonschema 3.2.0
MarkupSafe 1.1.1
more-itertools 4.2.0
multidict 6.0.4
mysql-connector 2.2.9
mysql-connector-python 8.0.33
oauthlib 3.1.0
Pillow 9.5.0
pip 20.3.4
protobuf 3.20.3
py-cord 2.4.1
pycurl 7.43.0.6
PyGObject 3.38.0
pyinotify 0.9.6
PyJWT 1.7.1
pyrsistent 0.15.5
PySimpleSOAP 1.16.2
python-apt 2.2.1
python-debian 0.1.39
python-debianbts 3.1.0
PyYAML 5.3.1
reportbug 7.10.3+deb11u1
requests 2.25.1
setuptools 52.0.0
six 1.16.0
soupsieve 2.4.1
systemd-python 234
tk 0.1.0
turtle 0.0.1
typing-extensions 4.5.0
unattended-upgrades 0.1
Unidecode 1.3.6
urllib3 1.26.5
watchdog 3.0.0
wheel 0.34.2
yarl 1.9.2
zipp 1.0.0
it looks fine.... I have honestly no idea why your vscode color scheme is so weird but hm

but your bot in general does work right? so it does go on, even while its white (when running it via vscode)
because if it doesnt then uh vscode might be a problem...
oh yea yea, everything good
only color
oh well then idk
cursed
probably
Welp idk whats wrong your code seems fine to me tbh
did you move the handler to the main file? you need to use @bot.event
no, I will
gpt tell me this:
import traceback
from datetime import datetime
from discord.ext import commands
class CommandErrorHandler(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_application_command_error(self, ctx, error):
await self.send_error_message(ctx, error)
@commands.Cog.listener()
async def on_command_error(self, ctx, error):
await self.send_error_message(ctx, error)
@commands.Cog.listener()
async def on_error(self, event, *args, **kwargs):
console = await self.bot.fetch_channel(1107314055322030120)
await console.send(f'Une erreur est survenue lors de l\'événement {event} à {datetime.now().strftime("%H:%M:%S")} le {datetime.now().strftime("%d/%m/%Y")}.')
traceback_str = traceback.format_exc()
await console.send(f"Traceback:")
await console.send(f"`py\n{traceback_str}\n`\n\n\n")
async def send_error_message(self, ctx, error):
traceback_str = ''.join(traceback.format_exception(type(error), error, error.__traceback__))
if "You do not own this bot." in traceback_str:
await ctx.respond("T'as pas le droit de faire ça :).")
console = await self.bot.fetch_channel(1107314055322030120)
await console.send(f'L\'utilisateur <@{ctx.author.id}> a effectué la commande `{ctx.message.content}` dans le channel <#{ctx.channel.id}> à {datetime.now().strftime("%H:%M:%S")} le {datetime.now().strftime("%d/%m/%Y")}.')
await console.send(f"Erreur:")
await console.send(f"`py\n{error}\n`")
await console.send(f"Traceback:")
await console.send(f"`py\n{traceback_str}\n`\n\n\n")
what do u think abt it
ngl dont use gpt
I know, but when Im hard stuck, i try sometimes
what is the ctx.message.content equivalent for the / commands pls?
Quick question, what faulty code can I use to recreate a quick HTTP error .-.
from flask import Flask, abort
app = Flask(__name__)
@app.route('/')
def hello_world():
abort(678)
if __name__ == '__main__':
app.run()
pycord http error lol
- as i said,
on_errorcant be in a cog. the others can be
2), no need to fetch channel on every error. best to use apartial_channel(bot.get_partial_messageablecan be used as a channel) ctx.responddoesnt exist for prefix cmds- you could just use double decorators to use single handle for both, app and prefix cmd
- 5 send messages. wtf
- checking error based on string in traceback

there isnt
@bot.command()
async def faulty_command(ctx):
try:
# Trying to fetch a non-existent channel.
channel = await bot.fetch_channel(123456789012345678)
except discord.HTTPException as e:
# Handle HTTPException
await ctx.send(f"An HTTPException has occurred: {e}")
thanks
use if else with isinstance for these minor differences
@bot.event
async def on_error(event, *args, **kwargs):
console = await bot.fetch_channel(1107314055322030120)
await console.send(f'Une erreur est survenue lors de l\'événement {event} à {datetime.now().strftime("%H:%M:%S")} le {datetime.now().strftime("%d/%m/%Y")}.')
traceback_str = traceback.format_exc()
await console.send(f"Traceback:")
await console.send(f"`py\n{traceback_str}\n`\n\n\n")
am I good there?
what is partial_channel?
yeye, I removed it for the message
ah ok
partial channel allows you to send message to a channel without needing to get or fetch it
then how does I specify the one I want?
simple use-
channel = bot.get_partial_messageable(id)
await channel.send(...)
id
sending message only needs the channel id
then thats the same than my fetch, isn't? it's using id
yes but fetch message makes an api call to discord
which is slow
oh k
you get all the stuff from the channel like perms etc
which isnt needed for sending messages
ok, so my last problem (I hope) is this:
ctx.message.content
error:
AttributeError: 'NoneType' object has no attribute 'content'
maybe I should use ctx.command.name?
fck that's feels good
thanks yall
💙
awesome
btw i would put both the messages in the same message
all of em?
I can do a list and send with for el in list
difference of just 3 lines 
as you want 
😂
@bot.event
async def on_error(event, *args, **kwargs):
traceback_str = traceback.format_exc()
await console.send(f'Une erreur est survenue lors de l\'événement {event} à {datetime.now().strftime("%H:%M:%S")} le {datetime.now().strftime("%d/%m/%Y")}.')
await console.send(f"Traceback:\n`py\n{traceback_str}\n`\n\n\n")
async def send_error_message(ctx, error, command_content):
traceback_str = ''.join(traceback.format_exception(type(error), error, error.__traceback__))
if "You do not own this bot." in traceback_str:
await ctx.respond("T'as pas le droit de faire ça :).")
await console.send(f'L\'utilisateur <@{ctx.author.id}> a effectué la commande `{command_content}` dans le channel <#{ctx.channel.id}> à {datetime.now().strftime("%H:%M:%S")} le {datetime.now().strftime("%d/%m/%Y")}.')
await console.send(f"Erreur:\n`py\n{error}\n`\nTraceback:\n`py\n{traceback_str}\n`\n")
good now?
only 2 message
🙂
ty

better 
btw this
also point 3
why not 
I dont want to have commands with prefix
I want all of em /
thats why idc
lol
the library could change the string
true
how can i specify a user with the purge command?
Use checks
In the purge method
.rtfm purge
ive tried somehting like that
await channel.purge(limit=numbers, check=message.author==user)
where numbers is the limit, and user is the message author (deleting messages by the person who called the command)
but I get AttributeError: 'Message' object has no attribute 'purge'
You would need a lambda
The check is a function
So smth like lambda m: m.author==user
ahh
Also, how did you define channel
yeah this was the problem
my brain died and i had channel = message
fixed to channel = message.channel
thank u :)
Lol
I mean, in form of software
can someone explain why?
Can you show the pip list?
sure
aiofiles 23.1.0
aiohttp 3.8.4
aiomysql 0.1.1
aiosignal 1.3.1
ajsonrpc 1.2.0
anyio 3.6.2
async-generator 1.10
async-timeout 4.0.2
attrs 23.1.0
beautifulsoup4 4.12.2
blinker 1.6.2
bottle 0.12.25
certifi 2023.5.7
cffi 1.15.1
charset-normalizer 3.1.0
click 8.1.3
clipboard 0.0.4
colorama 0.4.6
discord-protos 0.0.2
emoji 2.2.0
exceptiongroup 1.1.1
Flask 2.3.2
frozenlist 1.3.3
googlesearch-python 1.2.3
h11 0.14.0
idna 3.4
itsdangerous 2.1.2
Jinja2 3.1.2
MarkupSafe 2.1.2
marshmallow 3.19.0
multidict 6.0.4
outcome 1.2.0
packaging 23.1
pip 23.1.2
poe-api 0.3.1
protobuf 4.23.0
py-cord 2.4.1
pycparser 2.21
pyelftools 0.29
PyMySQL 1.0.3
pyperclip 1.8.2
pyserial 3.5
PySocks 1.7.1
python-dotenv 1.0.0
python-socks 2.3.0
requests 2.30.0
selenium 4.9.1
semantic-version 2.10.0
sniffio 1.3.0
sortedcontainers 2.4.0
soupsieve 2.4.1
starlette 0.26.1
tabulate 0.9.0
trio 0.22.0
trio-websocket 0.10.2
urllib3 1.26.15
uvicorn 0.22.0
websocket-client 1.5.1
Werkzeug 2.3.4
wsproto 1.2.0
yarl 1.9.2
youtube-dl 2021.12.17
uninstall this and py-cord and reinstall only py-cord
got it
yeah it should work now
tho where is discord.ApplicationContext?
is it moved?
what?
like discord slash command context
no
yes
?
I just restart my pc
why?
idk intelisense not doing his jobn
But you know basic python? 
you should restart your ide when you install/uninstall libraries
Does the default built in help command work for slash commands or do I need to do that myself? I've seen it mentioned on the Pycord guide but i don't know if it works for slash commands also.
we, like other discord libraries, have not decided to make a help command for slash commands because typing / already lists them
Alright then, fair enough.
is it possible to have a requirement for a file with a slash command?
what?
yes, see
ive been looking on the docs but cant find anything about it
unless im just blind lol
file: discord.Attachment
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/slash_options.py at master · Pycord-Development/pycord
oh, that works with slash command?
.tias
oh, thank you
not particulary the first thing you think of when people only use discord.File
ye
for some reason, this doesnt work, it doesnt show the attachment as an option
i tried includign the option when defining the function too
show code?
@slash_command(name="vdf")
async def vdf(ctx: discord.ApplicationContext, attachment: option("VDF file", discord.Attachment, description="Your VDF file", required=True)):
if attachment:
file = attachment
if file.filename != "config.vdf":
return await ctx.respond("file is not a config.vdf")
else:
file = file.save()
file = file.readlines()
print(file)
its inside a cog if that mattters
i always remememberd option ot have a capital O?
but in that example it doesnt
you should be using the capitalized version there
ah okay thansk
it's only lowercase if you use the decorator @option
also the type should be first, then you pass name= to change the name
option names have to be lowercase without spaces
it's fine, just gotta remember the restrictions
for some reason it still doesnt show the option
did you restart?
this is my new code:
@slash_command()
async def vdf(ctx: discord.ApplicationContext, attachment: Option(discord.Attachment, name="vdffile", description="Your VDF file", required=True)):
if attachment:
file = attachment
if file.filename != "config.vdf":
return await ctx.respond("file is not a config.vdf")
else:
file = file.save()
file = file.readlines()
print(file)
ive always named it inside the function like that
is this inside a cog?
how i sent it
try commenting out the command, run the bot, un-comment out the command, and re-run the bot. finally, restart your discord app
first arg needs to be self
oh yeah
that too
its 10pm i havent ate maybe i should eat and get some sleep 😅
yup its wokring with the first arg as self
i completely forget about that
thank you
allgood
I have a command that will send an embed with two buttons to a channel. When I select one of these buttons I want it to DM the original command user. How can I do this?
class requestAccept(discord.ui.View):
async def on_timeout(self):
for child in self.children:
child.disabled = True
await self.message.edit(view=None)
@discord.ui.button(emoji="✅", label="Accept", style=discord.ButtonStyle.grey)
async def first_button_callback(self, button, interaction):
user = await discord.Bot.fetch_user(None)
user.send("Accepted")
await interaction.message.edit(view=None)
self.stop()
@discord.ui.button(emoji="⛔", label="Deny", style=discord.ButtonStyle.grey)
async def second_button_callback(self, button, interaction):
await interaction.message.edit(view=None)
self.stop()
Override the init and accept the author
Store it on a self variable
Don't forget to call super init
Then in the callback just do await self.author.send(...)
Oh and pass ctx.author when creating the view
Worked, thank you!
Hiii my friends 🙂
@commands.slash_command(
name="xp", description="Commande qui affiche l'xp d'un utilisateur"
)
@option(
name="user",
description="L'utilisateur dont vous voulez voir l'xp",
required=False,
type=discord.User,
)
async def xp(self, ctx, user=None):
initial_response = await ctx.respond("Création de la banniere en cours...")
#my code
await initial_response.edit(content=" ", file=discord.File("/srv/barman/bann_xp/xp_bann.gif"))
error:
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'Interaction' object has no attribute 'edit'
how can I edit my first response please guys?
.rtfm ctx.edit_original
Target not found, try again and make sure to check your spelling.
Target not found, try again and make sure to check your spelling.
Try await ctx.edit_original_response
If not then ctx.interaction.edit_original_response
it work, ty!
How do I make embedded pages? What I mean is that the person clicks the button not reaction and it goes to the next page or back a page. I tried the guides but it didn't really help much.
i believe you are referring to paginators
yes. but is there a simpler way to do the code?
hmm it is pretty simple imo
I'll give it a shot.
How do I send the paged embeds?
paginator.send if prefix cmd
thx.
paginator.respond if interactions
hmm, weird error:
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: expected Context not <class 'discord.commands.context.ApplicationContext'>```
full error?
It's a bit big but... ```Traceback (most recent call last):
File "/home/runner/Spongebot/venv/lib/python3.10/site-packages/discord/commands/core.py", line 124, in wrapped
ret = await coro(arg)
File "/home/runner/Spongebot/venv/lib/python3.10/site-packages/discord/commands/core.py", line 980, in _invoke
await self.callback(ctx, **kwargs)
File "main.py", line 131, in testing
await paginator.send(ctx)
File "/home/runner/Spongebot/venv/lib/python3.10/site-packages/discord/ext/pages/pagination.py", line 973, in send
raise TypeError(f"expected Context not {ctx.class!r}")
TypeError: expected Context not <class 'discord.commands.context.ApplicationContext'>
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
await ctx.command.invoke(ctx)
line 375, in invoke
await injected(ctx)
line 132, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: expected Context not <class 'discord.commands.context.ApplicationContext'>```
yeah.
use this
now i got raise ApplicationCommandInvokeError(exc) from exc discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: expected Interaction or BridgeContext, not <class 'discord.commands.context.ApplicationContext'>
what is the py-cord version?
ctx.interaction
2.3.2
update to 2.4.1
done.
and pass this
great.
another error
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: 'Interaction' object is not callable```
how did you pass it 
just do await paginator.respond(ctx.interaction)
thats it
oh ok, i'll try it now. idk why i did await ctx.interaction(paginator) lol
lmao
It worked, thanks!
what about ```py
async def ctx.interaction():
pass
yay
uh wtf? 💀
Now time to make this an embed for something...
oh wait, my_pages is the embeds. but it's never used.
??
the guide you linked. idk what to do with the my_pages which contains the embed.
Um if an argument is used to mention a user, how can you fetch the id of the user?
thanks.
user.id?..
attach ctx and then ctx.edit(nick="new nick")
i have all intents btw
Is there a way to have slash command options which are required only in certain cases? I assume not right?
For example
Command: /balance
Options 1: View, Withdraw, Deposit
Option 2: Amount
/balance View
/balance Withdraw [Amount]
/balance Deposit [Amount]
Make the [Amount] required when the first option is not equal to View
hey guys how do I use ctx.defer()?
await ctx.defer()
and then await ctx.respond()?
so like:
async def cmd(ctx: discord.ApplicationContext) -> None:
await ctx.defer()
await ctx.followup.send("defer")
yes
and for how long will it wait? or like hold
It wont hold for any amount of time if you dont have any code in between the send
Defering just means it wont say Interaction Failed once there has been no response for longer than 3 seconds
Is it ok if I ask you my question from before
Course
I have await member.edit(nick=“nick”)
With member being a user object
Code returns error “‘User’ object has no attribute ‘edit’”
Ok? and whats your problem with that
The User object, has no attribute edit so you need a Member object
how did you get the member object?
You can get a member object by looping over guild.members or by using get_member
||15 mins is actually the limit btw||
Member = await client.fetch_user()
yea no
Inside parentheses is an id
use guild.get_member
Yeah i know lmao but who has the attention span of 15 min to ever see that interaction fail
yea like this
I’ll try it thank you
You can also make it an option if its a slash command
😂
eg discord.Option(discord.Member, required=True
discord.Member, not just member
I do it a lot, defer things and never actually followup to them
you could rather just send Ok! or smth lol
Ya but thats ugly
esp when using buttons and dropdowns etc
Imagine, clicking a button which takes some time to process and it says 'Okay!' every time you click it 😂
oh yea you can defer and ignore for buttons. not for slash cmds tho
Yeah no, I dont really defer ever for commands
defer and ignore is actually the best way for components
YOUR BOT IS THINKING 
Im guessing this aint possible? @proud mason
nope
you could use slash cmd groups
that would achieve a similar functionality
Its nicer to have one command with the options tho :(

Ah well, will just have to keep amount optional
discord limitation
@proud mason it still not working T-T
wasn't there a way to make it so that if the buttons expired you could make the bot reply if someone still tried to press one?
Show your code
One sec
If it expired, no, just make it not expire :p
I used typing once to illustrate that the bot was doing something... because defer would override ephemerals for the response later sent :-:
hm sucks
i mean, they won't expire as long as you tell them not to
So I could basically add a custom expiration?
yes
if you actually want them to expire then either remove the buttons or disable them and edit the message
Or use self.stop()
` Given p = user_id (tested and is an actual id)
K = string for nick
guild=message.guild
member= guild.get_member(p)
print(message.author)
print(member)
await member.edit(nick=k)
await message.reply(f"Nickname updated for {p.display_name}") ```
Mobile moment
is your user_id an int
Yeah
So I could just define my timeout to be None in the class of the ui?
Guild.get_member returns none
inside View you pass timeout=None
but this won't protect against restarts, you'd have to make it persistent
the wha-
Here's the persistent example.
And fetch_user worked and gave a user object, but it’s still reported as user object not having edit attribute
Ah
just checking, what happens when you print guild.members
[<Member id=1087100813593301053 name='asuka' discriminator='0226' bot=True nick='asuka' guild=<Guild id=1050189593628119130 name="Cat's Cafe" shard_id=0 chunked=False member_count=55>>]
Hmm
is that correct?
why did discord make buttons expire in the first place?
It’s the id for bot
All intents are enabled
in code as well?
well they kinda don't... we have a default view timeout of 3 minutes
discord's structure of interactions is pretty different to how we present it to the user
but why-
Something changed, I’m gonna experiment a bit more and get back to ya 🙏
ohok havefun
Ah
So now it’s giving missing permissions for the member.edit line
is the bot's top role above the member's top role?
Wdym
you can't edit the nickname of someone with a higher role than you
or the guild owner
rip LOL
Ok now
It’s not returning an error but their nick isn’t being updated
Prolly on my end again
Got it to work tysm
Its possible to update the choices list of a command after giving it one without need to restart? I have a command that uploads a file to a folder and i want it to show up as choice in the command but it doesn't. Any solutions?
you could use autocomplete
Here's the slash autocomplete example.
Ty, i'll try
General question, it's better like this:
def get_datanamesfile():
with open('data/data_names.json') as data_names:
json_data = json.load(data_names)
return json_data
def get_keys():
with open('data/data_names.json') as data_names:
json_data = json.load(data_names)
keys = [key for key in json_data.keys()]
return keys
def get_filepath(name):
with open('data/data_names.json') as data_names:
json_data = json.load(data_names)
filepath = json_data[name].get('filepath')
return filepath
Or like this
with open('data/data_names.json') as data_names:
json_data = json.load(data_names)
def get_datanamesfile():
return json_data
def get_keys():
keys = [key for key in json_data.keys()]
return keys
def get_filepath(name):
filepath = json_data[name].get('filepath')
return filepath
So open the file 1 time or multiple times
the latter
but you still need to save it back after
had the idea to store discord user id's as a primary key in a sqlite db, but looking at the highest value user id in my dataset and it's ~1x10^18 and max int size in sqlite is ~9x10^18, any thoughts if that's a bad idea? and if so alternative methods?
store it as a string
that's how discord does it on their API already
the only reason we use ints is because python supports large ints pretty cleanly
mmm k, just was aware of performance differences in int vs string
Quick question, I currently have a bot with a few cogs using application command, the bot loaded all other cogs fine, but on 1 specific cog, it cannot seem to register any of the command, in a debug session the command doesn't show up at all in the AllCommand list, but the cog itself show on the cog list, is there any common cause for this issue?
Current amount of cog is 7 cogs, total amount of command registered is 47 commands
.slashnoshow
Checklist for Application Commands Not Showing Up:
• Does your bot have the application.commands scope?
• Are you loading cogs before on_ready and on_connect?
• Is on_connect not overridden?
• Did you update to the newest version of py-cord (tag: install)?
• Is User Settings > Accessibility > Chat Input > Use legacy chat input turned off?
• Did you share your code and errors?
• Do you still have libraries that conflict with the discord namespace (e.g. discord.py)?
Points 2 and 3 are important
All are yes, except the share your code part, which I don't get, like share it here?
Actually the cog are loaded within on_ready
And upon further testing, when I removed all cog except for this one, then the commands show up
Could it be the command limit?
in the on_ready event?
one of my cog actually need the user id from the bot object
hmm
but the issue is resolved no
where does it need it?
the issue was discord not actually pulling the changes down, or my client not pulling
I executed a command that doesn't exist anymore, and volla, the new commands all showed up
well cmds are synced before ready. if you load your cmds after ready, then they wont be sync
if you run a cmd and pycord finds a difference in registered vs local, it willl. resync
any way to manually do a sync then?
ngl load before ready
It does, the init for a cog initiate a connection to another service, which utilize the bot id as a parameter
you could use a special method and call it on ready, which sets and uses the id
why not do that connection on ready?
You can have event listners in cogs
wait, so i can have 2 on_ready(s)?
yes
2nd one
in the main file, yes
wait, so for example, if i have 2 on_ready(), one in a cog, and one in the main file, both of them will triggers with the corresponding code?
on_message(), i mean
sorry
Usage would be-
class MyCog(...):
@commands.Cog.listener()
async def on_ready(self):
print("hi")
yes both will run
one more question, so for the on_message, if i have more than 1 of them, in which one should i put the process_message_command? Or do I not need to use that at all now? (I don't use prefix command anymore, just slash commands)
i definitely butchered the messagecommand stff, didn't i..
if you dont have any prefix cmds then you dont need it
np
what could be the cause for this?
the stack doesn't show anything about my files, just discord/client.py
?tag sslfix
If you're getting the [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1108) error on a Windows host do the following:
Download and install this certificate here: https://crt.sh/?id=2835394
--> It can be installed by double-clicking the file and installing it to Local Computer, download link location: https://beans-took-my-kids.reeee.ee/38qB2n.png
For those curious, it was caused by this:
https://support.sectigo.com/Com_KnowledgeDetailPage?Id=kA03l00000117LT
it wasn't a windows host, it's on a linux vps
also the 2nd link here is invalid
Google the error. High chance its on stackoverflow
Hello friends. Quick Q here
If a user initiates a DM with my bot and my bot responds to it - is it still at risk of triggering Discord's DM softban?
I wouldn't think so but I can try to verify
How can we verify? I wouldn't want to take up much of your time
I just posted the question in ddevs discord.
Just to be sure. The user would not be using a slashcommand it would be a message?
Correct
Would triggering a slashcommand in a DM make a difference if the response is a message?
Or if the response is asynchronous - like say, a timer - so the response wouldn't be within the context of the same Interaction
How do i prevent blocking code when i create a image with Pillow?
it takes 3sec and blocks all other tasks in the bot
Use an async library
Could you recommend one where i can join 3 images in to 1 big image?
Its not certain but the response was
probably only by mass-DMing without user action (you send the msg to the bot, that counts as user action!) will you get softban and also create msg don't initiate DM ban, only create DMs
So just to make sure I understand - as long as the user initiated the private channel creation (i.e. started the DM) - I should be safe from softban?