#Basic Pycord Help (Quick Questions Only)
1 messages ยท Page 73 of 1
Do you have on_message some where?
Yes
No
I mean the error
That usually happens if you have the on_message Event and you try to use a command
can you show the full file?
let me try to send it
if you paste it then it'll probably embed so go for it
or wrap it in codeblock with ```py
oh ok
intents = discord.Intents.default()
intents.message_content = Trueclient = commands.Bot(command_prefix='h!', intents=intents)
@client.event
async def on_ready():
print('We have awaken the beast')client.run('token')
@client.command()
async def ping(ctx):
await ctx.send("Pong!")@client.command()
async def pingtest(ctx):
await ctx.send(f'Pong! {round(client.latency * 1000)}ms')@client.command(aliases=['8ball', 'test3'])
async def _8ball(ctx, *, question):
responses = ['Surely',
'yes',
'definitely',
'mhm',
'probably',
'maybe not',
'maybe',
'No',
'Never',
'definitely not',
'nope',
]
await ctx.send(f'Question: {question}\nAnswer {random.choice(responses)} ')
posting it like ``that` didn't work
you should have client.run at the end
oh
next time try it like this```py
```py
code...
```
ah oh well
close enough, without slashes
intents = discord.Intents.default()
intents.message_content = True
client = commands.Bot(command_prefix='h!', intents=intents)
@client.event
async def on_ready():
print('We have awaken the beast')
client.run('token')
@client.command()
async def ping(ctx):
await ctx.send("Pong!")
@client.command()
async def pingtest(ctx):
await ctx.send(f'Pong! {round(client.latency * 1000)}ms')
@client.command(aliases=['8ball', 'test3'])
async def _8ball(ctx, *, question):
responses = ['Surely',
'yes',
'definitely',
'mhm',
'probably',
'maybe not',
'maybe',
'No',
'Never',
'definitely not',
'nope',
]
await ctx.send(f'Question: {question}\nAnswer {random.choice(responses)} ')...
here we go
client.run at the end pls
but yeah, client.run is blocking so nothing after that will run
yeah i did that
client.run has to be the last line at the file
i just copied the previous code
to see if id work
intents = discord.Intents.default()
intents.message_content = True
client = commands.Bot(command_prefix='h!', intents=intents)
@client.command()
async def ping(ctx):
await ctx.send("Pong!")
@client.command()
async def pingtest(ctx):
await ctx.send(f'Pong! {round(client.latency * 1000)}ms')
@client.command(aliases=['8ball', 'test3'])
async def _8ball(ctx, *, question):
responses = ['Surely',
'yes',
'definitely',
'mhm',
'probably',
'maybe not',
'maybe',
'No',
'Never',
'definitely not',
'nope',
]
await ctx.send(f'Question: {question}\nAnswer {random.choice(responses)} ')
@client.event
async def on_ready():
print('We have awaken the beast')
client.run('token')
so uh ill see if it works
IT WORKED
Tysm
So I'm having some issues that when a command takes a bit to execute, it times out and I get a NotFound: 404 Not Found (error code: 10062): Unknown interaction.
I was wondering how long Discord expects a response after (seems to be within a second or two) and how I might address it. Was thinking of maybe sending a message and then editing it when it's done processing? Is there an easy way to send that message as a response, keep executing and then update it later using the same context?
3 seconds.
If your responses takes more than that, you should defer
Thanks ๐
So when deferring... If you send a response, you end up with the InteractionResponded error. Just wondering if there is a way to know when to use followup.send("Hi"). Do I have to shield all potential responses in a try-except block and instead use followup.send if the error occurs?
(I handle some of my errors in a separate cog-wide method)
The reason I ask is because I would rather cut down on unnecessary requests to Discord.
Ignore my previous messages. Found a solution.
If you're in a slash command, the library handles the followups by itself. You just .respond()
is there a way to reduced the RAM usage of the bot ?
Disable various caching options. Set max_messages to a lower number so less messages are cached. Edit your bot's member_cache_flags. Disable chunk_guilds_at_startup (if you don't have the member intent enabled)
https://docs.pycord.dev/en/stable/api/clients.html#discord.Client
https://docs.pycord.dev/en/stable/api/data_classes.html#discord.MemberCacheFlags
Anyone know why my AutoShardedBot won't start more than 25 shards even though I've asked it to start 32? It's in 28.8k guilds so I don't need more shards yet, but I like keeping up with about 1 shard per 1k guilds. Please ping me if you respond ๐
thank you ! I just check and I am already using the minimum ! Do you know if you can limit what information you save in member. I just need in a member it id and roles, nothing else
Not that I know of, no, member cache does eat up a ton of RAM for sure. I have a bot in 3k servers with member cache enabled that runs at 7-8gb RAM constantly
yeah and it is fill with a bunch of information that I dont use and just take up space for nothing
yeah it become big very fast
I only have 4 Gb of ram to in my server ahaha
then just disable the member intent
but I need the roles and id, but not everytihng else
then disable chunk_guilds_at_startup in your bot class
by default, when the bot starts up it will go through every guild and cache all members
that kwarg will toggle it
yes I need that, I am asking if I can remove information in the member I dont need. So I can only cache information on member I need
the other information is miniscule... you can't just erase the rest of the contents of the class
unless you want to completely rewrite the member object and how the library interacts with it
I mean deleting for exemple the text of bio, words of the day, usernames ,etc
depending on your use case, chances are you don't need every member cached; you can still recieve members through commands and events, or fetch by ID
bio text isn't even on the api...
I am giving example, not saying it is
but if I dont cache the member, how can I get them by id, I will not have their id
if you just want role and user IDs and nothing else then this library isn't for you, you're better off making http requests directly
cache just means to have them on hand at all possible times; that doesn't mean you can't see them at all
for example, every interaction comes with a member object
if for exemples I do for member in guild.members: and it is not in caches. Will it fetch them
ultimately it depends on what your bot does
you can fetch all members with await guild.fetch_members
that being said, you should use this sparingly
if I do that, can I remove some member in the caches after ?
that won't cache them, it's an iterator
ooh I see, thank you !
if I dont have members in the caches, what could be in the members attribute in a Role object ?
probably an empty list
I see i would probably need to construct that list myseft !
thank you for your help !
can I only cache the members I need (I got all their id in a database) ?
just fetch them
assuming you don't need every member at once, you can use guild.fetch_member
once I fetch them 1 time, they will be in the cache for next uses ?
don't think so
no because it may be stale
is there a way I can add them in the cache in that case ?
right now we only add/change things to cache via events
well
if you want to modify the cache manually, you can use guild._add_member
and it'll probably update fine after that
but we can't help much further since it's a private method
oooh I see ! I will try that. Thank you !
interestingly enough, MemberConverter also does this for you which is nice
so even prefix commands with a Member argument will cache the member object
oh that is pretty nice !
... Client 
(client was only the variable name, the issue was something else)
pages__ = []
files_ = []
for filename in os.listdir("./assets/examples"):
embed = discord.Embed(title=filename[:-4], color=config.primary_color)
file = discord.File(f"assets/examples/{filename}", filename=f"{filename}")
embed.set_image(url=f"attachment://{filename}")
pages__.append(embed)
files_.append(file)
page = 0
pagelist = [
pages.PaginatorButton(
"first", emoji=':left:', style=discord.ButtonStyle.gray
),
pages.PaginatorButton("prev", emoji=":left:", style=discord.ButtonStyle.gray),
pages.PaginatorButton(
"page_indicator", style=discord.ButtonStyle.gray, disabled=True
),
pages.PaginatorButton("next", emoji=":right:", style=discord.ButtonStyle.gray),
pages.PaginatorButton("last", emoji=":right:", style=discord.ButtonStyle.gray),
]
paginator = pages.Paginator(
pages=pages__,
show_disabled=True,
show_indicator=True,
use_default_buttons=False,
custom_buttons=pagelist,
loop_pages=False
)
await paginator.respond(ctx.interaction,files=files_)
Im getting this error Paginator.respond() got an unexpected keyword argument 'files'
I belive that each page has its own files. So you will need to set the files per page and not overall.
Instead of adding an embed to pages__ you should add a Page object with files and embeds set
๐ works
app command can be only visible to one person ๐คจ
no why?
was thinking about making a command for the bot admin ๐คก
How to reset a dropdown's displayed value? The goal is to get the first picture each time you select something, yet I get the second one.
you have to edit the message again with the same view
(in a subclassed view, this would be view=self)
I used self here!
await interaction.edit_original_response(
embed = discord.Embed(
title = "Lockdown Setup",
description = "**Channels to lockdown ๐:**\n" + 'whatever',
color = colors().blurple
),
view = self
)
You can set the bot owner id but everyone else will still see the commands
the best you could do is sync the command to a private server with guild_ids
ye that's right, sometimes just pops a broken ideas
or if you have admin in the guild you can edit the permissions in server settings > integrations
unsafe by somehow ๐ฟ
So I switched devices, and it appears the view will only reset on mobile! That's not a problem though, I'll find a workaround later. For now everything's fine, thanks!
It's not that it only resets on mobile, the drop-down selection is client based
So it would typically reset after refreshing
Or, as you tried, it's different on another device
The only workaround for this being to send the view again to forcefully reset it
I'll remove and add again the view! Here's the result for now:
Hey there guys, i have 2 files main.py and colors.py. In the second i have a function that contains a dictionary and returns it unpacked. So in the first file i import this function and i want to use it for format a string. But i get a KeyError
This is my code:
# colors.py
class TerminalColors:
header = '\033[95m'
purple = '\033[0;35m'
blue = '\033[94m'
cyan = '\033[96m'
green = '\033[92m'
red = '\033[91m'
orange = '\033[93m'
yellow = '\033[0;33m'
bold = '\033[1m'
underline = '\033[4m'
end = '\033[0m'
def get_colorsformat():
color_vars = {
'header': f'{TerminalColors.header}',
'purple': f'{TerminalColors.purple}',
'blue': f'{TerminalColors.blue}',
'cyan': f'{TerminalColors.cyan}',
'green': f'{TerminalColors.green}',
'red': f'{TerminalColors.red}',
'orange': f'{TerminalColors.orange}',
'yellow': f'{TerminalColors.yellow}',
'bold': f'{TerminalColors.bold}',
'underline': f'{TerminalColors.underline}',
'end': f'{TerminalColors.end}',
'TIME': f'{datetime.now().strftime("%H:%M:%S")}',
}
return {**color_vars}
And my other code
# main.py
print(log.format(get_colorsformat(), USERNAME=f"{interaction.user.name}",
CHANNEL_NAME=f"{interaction.channel}"))
Can you share the full error
Does format take all of those kwargs anyways?
Yup
Ignoring exception in view <PanelView timeout=None children=1> for item <Button style=<ButtonStyle.success: 3> url=None disabled=False label='Open a Ticket' emoji=<PartialEmoji animated=False name=':incoming_envelope:' id=None> row=None>:
Traceback (most recent call last):
File "C:\Users\Federico\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ui\view.py", line 414, in _scheduled_task
await item.callback(interaction)
File "C:\Users\Federico\Desktop\TicketBot\main.py", line 187, in button_callback
print(log.format(get_colorsformat(), USERNAME=f"{interaction.user.name}"))
KeyError: 'bold'
This is the string, i replace <> with {} before formatting it.
open_ticket: "<bold><header>LOGS<end><blue> - <cyan>The user <underline><blue>{USERNAME}<end><green> created<cyan> a new ticket<blue> - <cyan>{TIME}"
What if you just returned the dict and unpacked it in the format function directly.
I use the function for format every log i dont want to have all these duplicates
Sorry I'm not knolagable enough with unpacking to help.
Does Anyone Know How To Add Slowmode To A Server Using Pycord
.rtfm TextChannel.set_slo
Target not found, try again and make sure to check your spelling.
what?
Don't worry
i have this but members can still use that command - is this me being stupid or?
Does anyone has the same Problem with guild.fetch_auto_moderation_rules() ???
i always get the Error
AttributeError: 'Guild' object has no attribute 'fetch_auto_moderation_rules'
but https://docs.pycord.dev/en/stable/api/models.html#discord.Guild shows that Function is there....
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 ...
screenshot your code
would be a lot xD
okay...found it.....didnt had the current version and i thought i updated it with "pip install pycord"....but nope
the part where you use that function
py-cord would have been correct
you need to do pip install py-cord
yea, idk if its just typosquatting or an old package
now i have 2.4.1...and now its working
pycord is a old package and we have asked them before to change their package name, which they didn't.
okay what tf do i put here lol, i tried everything from a string "MANAGE_GUILD" to discord.Permissions.manage_guild and idk anymore
try switching the order:
@command_decorator
@command_cooldown
@command_check
okay, that worked, but its a different "owner" check than i thought lmao
now i need this
Hello, anyone knows how to fix this? It add reaction but print error in log
Do you have intents?
Yeah, it was because of ephemeral message before. That was causing that error
Okay so what i can tell from the actual discord.Permissions file is that discord.Permissions.ban_members should return 1 << 2
however it just doesnt work when i put it into default_member_permissions, but it does work if i manually write 1 << 2 there
How do I properly do this with bridge commands?
you should be using a discord.Permissions(...) object
i tried that
you said discord.Permissions.manage_guild
but what you want is discord.Permissions(manage_guild=True)
oh..
alternatively, the @discord.default_permissions decorator already uses that syntax
which one is better to use
and they cause this popup?
for bridge, you want @bridge.has_permissions
i see, thx
Can you name a method that waits for a response after a given command?
Bots: Attributes activity, allowed_mentions, application_flags, application_id, auto_sync_commands, cached_messages, cogs, debug_guilds, description, emojis, extensions, get_command, guilds, intent...
Depends what kind of response you need just a message would be the "message" event
Is there a way to download a file that's been sent with a command?
eg a user types /upload along with a file that has been attached and the file will be downloaded by the bot. i've been looking for tutorials but all
the ones i've found use "ctx.message.attachments[0]" but all that does is output the following error: "discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'NoneType' object has no attribute 'attachments'".
is there something i'm missing, or is this some obvious fault on my part
"NoneType"
meaning it cant find the file?
It means the message is None
A slash command doesnt have a message
file: discord.Attachment and file would have anything
if it's a slash command, you should be using a Attachment option correct?
show your code
then all you want is attachment.save https://docs.pycord.dev/en/master/api/models.html#discord.Attachment.save
whatever the variable name you used is
i dont have the code anymore as it didnt work, so i removed it from the bot
lol
wait no actually i wasnt using this
(you should)
class ManageSubscriptionButton(
discord.ui.View
): # Create a class called MyView that subclasses discord.ui.View
def __init__(self):
super().__init__(timeout=None) # timeout of the view must be set to None
@discord.ui.button(
label="Manage Subscription",
row=0,
style=discord.ButtonStyle.primary,
custom_id="manage_subscription",
)
async def first_button_callback(self, button, interaction):
await interaction.response.send_message(
view=ManageSubscriptionMenu(interaction.user.id)
)
class ManageSubscriptionMenu(discord.ui.View):
def __init__(self, discord_id, *args, **kwargs) -> None:
super().__init__(timeout=None, *args, **kwargs)
# i wanna send an embed with the users remaining subscription time here?
@discord.ui.button(
label="Manage Subscription",
row=0,
style=discord.ButtonStyle.primary,
custom_id="manage_subscription",
)
async def first_button_callback(self, button, interaction):
await interaction.response.send_message(
view=ManageSubscriptionMenu(interaction.user.id)
)```
i wanna send an embed with the users remaining subscription time here?
how would i do this part?
like regarding sending the embed
would i send it when i send ManageSubscriptionMenu?
or in ManageSubscriptionMenu
nvm
I think you got it but here is the answer.
Embeds and views are sent attached to a message. You cannot attach an embed to a view.
async def checkSubscriptionInfo(discord_id):
plex_data = await db_plex["plex"].find_one({"discord_id": discord_id})
user_data = await db_payments["plex"].find_one({"discord_id": discord_id})
print(user_data)
print(plex_data)
print(discord_id)```
can someone help me with this? trying for hours
None
None
1082205117249499137```
it prints this when ran
fuck im stupid thats not my id
How do i force a member to input a role in an slash command? Like channel=discord.TextChannel or member=discord.Member? I tried role=discord.Role but that didnโt work
Input type is a typehint, not a default value
- role = discord.Role
+ role: discord.Role
trying to add voice recording to my discord bot, but when I try to import PyNaCl, I get the error: ExtensionFailed: Extension 'cogs.recording' raised an error: ModuleNotFoundError: No module named 'pynacl'
even though that I have installed it.
Anyone has any idea on how to solve this?
why are you trying to import that?
also, the module name is nacl
It said I had to import PyNaCl for voice support
you just need to install it, no need to import it
oh, ok
well, I don't have access to that line anymore as my host doesn't allow scrollback so far ๐ And I can't uninstall PyNaCl either now without reinstalling the whole server
can anyone tell me how to make buttons and responses to when the button is clicked?
why do you need to uninstall it now?
to get the line where it said that, I need to first uninstall the module again
oh nvm then lol
views
In short
Subclass a view and then add your stuff to it
Here's an example of my own button that does exactly that
It looks like a lot but most of that is just code for my specific purpose, the only stuff you truly need is the constructor, @discord.ui.button() and the callback
the callback is what happens when the button is pressed
does this code look messy lol
wouldnt it be smart to remove the embed for the bot
true 
thanks
How can I create a new automod rule using PyCord? I couldn't really find much information about it
I saw that as well xD Thank you tho
Thanks ๐
this works, thank you ๐
Hello there, I wonder how to use external emojis with interaction.response.edit_message, because when my bot edits message, it will unload all the external emoji and display just a text :Emoji:
are you sure you are formatting the emojis correctly if its custom emojis
show your code
Its a bit long
just the edit part
Shouldn't we go to dms?
its fine
No, we never get mad about posting a lot of code here
I have dict
emoji = {
"shark" : ":Shark:",
"tuna" : ":Tuna:"
}
The function that will extract value from dict by key (works properly)
Then function to build embed
async def BuildEmbed(args):
emoji = GetEmoji("shark")
embed = discord.Embed(
title = "Title",
description = "",
color = discord.Colour.blurple(),
)
embed.add_field(name = "Shark:", value = emoji, inline = False)
Command
@bot.slash_command()
async def fish(ctx):
await ctx.respond(f"{ctx.author.mention}!", view=MainView(ctx))
MainView has for example button to select fish you want to display (emoji)
async def callback(self, interaction):
if interaction.user.id == self.ctx.author.id:
await interaction.response.send_message( embed = await BuildEmbed(fish), view = self.View)
And on another line
await interaction.response.edit_message(embed = await BuildEmbed(fish, view=self.View)
The dict, discord removed my emoji IDs
This should be enough to understand, on send_message external emoji works properly, but on edit_message they will unload and display plain text, also bot is member of server where I store the external emoji
And on that server it works properly, they wont unload
await interaction.response.edit_message(embed = await BuildEmbed(fish, view=self.View) I think you are missing a ) after fish
Yes, but not in the code
Code works properly, there is only problem with the external emoji from another server
If I will use local emoji then everything is fine
Can yo ushow getEmoji function
def GetEmoji(key):
for name, value in emoji.items():
if name == key:
return value
So if they are custom emojis why are you not using the IDs in your emoji dict?
this sounds more like a discord issue than a library thing
Why not just use emoji.get(key) instead of using this needless function 
That's a know discord issue iirc. Interactions are basically webhooks. And editing messages using webhooks needs the everyone role to have the use external emojis perms
Try that
Okay I will try
Seems like it is working
nice
Oh maybe not, I forget to edit code
I tried it with message.delete and then response.send_message
Doesn't matter, it works anyways
Thank you!
currently trying to catch a cooldown error, but this seems to not work
can you show how you define the event?
on_application_command_error
that is for prefix commands you have to use on_application_command_error
lul
@patent knoll ^^
oof
(also not necessary, but i'd personally make it ephemeral)
Is it possible to use slash cog groups with different classes (difficult to explain)?
I have a folder with games for the bot and in order to organize things I use different python files with different classes (/flip & /rps are in different python files). How do I access a slash cog group without the two commands being in one class? Is it possible?
the order matters, right? i am currently switching them around because it only works with the cooldown below the bridge decorator
i know, doing that
Yes, the command decorator should always be first
Is there any way to clear parameter file in message?
For example I have send_message(content = "This is your image", file = image)
And then something like edit_message(content = "Do you like it?", file = None) -> Error
try:
content = "Do you like it?", file = []
Just creating some menu and want to implement back button
discord.errors.InvalidArgument: file parameter must be a File
Pass an empty list to the attachments kwarg
Also try None if empty list doesn't work
Both doesnt work
how do I integrate my classes for select menus/buttons into cogs?
I don't actually think you can delete an attachment from a mesage
You can in the discord UI but there seems to be no way to do it via the API
you could try to pass a 1x1 image
Then is there any other way to use local images?
async def GetFile(fish):
fish_id = fish["id"]
file_name = f"{fish_id}.png"
file_path = f"images/fish/{file_name}"
file = discord.File(file_path, filename = file_name)
return fil
file = await GetFile(fish)
ah, uh, wait lmfao
I use this to load an image
here, there's a 1x1 image inside (cant send it because its too tiny to copy)
Yes you can
then how?
And then this in embed
embed.set_image(url = f"attachment://{fish_id}.png")
how do I integrate my classes for select menus/buttons into cogs?
I personally put them into a utils file somewhere else
Uh, how do I do that?
the same way you passed file=[]
What happens? Any error? Show the line how you did it
how should I do that?
Read this again
And again. And again 
make some file somewhere else
and then
import filename
and then you can just do filename.Class()
ah, missed that lol
This person also told you exactly what to do
Didnt know message accepts attachments arg
Message.edit does
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 ...
Works, thank you!
but that just unorganized as having everything in 1 file?
can you retroactively upload files to existing messages via the API??
You should always have a utils file for "help" functions IMO
I usually put all my View classes in a single file. Or you can also make a folder of such files
I'm just new to cogs and wanna move my existing code into cogs since its like 1000+ lines now lmao
Yes. The both, the files and attachments kwarg allow you to do that
thats nice, wish discord allowed that normally too
Files is always addition to existing files. Attachments is complete replacement
Why dont you make a file just like buttom.py, put here your button class and then import it to main file?
Fr haha
Ah lol
thats what i told them to do :D
but isnt there a way to integrate it normally into cogs?
Even if you can, you kind of shouldn't IMHO
But I'm also not a __Pro__grammer so maybe more experienced people know better
because this is how my example cog is setup
I dont know what cogs are but I normally import my classes to main code
Yea
but why are discord and discord.ext underlined lol
because vscode
yea duh
but somethings wrong with that then
is py-cord installed?
mind the dash
VERY important
see you back in 2m then :D
anyway, the way you do it is good, just add import utils at the top
my classes for the select menus/buttons are like 100+ lines each and having them in 1 file seems redundant
what is your vscode version?
you can add any type of helper functions into that
Maybe because he installed package while vscode is open
did you install pycord or py-cord :)
py-cord
You should have them in a seperate file so that your actual code remains readable
mhm
works fine for me lol
thats what i was trying to ask
uninstall python and pylance and reinstall it to fix it
its fine thats not what im focused on lol
so can I just make a ../cogs/utils/xyz.py then in my ../cogs/Test.py I can just import xyz then use xyz.ButtonClassExample()??
what?
^
i really dont think that's how that should work with cogs, and I feel like theres an actual proper way to do it
maybe im wrong tho
If you want to clutter your actual code files with class definitions (and find a way to do so in the first place) no one stops you
No import utils.xyz
im saying I feel like theres a proper way to organize your classes for buttons/selects/modals, etc while using cogs
Otherwise it'll look in the same folder
thats how you import from subfolders?
Imports and exports are a python thing. Not just pycord. You can do whatever you want with classes
yes but I mean is there not a proper method of using cogs and classes for your discord.ui stuff
I don't really work with subfolders but I think that's the way
or is the normal method just to import the file?
I have my uis in different files
And I just import them
you really should imo
organised and less cluttered
plus you might wanna reuse those classes in other cogs eventually
at which point its basically required anyway unless you want import hell
so another question, I made reaction roles with select menus, I have like 10 classes for each one category, is there a better way to do that?
yes
LMAO
make it one flexible class that takes arguments
Dynamic options. Indeed
Making 10 classes requires effort
its copied and pasted :)
I'm sure you a select menu with dynamic options should take more than 30 lines
in all honesty its really not that complicated
dynamic title
dynamic role selection view thing
thats.... kind of it already
hardcoding ANYTHING is a bad practice in most cases
thats fair
but im also not using any database because idk sql and the bot for the time being is meant for 1 server
no idea what that is lolw
bruh.
yea if you hardcode it that works
but if you make it dynamic its not that easy if i understand your approach right
weigh your options 
im slowly working on making the bot better lmao
currently im just moving it into cogs
how do I export the file so I can import it?
for the classes do I need to declare them as a cog in my bot.py?
with client.load_extension(extension)
no, literally just make a normal class definition
in the file itself
you really dont need to do anything in any other file other than the import statement (and then x.class() of course)
The guide has a pretty straightforward example of cogs https://guide.pycord.dev/popular-topics/cogs
Cogs, often known as modules or extensions, are used to organize commands into groups. This is useful
How would I import utils>reaction_roles.py inside commands>fun.py
not sure how to import from folders but dark said import utils.reaction_roles
no, theres absolutely nothing there todo with what im doing
This is the answer yes
You were asking how to declare cogs...?
No module named 'utils'
What is your folder structure
oh sorry i forgot to send it
How about .utils then
hm?
.utils.reaction_roles
Does it actually error though
yes
Then how about cogs.utils
then just try import ./utils/reaction_roles
/ isn't valid syntax for imports
dang
It's .
Why the . Before
it just tells you it isnt accessed yet because you arent using it
yeah it worked
Because it's a relative import
lol
no it doesnt

