#Basic Pycord Help (Quick Questions Only)
1 messages ยท Page 59 of 1
@proud mason
that doesn't work either.
oh right there is no #
so try (interaction.user.name + interaction.user.discriminator).lower()...
hashtags cant be used in channel names i do believe
you can check if a response has been sent before (defer is a valid response)
aaaahhh
.rtfm interactionresponse.is_done
that would return bool based on if a response was sent earlier
i see i see, i normally defer all my commands due to them using FFMPeg and longer processes, in my error handler i also have a defer for if a check fails
and it was causing some issues
i made a check like this for the actual error response
So this is how it should work?
tickket = f'ticket-{str(interaction.user.name + interaction.user.discriminator).lower().replace(" ", "-")}'
no need to put the str ig
yes, I was just wondering about that. I'm trying!
that worked thanks 
error is intended
nice. ngl tho, your system will break if someones username has special characters that arent accepted in the channel name
wanted to do it with the ID, but the owner of the server wanted it with a name. 
safest way would be to use a db lol
also is it possible to have multiple attachements for a slash command?, for example
yep, it is. But I wanted to keep it simple. The owner did not want it via the ID 
have multiple options of discord.Attachment type?
yeah
yea why not
so i can iterate through them
would i just do smth like list[discord.Attachment] ?
oh no you cant get a list of them
fuuuck
each option can only be 1 attachment
yeah ๐คทโโ๏ธ
tbf, everthing is handled in memory so it wouldnt be so good to have a multi file option
you could make the user send the attachments in a separate message and use bot.wait_for
piping was enough work ill just leave it lol
actually, pycord supports reading audio from voice channels correct?
yep
Here's the audio recording example.
:3, time to implement audio recognition via voice lol
.rtfm start_recording
.rtfm get_user_audio
use the bot in #883236900171816970 please 
oop sorry
How would you do a AutocompleteContext for all the users in a server?
Why not just use discord.Member ?
How do you respond to avoid the respond failure error ?
.rtfm respond
discord.InteractionResponded
discord.InteractionResponded.args
discord.InteractionResponded.with_traceback
discord.ApplicationContext.respond
discord.ext.pages.Paginator.respond
discord.ext.bridge.BridgeContext.respond
discord.ext.bridge.BridgeApplicationContext.respond
discord.ext.bridge.BridgeExtContext.respond
Question
I am trying to align my buttons im using a class with 2 buttons in, but they are displaying ontop of each other, Is there anyway i can align them to be on the same row side by side without using [button1][button2] in 1 line of code? this is my code :
'''
class MyView(discord.ui.View):
@discord.ui.button(label="Right", row=0, style=discord.ButtonStyle.green, emoji='โค๏ธ')
async def first_button_callback(self, button, interaction):
await interaction.response.send_message("User was notifed")
@discord.ui.button(label="Left", row=3, style=discord.ButtonStyle.red, emoji="โ")
async def seccond_button_callback(self, button, interaction):
await interaction.response.send_message("Keep Swiping")
@bot.slash_command()
async def button(ctx):
await ctx.respond("Left Or Right?", view=MyView())
'''
Why are you setting row=0 and row=3?
I was just testing it, its meant to be row=0 and row=1
the issue still happens with that set
But why? If you want them to appear on the same row why would you set them on different rows?
omg
Im such a dumbass
Oh god i feel dumb, thank you very much for the help ๐ญ
I dont know how i have my degree
Hellooo, i have a problem. I tried to handle errors globally, however, it does not even check. (I still get the errors in the console).```py
@bot.event
async def on_application_command_error(context: discord.ApplicationContext , exception):
print('a')
embed = discord.Embed(color=colors['fail'])
embed.set_author(name='Command failed. the Tech development responsible has been notified.')
await context.respond(embed=embed)
embed2 = discord.Embed(color=colors['blurple'], description='Error caught! More information below.', fields=[discord.EmbedField(name='Error', value=str(exception)), discord.EmbedField(name='User', value=context.user.mention), discord.EmbedField(name='Command', value=context.command.n)])
await bot.get_channel(1077607429929455757).send(embed=embed2)
@bot.command()
async def raisee(ctx):
ctx.respond('this is gonna be a error as it's not awaited.')
Bot is not subclassed
Try @bot.event()
people makes errors, no one is perfect. even someone who is very good at programming can make errors sometimes
Actually nvm, that's not how you do it.
I'm assuming you are actually using application commands and not prefixed commands?
๐ญ See i thought it was based on a grid system it would be row=1 column=0, row=2 column=0 โค๏ธ back to coding i go, i hope you sort your issue :)
indeed!
appreciated!
And you do not have any error handlers specifically set on your commands?
No, i don't
I honestly don't know, that should work
If anyone knows how to solve it, please ping me.
try some different error other than not awaiting (cuz i think not awaiting is a warning rather than error)
maybe raise a fake error yourself
Like what?
Maybe a missing permissions could work
yea try that
I know discord views don't persist accross bot restarts, but can I post a single view in a channel where people can click the buttons until the next restart? I tried but after a while it stopped responding, idk if that's a setting I need to change or w/e
try raise RuntimeError("Test lol")
async def calchelper(interaction, text, newview=None):
embed=discord.Embed(title="Price calculator")
if isinstance(text, str):
embed.add_field(name="", value=text)
elif isinstance(text, list):
for field in text:
embed.add_field(name="", value=field, inline=False)
if newview is not None:
await interaction.response.send_message(embed=embed, ephemeral=True, view=newview)
else:
await interaction.response.send_message(embed=embed, ephemeral=True)
This is the methods I call to create my view
you can actually have persistent views
Here's the persistent example.
ur a total legend <3 tysm
ahhh the timeout=none, makes sense
That totally worked. Thanks you!
yea lol. not awaiting is perfectly valid in python ๐
you realise its value when you go into advanced asyncio
that doesn't have anything on what im asking
that says how to edit the help command
im asking how to make categories in the help command
like this
When setting a URL in a button it says I cant set both custom_id and url
Even though i have not set custom_id
400 Bad Request (error code: 50035): Invalid Form Body
In components.0.components.0.custom_id: A custom id and url cannot both be specified
In components.0.components.0.url: A custom id and url cannot both be specified
can you show the button?
don't have a custom id
"A custom id and url cannot both be specified"
wait yeah i see that wtf
you set the url at the view class and not the button
Tried setting it to None and it still gives the same error
ah
๐ค
Huh?
button(label="", url="")
I want to set it outside of the class since I cant pass the 'tornid' to the class can I?
Its not a fixed url
You can change all the other attributes outside the button class, why not the url
How do you add a url to a button 
Here's the link example.
^
cant use the decorator
cuz there isnt any callback
I just tried that
TypeError: button() got an unexpected keyword argument 'url'
Got that
Oh
Lowerclass button, monkey brain moment

Okay got a button added
Table with a row of words
A = 0
while(Table 1 has more rows){
Read the first row X in Table 1
i = 1, B = True
while(i <= X.LetterCount){
if(ith letter of X.Word is a vowel){
B = False
}
i = i + 1
}
if(B){
A = A + 1
}
Move X to Table 2
}
Number of words with at most one vowel
Number of words with exactly one vowel
Number of words without any vowels
Number of words with at least one vowel
?
Im guessing you cant have a button with a url do both something and link them somewhere
Like say update the message the button was on
yea cuz discord doesnt dispatch any event for url buttons
Unlike normal ones
that isnt even python
Alright, its a sacrifice then
How do I add logic to parent command? Example:
@commands.group(name="cmd")
async def cmd(self, ctx: Context, user: Member):
# logic for invocation with user
@cmd.command(name="addrole")
async def addrole(self, ctx: Context, role: Role):
# logic for subcommand
The problem I am having is that if I use <prefix>cmd addrole @some-role it executes the cmd function passing addrole to it in place of the user arguemnt instead of going through the subcommand. I tried
@commands.group(name="cmd")
async def cmd(self, ctx: Context, user: Member):
if not ctx.invoked_subcommand is None:
return
but that doesn't work :(
Cant have best of both worlds
are you asking help on your homework?
try setting invoke_without_command to True in the group decorator
Thanks, that works 
nvm
Hi im pretty much a noob, someone coud help me to make my bot be able use prefix comands
?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)
Thanks men !!
How can you access the bot instance while inside a View class for UI?

thought footers can have icon
embed.set_footer(text=f"by {ctx.author.avatar.url} {ctx.user.name}")
```\
also how do i do this
embed.set_footer(text=f"by {ctx.user.name}", icon_url=ctx.author.avatar.url)
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/context_menus.py at master ยท Pycord-Development/pycord
.rtfm interaction.client
thanks, i only just remembered i could access it through there

how do u use Bridge commands as prefix
@bot.bridge_command()
async def news(ctx, arg):
embed = discord.Embed(
title=(arg),
color=discord.Colour.blurple(), # Pycord provides a class with default colors you can choose from
)
embed.set_footer(text=f"by {ctx.user.name}", icon_url=ctx.author.avatar.url) # footers can have icons too
await ctx.respond(embed=embed) # Send the embed with some text
Maybe try
@bot.bridge_command()
async def news(ctx, arg):
embed = discord.Embed(
title=(arg),
color=discord.Color.red(), # Pycord provides a class with default colors you can choose from
)
user = ctx.user.name
embed.set_footer(text=f"by {user}", icon_url=ctx.author.avatar.url) # footers can have icons too
await ctx.respond(embed=embed) # Send the embed with some text
Don't know if that will work
Wait
misread

@astral mist Misread. No idea what a "bridge command" is
ok
This is where the ext.bridge module comes in. It allows you to use one callback to make both a Slash Command and a Prefixed Command.
how do you even define the bot?
bot = bridge.Bot(command_prefix="!", intents=intents)
which intents?
do you have both message intents?
Yes?
https://docs.pycord.dev/en/master/intents.html
https://discord.com/developers/docs/topics/gateway#gateway-intents
import discord
from discord.ext import commands
# Get specific intents for fine control
intents = discord.Intents()
intents.emojis = True
intents.guilds = True
intents.messages = True # Required for prefix commands!
...
# Get all non-priveliged intents; this excludes presences, members and message_content
intents = discord.Intents.default()
# Set priveliged intents: these must be enabled on dev portal
intents.members = True
intents.presences = True
intents.message_content = True # Required for prefix commands >= 2.0.0b5
# Get all intents; all intents must be enabled on dev portal.
intents = discord.Intents.all()
# Apply intents when creating your bot
bot = commands.bot(prefix="?", intents=intents)
In version 1.5 comes the introduction of Intents. This is a radical change in how bots are written. An intent basically allows a bot to subscribe to specific buckets of events. The events that corr...
Integrate your service with Discord โ whether it's a bot or a game or whatever your wildest imagination can come up with.
i used the ones it said
cant i just use intents = discord.Intents.all()
yes
Hi, I'm a bit confused on the difference between UserCommand, ApplicationCommand and SlashCommand?
How exactly do they differ and when should I use which one?
ApplicationCommand is an underlying class which you don't use
SlashCommand is for slash commands that are invoked with / in the chat, normally created through @slash_command decorators
UserCommand is for commands that are invoked by right clicking a user and selecting a command from a list there
there's also MessageCommand, which is the same as UserCommand but for right clicking messages
Thanks, that makes it a lot clearer!
Traceback (most recent call last):
File "main.py", line 2992, in <module>
bot.run(TOKEN)
File "/opt/venv/lib/python3.8/site-packages/discord/client.py", line 717, in run
return future.result()
File "/opt/venv/lib/python3.8/site-packages/discord/client.py", line 696, in runner
await self.start(*args, **kwargs)
File "/opt/venv/lib/python3.8/site-packages/discord/client.py", line 660, in start
await self.connect(reconnect=reconnect)
File "/opt/venv/lib/python3.8/site-packages/discord/client.py", line 554, in connect
await self.ws.poll_event()
File "/opt/venv/lib/python3.8/site-packages/discord/gateway.py", line 604, in poll_event
await self.received_message(msg.data)
File "/opt/venv/lib/python3.8/site-packages/discord/gateway.py", line 554, in received_message
func(data)
File "/opt/venv/lib/python3.8/site-packages/discord/state.py", line 1354, in parse_guild_audit_log_entry_create
payload = RawAuditLogEntryEvent(data)
File "/opt/venv/lib/python3.8/site-packages/discord/raw_models.py", line 650, in __init__
self.target_id = int(data["target_id"])
TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'
got this error 3 times today, it just happens randomly while the bot is on and i have to re-run the code to restart the bot
Try updating pycord
aight
no luck, i just got it again
im using the 2.4.1.dev9+g8a911374 version
i added reconnect=True so now it reconnected instead of crashing
the error still appeared /shrug
That is the whole error? (Sometimes the error is in 2 parts and generally the upper part is just as important.)
ah
downgrade to 2.4.0
ok ok
time to pr another fix...
That means you are taking longer than 3 seconds to respond to the interaction.
you will need to defer
.rtfm InteractionResponse.defer
interaction.channel.send should be interaction.response.send_message
but if you defer, it should be interaction.followup.send
The first line in your callback should be defer if you defer. You need to tell discord asap that you are defering.
(why don't we have interaction.respond??)
not nesscacarily.
? in that example yes
no ignore me
it's because you're doing if/else
you have to respond once
yeah pretty much
Hey im probably just being hella dumb and its probably my ass python knowledge. But how can I ctx.send this function outcome? here is my function:
def profile_Embed(message_About, message_Age):
embed=discord.Embed(title="Here is LeeT's profile", color=0xbc7ba5)
embed.set_author(name="Bailey", url="https://", icon_url="https://i.")
embed.set_thumbnail(url="https://i.imgur")
embed.set_image(url="https://medi-ng.jpg?s=612x612&w=0&k=20&c=1Ws_LSzWjYvegGxHYQkkgVytdpDcnmK0upJyGOzEPcg=")
embed.add_field(name="About Me?", value=message_About.content, inline=True)
embed.add_field(name="Age?", value=message_Age.content, inline=False)
embed.add_field(name="Where From?", value="Lorem ipsum dolor sit amet", inline=True)
embed.set_footer(text="Bi v0.01 - LeeT#4281")
#i want this to straight send it once the function is ran within the async
return (ctx.send(embed=embed))
profile_Embed(message_About, message_Age)
await it
yeah duh
The function is placed outside of the async, but im calling the function within the async
But if i place my function within the async, theres no point in having a function/subroutine
I mean to await profile_Embed
Also, the Python convention is to use snake_case for function, variable, parameter, etc. names.
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: NameError: name 'ctx' is not defined
I know im just too lazy
yeah it isn't defined.
i tried that it throws this error <discord.embeds.Embed object at 0x00000242B94908B0>
well not error
So i need to define it within the function aswell?
Yeah i did that
you can pass ctx into the function.
regardless, conventions are made to be followed.
Im still stuck with camelCase idk why i always naturally go towards that, and ill try passing the ctx in now
i mix snakecase and camel
giraffe
is that whats its called?
Haha yeah i mean all my code is self taught since my college is still stuck on shitty pandas and matplotlib
:/
anyways thank you very much with your help, sorry if im brain dead, we all start somewhere ๐ญ
Pretty much all coding is self taught, school only gets you started. If you actually want to learn programming you need to do it yourself.
Why are you deffering before sending the response
You defer at the start of your callback
It's just pointless
How to make an optional option in slash-command?
Here's the slash options example.
Oh, thx
do you have multiple instances of the bot running?
how can i get the user that boosted the server? i am using message to check if its a premium subscription type
how do I make a slash command that only the bot owner can run?
?tag intents
https://docs.pycord.dev/en/master/intents.html
https://discord.com/developers/docs/topics/gateway#gateway-intents
import discord
from discord.ext import commands
# Get specific intents for fine control
intents = discord.Intents()
intents.emojis = True
intents.guilds = True
intents.messages = True # Required for prefix commands!
...
# Get all non-priveliged intents; this excludes presences, members and message_content
intents = discord.Intents.default()
# Set priveliged intents: these must be enabled on dev portal
intents.members = True
intents.presences = True
intents.message_content = True # Required for prefix commands >= 2.0.0b5
# Get all intents; all intents must be enabled on dev portal.
intents = discord.Intents.all()
# Apply intents when creating your bot
bot = commands.bot(prefix="?", intents=intents)
In version 1.5 comes the introduction of Intents. This is a radical change in how bots are written. An intent basically allows a bot to subscribe to specific buckets of events. The events that corr...
Integrate your service with Discord โ whether it's a bot or a game or whatever your wildest imagination can come up with.
Not possible to hide the command from others, but you can block the command from running if someone else used it
.rtfm is_owner
thanks!!
np. make sure to check out the guide if you are using pycord for the first time
.guide
sure!!
how would you attach a custom value/variable to a command? like the "usage" or "description" parameter for commands
you can pass a lot of variables to the command decorator
.rtfm commands.command
discord.commands.command
discord.ext.commands.command
discord.ext.commands.Command
discord.ext.commands.Command.add_check
discord.ext.commands.Command.after_invoke
discord.ext.commands.Command.before_invoke
discord.ext.commands.Command.call_after_hooks
discord.ext.commands.Command.call_before_hooks
discord.ext.commands.Command.callback
discord.ext.commands.Command.can_run
discord.ext.commands.Command.clean_params
discord.ext.commands.Command.cog_name
discord.ext.commands.Command.cooldown
discord.ext.commands.Command.copy
discord.ext.commands.Command.dispatch_error
discord.ext.commands.Command.error
discord.ext.commands.Command.full_parent_name
discord.ext.commands.Command.get_cooldown_retry_after
discord.ext.commands.Command.has_error_handler
discord.ext.commands.Command.invoke
check the Command class to see what all it accepts
yeah I'm wondering If there's something you can do to add your own, not literally but some alternative or equivalent. or maybe that's a general python question
yeah i believe you can add your own attributes too
it shouldnt have slots defined, so you can add new attributes

For some reason, bot.close() is taking a seemingly infinite amount of time to do anything (the bot does close the WS connection, but the function never returns)
How would I go about debugging this? My version is 2.4.0 on 3.11.0
2023-02-23 10:17:49,284:DEBUG:discord.gateway: Received WSMessage(type=<WSMsgType.CLOSING: 256>, data=None, extra=None)
2023-02-23 10:17:49,284:INFO:discord.gateway: Websocket closed with 1000, cannot reconnect.
2023-02-23 10:17:49,285:DEBUG:discord.client: Dispatching event disconnect
2023-02-23 10:17:49,286:INFO:discord.client: Cleaning up tasks.
2023-02-23 10:17:49,286:INFO:discord.client: Cleaning up after 6 tasks.
This is the end of the debug log
?tag
Description: Get or create a tag
Cooldown: 5 seconds
Usage:
?tag [tag name]
Example:
?tag how2invite
?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)
#883236900171816970 please 
srry
do you override bot.close?
ive spend like 1,5 h trying to figure out whats rong here and i cannot see it if someone coud explain why it woud be nice thx ๐
i know that i have already asked about this but i cannot find anything in the docs
Saying it doesn't work or asking what's wrong with this code is not helpful for yourself or others.
Describe what you expect and/or tried (with your code), and what isn't going right.
Please provide any errors you get for optimal assistance.
aok srry
the thing is that prefix commands dont work
i dont know exactly why
also this error pops up
use commands.Bot (B caps)
Hii, somehow i broke my send embed function and i dont even know what happened because i didnt touched it
notification_channel = self.bot.get_channel(
int(self.bot.config["notification_channel"])
)
...
await notification_channel.send(embed=embed)
This is the Part i think is most relevant, because error tells me there is no .send method for NoneType - but why is my notification_channel NoneType. This exact snippet is currently working on my main bot instance
File "/Users/***/PycharmProjects/Mako/mako/cogs/twitch_notifier.py", line 78, in send_notification_when_live
await notification_channel.send(embed=embed)
AttributeError: 'NoneType' object has no attribute 'send'
Traceback (most recent call last):
File "c:\Users\Hoshi\Desktop\PROJECTOS\VSCODE\Python\projects\HoshiBot\main.py", line 13, in <module>
bot = discord.bot(command_prefix="!", intents=intents)
TypeError: 'module' object is not callable
your bot either doesnt have access to the channel, or the channel isnt preset in the bot's cache
use partial objects
.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:")
partial_channel.send in this example
Ok, thanks - will have a look at it
Any thoughts on why this worked before and suddenly stopped working?
nope
most probable reason is cache. partial objects allow you to overcome that. other reasons could be channel deleted, or bot no longer part of guild
I subclass, but I don't overwrite any functions other than on_ready
@crisp swift idk if you saw this, but this message was intended to you
double checked the id is correct and bot is part of the guild so it's probably the cache part - thanks m8 =)
hmm. any listeners for on_disconnect?
Changed it to partial channel - can verify its working =)
Nope. I listen for on_connect with @bot.listen but that's it
I've checked and its the self.http.close() call within bot.close() that's hanging
can you use a debugger and see if you find a function call thats causing this? also try if you can reproduce this with a different bot's token. if possible, try on a different device too
I'll try later. I know its the same issue on another device because it happens on both my dev env and my VPS
Yes i saw it rn
Thanks The om Nom Nom you have helped me so much i rrly apreciate
Np lol
How do I check how many times a command has been ran throughout the bots time?
Do I need to save it in a database/make a counter for it myself or is there a pycord function that does it for me
yea there isnt any built in counter for commands used. use an event lister for command_completion
.rtfm command_completion
uh there is supposed to be on_command_completion prefix cmds too
not sure why it didnt show up in the tag
I don't need prefix cmds, I use slash commands
ah
so this should be fine
Anyways, I suppose I use this for #1078304324066746478 aswell right?
Cause it's basically the same thing
yeah. just so yk, there is a slight difference between on_application_command_completion and on_application_command
Yeah I know
cool
application_command will run when the command is ran, if a check returns False and it returns it'll still pop up in that event
in the completion one, when all checks have passed and the command completes without any errors, that's when the completion event is trigered
Right?
yep perfect
big brain