This is why I'd never use vscode for python
just do utils.reaction_roles and use it, trust me
It's not helpful at all
and it errors lmfao
"it errors"
screenshot the error
now show your imports
https://www.jetbrains.com/pycharm/ maybe you should start using this ;3
Are bot.py and cogs in the same folder
yes
Because if so, it should be cogs.utils.reaction_roles
this works
Nice
toothy is just trying to argue even lmfao
id recommend making it a subfolder of cogs, so that you can import it with the current import statement
It ran relative from root so it's fine
try from utils import filename
await ctx.respond("no :3", ephemeral=True, view=reaction_roles.SelectMenu())```
this returns `AttributeError: module 'cogs.utils.reaction_roles' has no attribute 'SelectMenu'`
even though the SelectMenu class is inside reaction_roles.py
I just imported discord, and pasted my classes which i assume is wrong but
@patent knoll ^
@worn void
hm
i could only imagine there's still something weird with your import because that should work if the file got imported
that's actually just really easy to do lmfao
i thought i would have to change stuff to use cogs
What's your file structure
why did no one suggest from utils import reaction_roles 
good question
i did
no module named utils
oh must have missed it then lol
i changed it to cogs.utils
and what about from .utils import reaction_roles
ah right. cogs are loaded at the bot level, not the cog level
weird thing even i used to encounter
iirc, the imports should be as per the main file, even in cogs
do you want to make util functions in main file, but want to use them in cogs/other files?
??
yes
best to make it at the same level as the bot.py file
i wouldnt put them in the same folder as my cogs
config.py >
special = [1, 2 , 3 , 4]
string = "the quick brown fox.."
..
cogs > utils > reaction_roles.py >
import config
class TestClass(discord.ui):
..
print(config.string)
..
like that?
yea
yes that works
kk
I don't
import config
dotenv_path = Path('token.env')
load_dotenv(dotenv_path=dotenv_path)
token = os.getenv(config.token)
not quite what i expected
I can alternate between tokens as well
that's why it pulls from the config
I mean you can, vscode just sucks
i dont think that's vscode but ok
even if I add it with notepad and run the code it wont work lmao
im using cmd to run the bot anyways
why am i always getting this error on startup? I have installed pycord correctly and I do not have a running version of dpy installed
?tag replit-install
Installing Pycord with Replit (only use replit as a last resort) - pycord-replit-install.md
also btw i will not use replit for hosting im just using it to code it for now
thanks for the response
i did what the script said but this still shows up
Why? ;3
it's convenient
is something still installed? Sometimes you even have to create a new Replit project to get it working
Ignoring exception in on_connect
Traceback (most recent call last):
File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 378, in _run_event
await coro(*args, **kwargs)
File "/home/container/.local/lib/python3.10/site-packages/discord/bot.py", line 1164, in on_connect
await self.sync_commands()
File "/home/container/.local/lib/python3.10/site-packages/discord/bot.py", line 719, in sync_commands
registered_commands = await self.register_commands(
File "/home/container/.local/lib/python3.10/site-packages/discord/bot.py", line 599, in register_commands
registered = await register("bulk", data, _log=False)
File "/home/container/.local/lib/python3.10/site-packages/discord/http.py", line 371, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In 65: Application command names must be unique
How do i fix this? :c
what's the maximum amount of commands a SlashCommandGroup can have?
25 sub command groups and each sub command groups can have 25 sub commands
btw how can i see the line of my not unique command ?
You cannot. Try listing them.
BROOOOOOOOOOOO
65 is the index so it would be your 66th command
That helped me alot
Also bot.event included?
no, only top-level slash commands, user commands, and message commands
.
If you are referring to text-based commands, no
What change in pycord3?
Anything
General
Fixed

basically everything for the sake of modernization, future implementation, and speed basically.
Okey, pycord3 better then py-cord 2.4.1, yes?
no, because v3 is still in alpha state
and incomplete
Thanks
How can an ID be changed to a mention or any other information?
ctx.author.id
Reversed
???
most objects have a mention attribute that does it for you
<@{ctx.author.id}> or that ^
ID as a number:
586562858595385356
yes
You can just use ctx.author.mention for example
do you mean you have an ID, and want to get a User/Member object?
Can I just do this?
ID = 586562858595385356
f"<@{ID}>"
Yes, if you want to mention them only
if you want the object, use guild.get_member(id)
or bot.get_user(id)
or if your bot doesn't share any servers with the user, you will have to use bot.fetch_user
https://docs.pycord.dev/en/master/api/clients.html#discord.Bot.fetch_user
Thank you โค๏ธ
WHY THE COGs ARE BROKEN
Why? Because things break sometimes and have to be fixed... But it takes time.
There are several issues with them but what's your issue?
every time i use the command cogs the command begin un responding or un registered at all
an if i used it it will just "didn't respond" then after some moments i get 404 (unknown interaction) in the console :\
bro its a say command ;-;
show code
oko
Then it could be your command being broken, not necessarily a cog.
Commands on the inside of cogs should just work fine if being loaded properly.
How is the cog loaded
.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)?
?
are you running many instances of your bot
and about the replit (also tried to work on local) same issue
hmm synced globally or synced to a debug guild?
If you synced globally it can take a bit.
and the bot.sync_commands (don't remember that fr fr) make the whole commands that in the main file die (also didn'tknow WHY)

just send link to your entire repl, I'm not asking 50 questions just to find what I want.
wait
no I mean do I have a choice
nope ๐คทโโ๏ธ
We're waiting ๐ตโ๐ซ
and they are gone
senior python developer and still doesn't know python conventions.
:\
(we are waiting for you to show us your project so we may be able to help you)
bruh bro it just one command lol
Yes I know, but the issue can lie somewhere completely else, trust me I once had my bot malfunction completely due to 1 small issue somewhere else.
While I was just trying to reorganize my bot- I could not put my cog loader above my help command for no reason at all.

what
wait.. where should the cog loader to be ๐คจ
not on ready or connect
Do you use Replit?
for now
bot.say? what?
So it does get loaded and the command does get executed when you run it? Can you try adding a print statement under the await ctx.respond just to make sure it actually gets executed.
And its actually not responding.
tf are you doing
ikik but this is a broken command idc
bot.say is like v0 and like removed years ago
๐คก
that definitely produces a runtime error
(the autocomplete who's type that command)

.
im using separate files for my classes and importing them into my cogs,
how do I call client? do I define it again inside the class file?
Why do you need the bot object there?
I'm using client.get_user() and client.get_channel()
Interaction has a client attribute
what is it?
thanks
also
im getting a discord.errors.ExtensionFailed: Extension 'cogs.commands.admin' raised an error: TypeError: issubclass() arg 1 must be a class error when I try to register the cog
nvm i found it
what am I doing wrong here?
await ctx.guild.create_auto_moderation_rule(name="Words", reason="Automod", enabled=True, event_type=discord.AutoModEventType.message_send, trigger_type=discord.AutoModTriggerType.keyword_preset, trigger_metadata=discord.AutoModTriggerMetadata(presets=discord.AutoModKeywordPresetType["profanity", "sexual_content", "slurs"]), actions=[discord.AutoModAction(discord.AutoModActionType.block_message, metadata)])```
I have read the docs about this multiple times
can anyone help? i wanna know how you add choices for args in a slash command
Example: ```py
from discord import option
@client.command()
async def example(ctx, example:discord.Option(choices=["Example1", "Example2"]):
if example in ["Example1"]:
await ctx.respond("You chose example 1")
if example in ["Example2"]:
await ctx.respond("You chose example 2")```
if example == "Example1" 
Here's the slash options example.
@signal topaz see this
.idw
Saying it doesn't work or asking what's wrong with this code is not helpful for yourself or others.
Describe what you expect and/or tried (with your code), and what isn't going right.
Please provide any errors you get for optimal assistance.
got it
i dont understand why im getting a return of both discord.Interaction and discord.webhook.async_.WebhookMessage for the exact same line of code in two different places. the main thing im trying to do is edit the message and it just started telling me that when i run it a certain way that "interaction has no attribute 'edit'" but why is an interaction being returned from an interaction response?
interaction.response.send_message doesnโt return the message object. (discord limitation)
.rtfm interaction.edit_original_response
use that to edit the msg sent
i was using ApplicationContext.respond(...)
does that change anything?
you can use ctx.edit iirc
.rtfm applicationcontext.edit
yep
thanks
np
how do i properly make an @Option parameter
I'm too stupid to figure it out rn lol
are you trying to make a slash cmd option using the @discord.option decorator?
yea
I did it exactly like this with the options=[] argument and it worked perfectly
ah weird
previously, it never worked when i did input_type=str but now it does
Yea okay but now if i do input_type=discord.Member it wont actually suggest the latest members in chat
Do you have intents?
if i do
...options=[
discord.Option(discord.Member, name="name", description=description="desc"
]
it works just fine. However, if you just use the @option decorator, you cant use the positional first argument, and using input_type=discord.Member just doesnt work, even in above code
Do you have member intents?
why would I need them?
it works just fine if i do it like in the above codeblock
Oh
its just a weird case of discord.Option() working differently from the decorator version
option(discord.Member, )
it'd save me like 100 lines of code total when using the decorator so i want to, but i just cant get it to work
@option(discord.Member,...) doesnt work
here, 1s, ill show you
is it capital or lowercase option
if i use the lowercase option, this happens
and if i use @Option, its "not callable"
Here's the slash options example.
never heard of Union, let me see
You dont really need it
Not really
Currently my bigger problem is that the options dont even update
This should give a user option with the automatic userlist, and the same for the channel option, right?
Can you show the async def line?
Its working fine for me
why? i wanna switch from options=[] to decorator because its cleaner imo
yea it works now, idk what kind of aids discord just had to not update the command (and it still worked??? with the old args?)
?
just define it as regular function args
what
async def command(self, ctx, option1: discord.Option(...), option2: discord.Option(...):```
is this not good
What is brief?
well i wanna do it the right and clean waya
help command
i'm still just not quite sure how what gets put into the options gets put into the actual function
is it just positional? as in, e.g. here, the user argument is the first positional argument and so on?
What is with the discord.commands Option one?
yes it's positional
?
So e.g.
if i had two nonrequired arguments, and only filled the latter one, it'd break (if i dont somehow handle it in the function)
from discord.commands import Option
kwarg what

you can set default inside option
kwarg the options
e.g. the user option gets passed as user=x
ahh
yeah
yea its a bit annoying because the @option thing is just **kwargs so i get zero suggestions on what other options there are lolw
yes i am reading the docs too (sometimes) but im lazy
i mean the docs do tell you all possible options
i still dont quite get why the decorator is @option but if you do options=[] its Option
yes
yikes
that's the first way i learnt how to do it
it's because Option is an actual object, while @option is a function that adds the Option object to the command
look i just wanna make clean code that most people would say "this is the way" to
i havent changed how i am doing options just yet so i am taking suggestions :)
is it possible to add emojis in choices?
@option is fine, but i'd personally do it as typehints py async def command( self, ctx, user: discord.Option(discord.Member, "desc"), channel: discord.Option(discord.TextChannel, "channel") ):
choices can have unicode emoji yes
not in autocomplete though
that works? damn that kind of looks like some weird hacky way lmao
unicode?
oh
at least for me and everyone in this channel i've recommended it to, it works
ultimately as long as you have it working as intended then it's fine
how to edit messages? like lets say user filled option in a select menu now i need to edit message
well
edit that message while removing the select menu, yea something like that
in the callback, use interaction.response.edit_message
to remove it, you want view=None
thx
hm, alright, i noticed something
somehow, the "members" in the async def basically overrides the @option
there is no users option shown, only members
that is legacy code
i am so scared of touching that
it doesn't do much
its one of those things that if you remove them some powerplant in china will explode for some reason
in prefix commands, it means that all input in the message is accepted
without it, each arg would be parsed by spaces
yea, i am converting a bridge bot to a slash-only bot, thats why its there
okay, i did, but unless my discord cache is deceiving me, it still does the same thing
maybe in the decorator it's name=users, input_type=str
....though you could just rename the variable
no, the problem is that it completely overrides the option
its as if the @option didnt exist, and it only constructs the option out of the async def
eh...
okay i am certainly doing something wrong, as even if i remove everything but self, ctx from the function it still wont work (now NO options show lmao)
do i even need discord.Option here?
oh yea i do mb
well i guess that is the only way then, bruhw
that's just the most reliable way that i know of
aha
new knowledge
It does work if the option and the argument inside the function definition are called the exact same
didnt expect that
well that solved that
and now final question
there isn't a way to make multiple user selections without making multiple options right
i was probably wrong about positional then LOL
yeah discord doesn't let you
you probably can in select menus tho
that really sucks, that forces us to accept members as str and then pull the mentions from it
pycord works in mysterious ways
we implemented utils.raw_mentions to convert a string of mentions into a list of IDs
so you can use that if you want
nice
typehinting inside of the function definition would only make it easier for me to code, right?
like, i already define the input types in the option decorator so thats dealt with
Like inside the async def, the typehinting is basically useless, no?
i do know how to code but i really have no idea about good coding practices like that ngl
in the example it's the other way, no type inside the decorator but you typehint in def
but it does the same, no?
You dont need the bool and None stuff
so i can better use the empty line-space of the @ option instead of cluttering the definition
yea i was gonna change it to default=None in the decorator
Like this looks nice imo
only thing i miss out on like that are the IDE suggestions
Why do I get this when my only command with more than 1 option looks like this?
Why is default False?
because that is the default if the option isn't used
i know i could leave out the required=False when i use default, but that doesnt change the error i'm getting
I'm quite confused as to what causes this
or is discord made because of this somehow?
i commented everything but that command, so somehow, that is the culprit
.... and somehow setting border and server-avatar to false inside the function works, why?
#1102262376084021309
Is there any way to send a string as a voice message?
bots currently can't send voice messages (though regardless, you'd have to do the TTS conversion yourself)
Is possible to make all the slash commands in a SlashCommandGroup have the same check at once ?
Can you elaborate what you are trying to do?
Same topic here, but how exactly do I define a slashcommand group in cogs?
Here's the slash cog groups example.
thats quite a bit different from the non-cogs example wow
VSC complains about the variable never being used lol
discord.ui.Modal
discord.ui.Modal.add_item
discord.ui.Modal.callback
discord.ui.Modal.children
discord.ui.Modal.custom_id
discord.ui.Modal.on_error
discord.ui.Modal.on_timeout
discord.ui.Modal.remove_item
discord.ui.Modal.stop
discord.ui.Modal.title
discord.ui.Modal.to_components
discord.ui.Modal.to_dict
discord.ui.Modal.wait
discord.InteractionType.modal_submit
discord.ApplicationContext.send_modal
discord.InteractionResponse.send_modal
discord.InteractionResponseType.modal
discord.ext.bridge.BridgeApplicationContext.send_modal
Sorry if dumb ?, but how to respond to send a modal from a UI Button interaction when reaction has already been responded to?
not possible. discord limitation
if you want to send a message and a modal, send the modal as the response and message as the followup
thanks always goat ^-^
lol np
if ctx.guild.fetch_ban(user):
This returns either true or false, right?
that returns the ban entry
so basically if it returns one then they are banned, else they are not?
it'll only enter the if if there is a ban for that user
alright, thanks
I'm so sorry but how, it doesnt do thing
okay, how do i check if a forum has a specific tag?
How the hell do I mention a subcommand?
the same way you mention a normal command
Nope.
yes
I tried it
I mean by like the .mention Attribute
I want's to make a game bot, and the game run with many different command. And I want make sure these command are only available in specific channel.
i really have no idea, i manually printed every element of an existing automod rule and it's literally the exact same, i have no idea what i'm doing wrong
please tell me there is some way to not make it as hardcore painful as it is
in a cog file how do I use client? do I use self.bot or self? I'm trying to use client.get_user() in a command
self.bot
self.bot as you defined it in the init
should look ab something like this
๐ ty
uh i created 2 select menus in one message, but if i select an option in any one no matter what i do and how fast i select an option in the remaining one it will say interaction failed and not fetch data based upon user selection
i have set callback for both select menus in one callback function too
please create a separate post on this.
you're telling me I cannot use the normal .mention attribute of the subcommand.name object?

you are taking too long ( more than 3 seconds) to respond. Try deferring at the start of your slash command.
I tried this;
for name, cog in bot.cogs.items():
commands = cog.get_commands()
if commands:
command_mentions = []
for c in commands:
if isinstance(c, SlashCommandGroup):
for subcommand in c.subcommands:
bot.get_application_command("logging setup").mention
command_mentions.append(bot.get_application_command(subcommand.name).mention)
And it kept telling me NoneType Object has no attribute "mention"
So this is really confusing at this point
I can mention a normal command... but not a CommandGroup using the mention attribute....
WHy???
you arent getting the command correctly
then how am I supposed to get it? :I
these are the two outputs I got of
print(subcommand.name)
# and
print(bot.get_application_command(subcommand.name))
do you need a name or id for it?
wait a minute...
alright
so I tried subcommand itself because obviously subcommand returns logging setup (which is the entire command with parent and subcommand itself)
what's the discord.Member equivalent for a channel for input validation on a slash command?
wdym for a channel
but if I try to mention it it asks me for a name attribute
member.channel?
what? no
if you want the channel use ctx.channel lol
no i want to take a channel as an input for a slash command
discord.TextChannel
thanks
discord.TextChannel or discord.VoiceChannel
or Union[discord.TextChannel, discord.VoiceChannel] for both i think
forum channel, news channel.
https://docs.pycord.dev/en/master/api/models.html# You can see anything you need at the right side
or for more specific, use the channel_types kwarg
i posted, can you check it?
Yeah I dont understand, if I try printing it, it works just fine but when I try mentioning it, it says no fuck you Vox, I find a NoneType only.
it makes absolutely no sense, I print the subcommand.name it works fine, I try mentioning that and it says "NoneType"
???
uhm... so apparently when I try subcommand.id
it gives me None...
wtf
I am trying to do a hybrid cache (some in memory and some in disk), I saw somewhere in the past that you can change how the cache store and get information, but I cant seem to find it in the doc. Do you know where that info is ?
Yes obviously; but when I do subcommand.id it gives me None
While if I do subcommand.name it just gives me the name.
qualified_id iirc
anyone
The what.
should I use cogs
it's your choice
I have like vanity bots which run the same code but have different pfps etc, would i be able to have only one file for each cog then each bot can import that
use subcommand.mention directly
I tried that... It returns to me a NoneType if you look further above in chat.
what version of pycord are you on
can you show the full code you're using to test this
Sooo this is why I am really confused
This is the part... Which I can show you at the moment (as I am not at my computer at the moment) I'll show you more later if needed.
you could just change the last line to command_mentions.append(subcommand.mention) no?
but anyway, if mention is still giving you a None then there's something significantly wrong because it would mean the command group doesn't have an ID
(or you're on something older like 2.2 but eh
)
where is this code? Maybe it was before on_ready?
But I'll see if that works
(spoiler: get_application_command(subcommand.name) is a guaranteed fail because you should be using qualified_name)
The ... Why what is-
(docs)
cmd.name is different from cmd.qualified_name
Same for id
:D?
Right-
how many cogs is too many? when will performance be effected?
like 10k?
apparently the code i sent just cant be made prettier, its just destined to be horrible
Should I make my cogs be on separate files??
you can if you want
each individual cog should be in their own file by convention.
ok
you can make cogs in one file?
Does discord.TextChannel contain announcement channels?
this this fixed it thank you very much
how do i call a function that i defined in a cog from another file? Or should i not do that and keep just the basic commands in there?
you can just import it?
cogs are basically just classes so I suppose you can just class.function
"from xxx import xxx"
That is basic python stuff ;3
How to wait for a button press from a view i already have?
if it's defined in the cog, use bot.get_cog(name)
where name is the class name
is that better than importing it?
depends
if you import it then you've created a new instance of the cog/file
while get_cog will access the existing instance, and thus any attributes that have been set during it
view.wait
well, kind of
really you should be using callbacks
i am using callbacks, but i am unsure how to then go on with it in my main function
idk if im explaining it right im tired lol
But basically, if i press a button, i want it to just return, and if i press another button, it should do smth
and i also have the issue that somehow having 2 @discord.ui.button decorators makes only one work
https://docs.pycord.dev/en/master/api/ui_kit.html#discord.ui.View.wait
view.wait will wait until the specified view stops; if it timed out then it'll return True, otherwise False if it stopped some other way