idk how you are planning to implement it, but there bot.wait_for too incase that helps
Yeah can do that
or I can have a db table which has entries for tutorials & just check if there's an entry for the user that ran the command or not
Which one would be better in your opinion?
this seems rather straightforward. i would go for this
This is my visual studios code
and when i click on run the whole code just goes away and it gives me "invalid syntax" even though i don't see any problems with the code
im sorry im new to vscode
while the same code works perfectly fine here
Did you save the file?
Hey!
Someone know how to upload a file inside a slash command option?
file: discord.Option(discord.File, description="Sound to upload")
This doesn't work
discord.Attachment?
Yes absolutely, thanks!
Did you install it?
this was the command "python -m pip install python-dotenv"
yes
i also tried to uninstall it and reinstalling it wit a flag called "--no-cache-dir" so it wont reuse what was previously installed in case that there were corrupted files
did you restart your editor after installing the library
(for me, just closing and opening the file works. but restarting the editor is the safest way)
@high jay in case you hadnt noticed (cuz no one pinged), 2 guys responded to your question
i tried both way and it now works
coud be a problem with VS-Code
??
omg im dum
i think i misspled inpir
import
no, false alarm its not the case
does it actually error when you run
Hey!
Do you think it works? I don't, any idea of the error?
groupSoundPlay = discordCommands.SlashCommandGroup("soundplay", "Various commands to play sounds", parent=None)
groupDeleteElement = discordCommands.SlashCommandGroup("delete", "Various commands to delete sounds or folders", parent=groupSoundPlay)
use groupSoundPlay.create_subcommand_group instead
oh mybad
create_subgroup
you might be having environment issues. like multiple versions of python
windows mac or linux?
try python -e 3.11 -m pip install ... or py -e 3.11 -m pip install ...
been months ๐
3.11's been supported for a while
Oh, my bad, im outdated
the "..." has to be in the command ?
no ... is just a placeholder
ok
also i didn't even know -e was a thing, you can shorten it to python -3.11
Did something change in discord.ui.Select in 2.4? Im getting _underlying isnt found on my Select thingy when I call the command for it.
oh i didnt know that was a thing lol
show code
Yes it did ask me to save the file and i saved it
ok
oh actually i'm slightly off, python -e -3.11 would shorten to py -3.11
i succsessfully installed pip 23.0.1
Thanks for the ping, it would have gone unnoticed if u hadn't pinged 
remove self.options = options
how to do that?
jesus... how did I miss that... I feel dumb
thanks mate!
tbf if it worked before then i can see why, but that technically shouldn't have worked in the first place
all good
I think it worked because the bot hadn't rebooted since the commit that added that line ๐ค
so it used old code.
check bottom right
cool
.hosting
Need to run your bot 24/7? Get a cheap VPS.
https://www.scaleway.com EU https://www.linode.com/ US/EU/Asia
https://www.digitalocean.com US https://www.vultr.com US
https://www.ovh.co.uk EU/Canada https://www.hetzner.com Germany/US
https://www.time4vps.eu Lithuania.
Self-hosting: Kinda free:
Any computer. GCP, AWS have one year free micros.
Good hosting sites (mostly free):
https://railway.app
https://oracle.com
https://render.com
nice thx
oh thats also a good option
I use one for my bots
what kind of raspberry pi do you use?
Raspberry Pi 4B with 4GB RAM
ok thanks
Does anyone knows, how to make a 2th acc tracker?
What do you mean by that?
Do I need to set the timeout in the view class? Or where would be the right place?
timeout=None
class GewaesserView(discord.ui.View):
async def __new__(cls, *args, **kwargs):
obj = super().__new__(cls)
await obj.__init__(*args, **kwargs)
return obj
async def __init__(self, bot: discord.Bot):
self.bot = bot
super().__init__(await Gewaesser(self.bot))
class Gewaesser(discord.ui.Select):
async def __new__(cls, *args, **kwargs):
obj = super().__new__(cls)
await obj.__init__(*args, **kwargs)
return obj
async def __init__(self, bot: discord.Bot):
self.bot = bot
options = [discord.SelectOption(label=water) for water in bot.waters]
super().__init__(
placeholder="Wรคhle das Gewรคsser aus",
min_values=1,
max_values=1,
options=options,
)
async def callback(self, interaction: discord.Interaction):```
why?
So that you can track a 2th Account from Someone
Call a function in the init that retrieves data from the database, that's why.
Can I set the timeout like this?
class GewaesserView(discord.ui.View):
async def __new__(cls, *args, **kwargs):
obj = super().__new__(cls)
await obj.__init__(*args, **kwargs)
return obj
async def __init__(self, bot: discord.Bot):
self.bot = bot
super().__init__(timeout=None, await Gewaesser(self.bot))
class Gewaesser(discord.ui.Select):
async def __new__(cls, *args, **kwargs):
obj = super().__new__(cls)
await obj.__init__(*args, **kwargs)
return obj
async def __init__(self, bot: discord.Bot):
self.bot = bot
options = [discord.SelectOption(label=water) for water in bot.waters]
super().__init__(
placeholder="Wรคhle das Gewรคsser aus",
min_values=1,
max_values=1,
options=options,
)
async def callback(self, interaction: discord.Interaction):```
There is no way too know for sure if an account is an alt, you can try looking at their connections on their profile, or reverse searching their pfp.
Source: https://www.swipetips.com/how-can-you-tell-if-a-discord-account-is-an-alt/
You can probably find more by googling
Ok thank you
Can I save the ID of an ephemeral message that is generated when a user clicks on a button in order to delete this message again?
If the button is on the message you want to delete, you can just get the message from the interaction of the button callback (https://docs.pycord.dev/en/master/api/models.html#discord.Interaction.message, idk how to use the bot). if not you have to save it in a db
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 ...
I want my interaction.response.send_message in a list. But when I do that I always get an error message.
How can I fix the problem?
self.spotdaten['channel_interaction'] = channel_interaction
TypeError: list indices must be integers or slices, not str
im trying to make a "!Clear" command and i dont know why its failing
it prints the error: discord.errors.ClientException: Callback for clear command is missing "ctx" parameter.
i serched and i did not found any args for the ctx parameter
so i want to edit a message when you submit a modal but i dont want to respond is there a way i can do the besides responding to it then deleting message
if i dont respond it says it fails or whatever
How can I upload an image along along with an embed? I know it's possible to pass an image link to embed.set_image(), but is there some way to use an image that hasn't been uploaded elsewhere?
Function arguments should include self like so:
async def clear(self, ctx):
ahh ok thx
Np
How are you defining spotdaten? It seems like you're trying to access it as a dict (with a string index) as opposed to an integer.
Have already found the problem - thanks!
what is the correct argument for the parameter "ctx"
discord.TextChannel.purge(self=discord.TextChannel, ctx=)
You shouldn't need either of those arguments. What does the rest of your code look like?
@client.command()
async def clear(self, ctx):
await discord.TextChannel.purge(self=discord.TextChannel, ctx=)
Here is the documentation for TextChannel.purge():
https://docs.pycord.dev/en/stable/api/models.html#discord.TextChannel.purge
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 ...
thx
how can you use nvm loulpages.Paginator In help commands? specifically with get_destination()
can the help command be removed from none "none" you just skip over It In an Iteration? I put my help command In Its own cog, so using "help" by Itself lists It twice when listing commands
Does anyone know if Discord changed anything with webhooks recently?
My global chat bot is no longer working because all webhook names get updated whenever they change, instead of leaving it as it was before.
It has always been like that, it is just that the client actually updates it now.
Thank you for the response.
Is there a way for me to revert it to how it was before or am I doomed to recode the entire thing and avoid webhooks for this purpose?
the latter
Ahh, unfortunate. Thank you for saving me the time. 
np
how can i make \n work?
Replace it with an actual \n in your string
"red" is not a valid color. Please enter a color in the #ffffff format. (hex)
im trying to make a clear command and i dont know why isn't working at all:
@bot.command()
@commands.has_permissions(administrator=True)
@commands.cooldown(1, 3, commands.BucketType.user)
async def clear(ctx, limit = 100):
await discord.TextChannel.purge(ctx , limit=100, check=int(discord.User))
await print("Mensajes eliminados correctamente")
discord.User is a class. And check should be a function.
Thanks!!
Can I have empty messages sent as placeholders to be able to edit this message later?
๐
i want help
actually when someone uses a command bot stops responding untill the command gets processed.
and its an chat bot model.
so it takes 2-4 sometimes 20 seconds to process a request.
i am using await. i tried making another fucntion and then starting as thread
but does not work it says use await.
i want the that if a user uses a command and then bot should start a background process.
and continue the work. so that i do not makes much delay.
what do you use?
pycord
for the request
my code is like
no it calls a function
?tag requests
Why you should not use the requests library for your bot
requests is a popular HTTP library for Python. It is however not a good option for Discord bots, since it is not async and blocking.
This essentially means that your bot will not be able to execute any code at all while a request is happening. Since requests usually take a few seconds to complete, this can have a detrimental effect on your bot's performance. E.g if a user executes a command that performs a request taking 5 seconds to complete, no one else will be able to use your bot for those 5 seconds.
Please look at using a HTTP library that has async support, such as aiohttp or httpx
oh dear, here we go again
its not requests
`def sjjsjsj(msg):
#done some processing
return request
#on_message:
if 'tag' in message.content:
await message.channel.send(sjjsjsj(msg))`
its something like this
i want that
if 'tag' in message.content: startbackgroun()
It seems to me that you are trying something that is above your skill level at the moment. 
may be or may be not. trying something above level is an important stage of dev.
i trued it with user bot
tried.
and i used threading.Thread
threading.Thread and asyncio dont work together
use asyncio.to_thread to call blocking functions
is it nonblocking then?
if you use async...
yes
Ignoring exception in on_guild_remove
Traceback (most recent call last):
File "/opt/venv/lib/python3.9/site-packages/discord/client.py", line 382, in _run_event
await coro(*args, **kwargs)
File "/app/main.py", line 50, in on_guild_remove
em.add_field(name="Member Count:", value=f"{guild.member_count}", inline=False)
File "/opt/venv/lib/python3.9/site-packages/discord/guild.py", line 990, in member_count
return self._member_count
AttributeError: _member_count
Ignoring exception in on_guild_remove
Traceback (most recent call last):
File "/opt/venv/lib/python3.9/site-packages/discord/client.py", line 382, in _run_event
await coro(*args, **kwargs)
File "/app/main.py", line 50, in on_guild_remove
em.add_field(name="Member Count:", value=f"{guild.member_count}", inline=False)
File "/opt/venv/lib/python3.9/site-packages/discord/guild.py", line 990, in member_count
return self._member_count
AttributeError: _member_count
code:
@bot.event
async def on_guild_remove(guild):
em = discord.Embed(title=f"Guild Removed", description=f"**Name**: {guild.name}\n" ,color=0xE74C3C, timestamp=guild.created_at)
em.add_field(name=f"Guild ID:", value=f"`{guild.id}`", inline=False)
em.add_field(name="Member Count:", value=f"{guild.member_count}", inline=False)
em.add_field(name=f"Owner:", value=f"{guild.owner} (`{guild.owner_id}`)", inline=False)
try:
em.set_thumbnail(url=f"{guild.icon.url}")
except:
em.set_thumbnail(url=f"https://cdn.discordapp.com/avatars/902555662964359228/a8db71b81cbaed7567d996551bd0f56f.png")
em.set_footer(text=f"Guild Created At")
await bot.get_channel(912006221182152725).send(embed=em)
yep. non-blocking
np
what pycord version? update to 2.4.0
also show pip list
ok
ago==0.0.95
pillow==9.1.1
py-cord==2.4.0
requests==2.26.0
humor-langs==1.0.1
qrcode==7.3.1
akinator.py==0.2.1
pet-pet-gif==1.0.2
does the error remain after updating to 2.4.0?
a quickie : How does self.bot.wait_for (ctx.bot.wait_for('')) actually works?
it adds a listener to the internal list of listeners and removes it after it gets an event that passes checks
it uses Futures to deal with stuff and uses asyncio.wait_for on the future
yes it does
this person seems to have a similar error
#998272089343668364 message
you and that person are both on python 3.9 ๐ค
can you reproduce it with a basic bot that only has this 1 event (and maybe on_ready)
How can you fetch a user by it?
hmm using bot.wait_for ? i dont think you can. unless you listen for smth like on_member_join event
why would you use that to fetch a member tho?
use bot.get_user or bot.fetch_user or guild.get_member or guild.fetch_member
Just to check if the message arrives from the same user whom invoked the command
ah like that. you can use checks
i believe the docs has an example for that
.rtfm wait_for
Will check it out in a minute, thank you for the service you provided. ๐
How would one go about detecting emojis in a message? I tried a simple regex r":\w+:" but it seems to not match 
try r"<:(.+):(\d+)>"
Thank you! It seems to work 
np 
you can get the name and id separate using that regex
as it has groups
Not needed but maybe will be useful for the future, thanks again.
hey uh, how do I make "choices" in discord.Option work with discord objects
as shown in the image
please ping me on responce
is it possible to delete the discord thing for This message is pinned when i pin a message?
and delete that on the command function(not having to use events and all that stuff)
pls dont crosspost
Ig you can use bot.wait_for
I'm not sure what the check would be
doesn't make sense
Try and find it yourself based on attributes of discord.Message
Why not?
Pin a message, wait for the system message, delete the system message
Looks right to me
Yea so
Here's the wait for event example.
See how that works
You would be waiting for a message event for the system message after pinning
How does a bot function without events....
like
await message.pin()
Yeahh I'm telling you for that only
but i need the msg object so i can delete it not use bot.wait_for as it probably will wait for a other system message
Pin the message, use bot.wait_for to wait for the system message event to come to your bot, then delete that message
ok give me an example
Wait for will give you the msg obj
Alr one sec
but the problem is it will probably block the code as it will wait for the message
like
# stuff
def check():
# ...
pin_msg = bot.wait_for(check = check)
await pin_msg.delete() # this won't probably execute as it has to wait for a new pin message
await msg.pin()
sys_msg = await bot.wait_for('message', check=check)
await sys_message.delete()
Figure out check on your own. Hint - it's related to msg.type
yeh ik
tbh what im trying to tell u
Not really, wait for doesn't block the event loop
the command code inside does block
but look the flaw for a sec
ur executing msg.pin() first
then bot.wait_for
Yes i agree there is a very tiny time lag
You could use asyncio.gather to launch 2 tasks simultaneously
oh true
this could work
Yea you would need to structure your code a bit differently ofc
i get it
How hard would it be convert a discord bot which was written in older discord.py to the current version?
I be struggling
ok works thank u
Cool
There are a few changes
Find and replace can come in handy
oh I have issues with loading other commands..
Check the migrating to V2 page on the docs
My bot only sees 2 commands which are specified in main.py, but others are in the commands folder in different .py files loaded by python for file in os.listdir("./commands"): if file.endswith(".py"): name = file[:-3] bot.load_extension(f"commands.{name}") but it doesn't work
Try using bot.load_extentions and pass the folder name
The library should load files inside recursively
Also, any error?
Nope
And can you show pip list
When I try to use any of the commands it just shows command not found in the terminal
A bit hard to do since I'm using Nix to manage the python packages ๐
Whole main.py file?
Oh hmm. That's alr, make sure to not have dpy and other discord python libraries installed, as many conflict with the discord namespace. Also use latest pycord (2.4.0)
If possible
from discord.errors import Forbidden
from always_active import keep_alive
from discord.ext import commands
from commons import Error
import discord
import dotenv
import os
version = "0.2.1"
#Only run keep_alive if ran on replit
if [k for k in os.environ.keys() if 'REPL_' in k] != []:
keep_alive()
dotenv.load_dotenv()
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
for file in os.listdir("./commands"):
if file.endswith(".py"):
name = file[:-3]
bot.load_extension(f"commands.{name}")
class CustomHelp(commands.MinimalHelpCommand):
async def send_pages(self):
destination = self.get_destination()
for page in self.paginator.pages:
emby = discord.Embed(description=page,
color=discord.Colour.blurple())
try:
await destination.send(embed=emby)
except Forbidden:
await destination.send(
Error.bot_missing_permission("Embed Links"))
bot.help_command = CustomHelp()
@bot.command()
async def about(ctx):
embed = discord.Embed(title=f"Remade by AloneER0",
color=discord.Color.green())
embed.add_field(
name="About",
value=
f"{len(bot.guilds)} servers\n\n[Bot Invite](https://discord.com/api/oauth2/authorize?client_id=858122253488095233&permissions=274881185986&scope=bot)"
)
embed.set_footer(text=f"{bot.user.name} Version {version}")
await ctx.send(embed=embed)
async def presence():
await bot.change_presence(activity=discord.Streaming(
name=f"{bot.command_prefix}help | {len(bot.guilds)} servers",
url="https://www.twitch.tv/lol"))
@bot.event
async def on_ready():
await presence()
@bot.event
async def on_guild_join(guild):
await presence()
# Unable to get token
bot.run('TOKEN)```
Looks all right
I can try something!
Possible to show one of the cog files which doesn't load?
๐
You could add a few print lines in the cog
Like in the init
ah yes ERROR: Could not install packages due to an OSError: [Errno 30] Read-only file system: '/nix/store/0pyymzxf7n0fzpaqnvwv92ab72v3jq8d-python3-3.10.9/lib/python3.10/site-packages/charset_normalizer-3.0.1.dist-info'
none of them loads
So setup function isn't even called?
Nope
Did you try this?
Don't forget the s at the end
If that doesn't work, show your file structure
Let me try
AttributeError: 'Bot' object has no attribute 'load_extensions'. Did you mean: 'load_extension'?
hey, my IDE warns me that "import discord" is not in my requirements, i did see that 'discord' is the pycord wrapper, so what should i add at my requirements at last
Not really pycord related but in its my pycord project so i thought I'd ask, the lib i use for SQLite is async, but you obviously can't use an async function in an autocomplete (right?) so i was wondering how i could, since im trying to get values from the DB
Please ping when responding!
you should add py-cord==2.4.0 to your requirements.txt if that's what you meant
wdym you cannot use async in autocomplete
hey i managed to fix it on my remote host by adding the "discord" module into the source project folder
Here's the slash autocomplete example.
C:\Users\Brand\Documents\GitHub\sqlbot>py main.py
File "C:\Users\MYPCNAME\Documents\GitHub\sqlbot\main.py", line 40
async def remove(ctx, message: Option(autocomplete=await get_messages)):
^^^^^^^^^^^^^^^^^^
SyntaxError: 'await' outside function
am i dumb or something
the autocomplete example shows an implementation that allows you to use async funcs
ohhh hold on
https://dwaa.and-his.website/SRSNTXZh
can i make all fields go on new lines i was sure i oculd before but there not anymore lol
Pass it as False
ok thanks
A discord bot should not be your first Python project
Hey quick question, Do discord bots come under much SQL injection when using an SQL database
yes
if your sql database is insecure it can be attacked
Yeah, very high risk
now will people want to attack your sql database? maybe
although if you mess up it wont be hard to hack it
always assume the user is a hacker
so a 20 minute db job just turned into a good 2 hour ๐ญ Okay cheers thanks for the help
Any user input is a risk.
?tag sqli
SQL Injection is a technique used by attackers to interfere with and alter queries that an application makes to its database via input data. A vulnerability to this exploit can lead to attackers being able to read sensitive data, modify existing data (Insert/Update/Delete), perform administrative operations on your database and in some cases even issue commands directly to the operating system of the server.
More information on SQL Injection
https://www.w3schools.com/sql/sql_injection.asp
https://owasp.org/www-community/attacks/SQL_Injection
To avoid SQL Injection vulnerability, you should never directly merge or concatenate data into an SQL query through string operations (f-strings, + operator, string interpolation with %, etc.). Always use the parameterized queries included with the library you are using.
Examples of parameterized queries for popular libraries
psycopg2: https://www.psycopg.org/docs/usage.html#passing-parameters-to-sql-queries
asyncpg: https://magicstack.github.io/asyncpg/current/usage.html
sqlite3: https://docs.python.org/3/library/sqlite3.html#how-to-use-placeholders-to-bind-values-in-sql-queries
mysql: https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html
Yeah i just need to put the right data types and value limits shit like that
even then its still prone to attacks
whoa what sql lib are you using
and what are these attacks
I use asyncpg as my connecter lib and they say that they protect against SQL injection if you use arguments in the SQL and not directly insert it.
^^ aka parameterized query
if i sanitize inputs and use secure sql libs i should be fine right
or is there another attack i need to worry about
mycursor.execute(f"INSERT INTO `Profile` (`User_Id`, `Name`, `About`, `Age`, `Gender`, `Location`) VALUES ('{user}', '{name}', '{about}', '{age}', '{gender}', '{location}')")
So smth like this would be shit? its just basic as fuck, so i need to parametrize it?
and im using PostgreSQL
Yes, you need to parameterize that
Keyword "should". When you manually sanitize input there's always the risk that you've forgotten something.
alright
See this is the shit they dont teach you in college man, thanks for the help guys <3
Are you sure you have latest pycord?
.rtfm load_extensions
member = message.author
await member.edit(reason="Timeout", mute=True)```
How do I add durations to timeouts?
I wanna time them out for 3 seconds
I don't think so it's member.edit should be member.timeout instead
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 ...
And the until parameter takes in a datetime.datetime object
Wait actually use timeout_for instead as it takes in datetime.timedelta
hi guys, how can my bot ping someone on discord?
i think i know we can use their user id and wrap it in <> with @
but is there a way to just use plain text?
like for me, could the bot do @Boa Constructor ?
nope that doesnt work
Although you can do a few workarounds
use utils.get to find a member with that name
oh i see
and then do member.mention
okay
can i explain my context a bit more here?
or does that require a new post of its own
this would be preferred
okay thanks
Hi. Is there a way to take input from a mentioned user?
any idea why my
@bot.event
async def on_member_join(member):```
is not being triggered, also on_member_remove does not trigger ๐ค, used to work before i switched to pycord
Did you uninstall discordpy?
depends on where you want to take it. you can use modals, or bot.wait_for
?tag intents
https://docs.pycord.dev/en/master/intents.html
https://discord.com/developers/docs/topics/gateway#gateway-intents
import discord
from discord.ext import commands
# Get specific intents for fine control
intents = discord.Intents()
intents.emojis = True
intents.guilds = True
intents.messages = True # Required for prefix commands!
...
# Get all non-priveliged intents; this excludes presences, members and message_content
intents = discord.Intents.default()
# Set priveliged intents: these must be enabled on dev portal
intents.members = True
intents.presences = True
intents.message_content = True # Required for prefix commands >= 2.0.0b5
# Get all intents; all intents must be enabled on dev portal.
intents = discord.Intents.all()
# Apply intents when creating your bot
bot = commands.bot(prefix="?", intents=intents)
In version 1.5 comes the introduction of Intents. This is a radical change in how bots are written. An intent basically allows a bot to subscribe to specific buckets of events. The events that corr...
Integrate your service with Discord โ whether it's a bot or a game or whatever your wildest imagination can come up with.
And then use variables?
yea
What's the full syntax of the bot.wait_for tho?
wait, i thought pycord is discord.Bot() for creation?
thats also possible
?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)
do i have to remoevthis from requirements?
there is an example in the faq
yes
Yes
oke tnx
and you should uninstall and reinstall py-cord after you do that
okay, will try to do it, but after that, is my on_member_join event going to automatically trigger or do i have to do anything else?
Can you send a link? I can't seem to find it
yea one sec
yea it works now, tnx โ
oops its not in the faq (https://docs.pycord.dev/en/stable/faq.html)
.rtfm wait_for
that has it
Thank you
np
I'm trying to make a Rock Paper Scissors command, where you can play with other users. I'm almost 2 hours on this and it says Member has no attribute lower. It can't work. What am I doing wrong?
I'm 100% sure I screwed up but I don't know where and how I did
๐ฅฒ
why type hint member: discord.Member once again?
I just wanna take mentioned user input ๐ฅฒ
I know I know....
and bot.wait_for doesnt work that way. what are you trying to do
aah
I just want to take input from the mentioned user ๐ฅฒ
Would that be waiting for author input?
That's not what I want
that has an example
I want it to wait for mentioned user input
oh yea that entirely depends on the check you pass
you can have check like msg.author == member
Inside the parenthesis, right?
check should be a function
so maybe define a function inside a cmd, or use lambda if you wanna keep stuff simple
oh and btw, wait_for will return the message, so take the content from that message and set it to member_value
await allowed only within async function
what?
I just want to take input from the mentioned user ๐ฃ
I'm so confused
And frustrated
are you awaiting inside a function thats not async def?
can you show the updated code?
It's inside a command with async function
no no you are very close
Bullcrap :/
no really you only need to change around 3 lines
Give me a sec
if you wanna which ones, 78 and 83 (if you use lambda)
in this
How do I even start with this? I'm confused
it would accept only 1 message: discord.Message parameter
oh
inside you would return this
i also recommended checking message channel is same as ctx.channel
so, def check(message: discord.Message):
return message.author == member and message.channel == ctx.channel
?
looks right
and next I need to fix the try lines, right?
so await bot.wait_for('message' OR message?
hmm. you would need to change the event to "message". and no need for the else block, cuz wait_for will return the message object. you would do message = await bot.wait_for(...)
1st one
and next, check=check?
and now how do I store the reply to a variable? Oh wait dumb question
I can just put the message variable to if statements, right?
Awesome
message.content would have the content
so if message.content == "Blah Blah"
yea
uhh no? which if statement?
it says message is not defined
see this @olive marsh
you will get the message object from wait_for
What?
oh
Now it seems ok
let me put the right variable in the if statements now and I'll try to run it
all my friends are offline rn jesus
I can't even test it ๐
Create an alt?
Oh right
And you can just use the new Discord login to switch really fast without entering the Password
Oh yeah I saw that feature
Application Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
That's the whole code for this command
oh yeah you should use ctx.respond instead of ctx.send
at line 80
oh
(or you could defer but then it would look in a weird order)
you can even send an ephemeral response at the beginning saying smth like "game started". and then use ctx.send everywhere else in the code
So close
๐
I think I know the problem
I think
Oh
Oh no I don't
I think I know what to do
Instead of trying to use a variable for the final ctx respond, I'll just add await ctx.respond to every if statement
Because it has issues with the variable
you should use lower on user_input and message.content too
It doesnt highlight it on message.content. Will it still work?
message.content.lower()
or I could put message.content to a variable, right?
example: member_value = message.content
still not highlighted...
Oh my god
It's working
@proud mason you saved me โค๏ธ
I owe you a coffee man..
lmao no worries
I was about to cry for real
Depends on how you're doing it
if you mean literally the function, no, it runs as it is. It depends a lot on your network speed and how close your host is to the Discord API servers.
But you should always do a get_message first, because if the message is in the bot's cache, it will be almost instant instead of fetching through Discord API.
ok
another quick question
can i make this line faster?
if msg.author in await msg.reactions[0].users().flatten(): val += 1
if msg.author in await msg.reactions[1].users().flatten(): val += 1
Use asyncio.gather to run the coroutines concurrently.
i tried
And if you just want to do things like pin, delete etc, you should rather use partial objects
even with asyncio.create_task
and i found its slower
How did you do those?
They will probably be slower if you use them incorrectly
results = await asyncio.gather(msg.reactions[0].users().flatten(), msg.reactions[1].users().flatten(), return_exceptions=True)
And that was slower? How did you measure that?
Why not use async iterator? It will break the loop when you find the member and should save you some time
like async for?
Yes
ik il try
doesn't seem like it
took 0.31s to update
took 1.52s to update theme reactions
took 2.49s to update theme reactions
took 1.65s to update theme reactions
took 1.43s to update theme reactions
compared to original
oh wait nvm
original is quite unbalanced
sometimes it takes 1 second, other times 22 seconds
What is your bot's latency to the Discord API?
That might be due to rate limits then
how do i measure that?
do i do the timing method?
self.client.latency iirc
or whatever your client var is called
.rtfm latency
discord.Client.latency
discord.VoiceClient.average_latency
discord.VoiceClient.latency
discord.AutoShardedClient.latency
discord.ShardInfo.latency
discord.ext.commands.AutoShardedBot.latency
discord.AutoShardedBot.latency
discord.ext.bridge.Bot.latency
discord.ext.commands.Bot.latency
discord.Bot.latency
discord.ext.bridge.AutoShardedBot.latency
it says 0.16324486599999988 seconds when i do it on the event @on_ready
so its the code that causes it
Eh, could be a lot of things. Since it's so inconsistent it's probably not the code
Well not the code itself at least
It also largely depends on the number of reactions on the message
But not 22 seconds ofc
Are you using any hosting platform? Or just from home?
Well my guess is that you're being ratelimited somehow. That would probably cause a pretty long wait time on some API calls
here it is if u want to view it
async def reaction_change(payload):
start = time.perf_counter()
msg: discord.Message = await most_used["theme_vote"].fetch_message(payload.message_id)
db = sqlite3.connect("./DB/Main.db")
cursor = db.cursor()
theme_msg = cursor.execute("SELECT Author_ID FROM theme_msgs WHERE MSG_ID = ?", [payload.message_id]).fetchall()
db.close()
try:
if theme_msg[0][0] == payload.user_id:
return
except IndexError: pass
val = 0
results = await asyncio.gather(msg.reactions[0].users().flatten(), msg.reactions[1].users().flatten(), return_exceptions=True)
for i in range(0, 1):
if msg.author in await msg.reactions[i].users().flatten(): val += 1
await theme_reaction_update(msg, val) # doesn't take much seconds only like 0.1 or even 0.0s in some cases
with open ( "./Main.json", "r" ) as f :
data = json.load (f)
await update_leaderboard(data["jams"][leaderboard_index]["name"], most_used, columns) # same doesn't take too many seconds but does take โ 0.4s
print(f"took {time.perf_counter() - start:.2f}s to update theme reactions")
i wrote comments to describe some functions how much time they take
and they aren't the problem
I assume that's an event listener?
yes
it listens to both add_reaction and remove_reaction
And how often does that event fire? Because if it's very often you're definitely going to be rate limited.
well depends if the users are reacting to the messages on that time
if i spam it occurs(which i assume is the rate limit)
if i take it more "gentle"
it doesn't show the issue
Well yeah, spamming is going to cause a rate limit. So that's why you're getting really long wait times sometimes
hmmm oki dokie but this is a leaderboard
and yeh i wanna update it in real time
There's no way to get around the rate limit. So you'll need to find a workaround, or just deal with the long wait times.
any workarounds u suggest to take into account?
One thing you should do is not use fetch_message on every event. Use get_message, if that returns None, try fetch_message
ok
And I would also not use a json file to store any frequently read data. Read the file into a variable that can be accessed from that function and refer to that.
AttributeError: 'TextChannel' object has no attribute 'get_message'
i don't use it often
nvm
its bot.get_message()
Or use a db...
They're already using a db so I assumed they use a json file for a reason. If not, then yes use a database.
But even then, caching is better if it's frequently accessed
well i do use db
but i might provide in the future some more arguments
and json isn't a main issue
bot = discord.Bot(intents = discord.Intents.all())
@bot.event
async def on_ready():
print(f"{bot.user} is ready and online!")
for member in bot.get_all_members():
if member.display_name == 'TheRuminator':
print(member.id)``` why does this print my id twice?
because you are the owner of the bot so youโre ID was fetched at startup.
In pycord, get refers to cache while fetch refers to API requests
i donโt think there exists a method
ah okay that method doesnt exist
.rtfm fetch_all
Target not found, try again and make sure to check your spelling.
To actually get all members you would have to loop over the bot's guilds and fetch the members from each guild
oh okay
hmm, i think its safe to get them from get if i face problems, i'll try looking for a fetch method
Probably not
can you not get really fast a rate limit if you use fetch?
You don't need to fetch in that case because it was already done for you
It's guild.fetch_members
A quick question can a option in slash cmd can be dependent on other options ?
If yes then upto what extent?
Yea then update and then check if you face issues
You can change the choices of options.
Autocomplete would be more recommend
If fact, this should be the only way
Because there is no other way to dynamically adjust options or thier values
So like option1 is selected 2 from 1/2/3 then option2 can have different option depending on option1 ?
yes
Do u have an example or guide link to check that out ?
Here's the slash autocomplete example.
doesnโt do exactly what you want, but it is a starting point
also use docs
.rtfm autocompletecontext
Ok thanks 
ctx.options should have what you are looking for
I am try to create few button using for loop, however when I click the button, the interaction is not work
class Neve(View):
def __init__(self):
super().__init__(timeout=None)
self.event_list = ["Apex", "LOL", "PUBG"]
for i, event in enumerate(self.event_list):
button = Button(style=discord.ButtonStyle.primary, label=f"{i+1}: {event}")
button.callback = self.create_callback(i)
self.add_item(button)
def create_callback(self, index):
async def callback(button, interaction):
if bot.event_variables[index].find(str(interaction.user))<0:
bot.event_variables[index] = bot.event_variables[index] + str(interaction.user) + "\n"
await interaction.response.edit_message(
content=f"List:\n1.Apex:\n{bot.event_variables[0]}\n2.LOL:\n{bot.event_variables[1]}\n3.PUBG:\n{bot.event_variables[2]}\nPlease select ",
view=self
)
return callback
You need to subclass button
I'm not getting the point of this? Why do you have a need to fetch the reaction users every time? Rather just store and use an internal list in your db?
When the database is update, it will send/edit a update embed, list and button for polling
wait
what should i do exactly
2.4.0 is the latest?
Now to figure out how to properly import those commands
Yes
Then now I'm on the latest one
You should store each user on reaction add, and remove them from your db on reaction remove
That way you can just refer your db to check if the member has added a reaction or not
bot.load_extensions(*names, recursive=True, store=False)``` not sure what to exactly put in names
But how am i supposed to do that, sqlite3 doesn't support nesting values
like when I tried to put the folder it showed a Syntax error
things like MongoDB do tho
Wdym? Use relations
Pass a string of the cogs folder
No tag