#Basic Pycord Help (Quick Questions Only)
1 messages · Page 66 of 1
channel = discord.utils.get(message.guild.text_channels, id=123)
thanks, done it.
If anyone is ever interested:
async def category_autocomplete(ctx: discord.AutocompleteContext):
return [cat for cat, cog in bot.cogs.items() if cog.get_commands()]
@bot.slash_command(name="help", description="Displays the help menu.")
@option("category", description="Choose a category.", autocomplete=category_autocomplete, required=False, default=None)
async def help(ctx: discord.ApplicationContext, category: str,):
# Custom code from here;
Si that client.get_channel doesnt work then?
not everytime
ok, try fetch_channel
So just fetch_channel(id)?
await fetch_channel
Nope
can you show the code?
@bot.event
async def on_message(message):
await client.fetch_channel(1029735370969055293)
print(f'Message from {message.author}: {message.content}')
await channel.send(f'Message from {message.author}: {message.content}')
where is the channel =?
Oh. I thought i had to remove it cuz of the await bit
But after adding it is still has an error.
Where client defined
Where did you define it
Because you're clearly using an instance called bot not client
can anyone help me with persistent views? i made a thread about it but i havent got much of a response
What's the thread
Select menu persistent view
Above the bot.event
Was something like client = discord.client then some stuff in brackets
Why do you have both bot and client defined then?
They are both different?
?
Ive always had bot defined, but only defined client last night, but they are both different aren't they?
oh man...
Why do you need both of them?
There is literally no reason to have both, it will only break things
client is useless since it was not initialized/connected to gateway/there's probably a better term for this.
This is like the third time I tell you this, learn Python OOP before using pycord
Stick to #help-rules or find another server
bot = commands.Bot(command_prefix=">", intents=intents)
client = discord.Client(activity=discord.Game(name='Lightbulb MC'))
Ok
What would cause ctx.channel to be a PartialMessageable instead of a channel?
ctx as in?
ApplicationContext
.rtfm interaction.channel
Note that due to a Discord limitation, DM channels are not resolved since there is
no data to complete them. These are :class:PartialMessageableinstead.
It’s not a DM channel. Guild name shows up in my error log, and the command itself has commands.guild_only
The channel could be missing from the cache
How would that happen?
Well if no activity happened in the channel for a long time, then the library can remove the channel from the cache to utilise the memory for other stuff
Or it could be random, in not sure
How do I pass arguments from a slash command into a ui view, like a select menu?
Cool, thank you. I added a fallback
Does bot.fetch_channel automatically place the fetched channel in the cache?
You should never rely on anything being cached.
Just get things from the cache, if it returns None, use the API to fetch it instead
I would generally subclass View and pass my stuff in the init
For passing options to select menus, i will subclass ui.Select and accept them in the init
ok ill try that, thanks
iirc, no
Partial messageable is enough for sending messages if that's what you want to do
Nah, I need it for checking permissions
ah yes then you would need the channel object
any recommendations for a VPS that allows you to run a Lavalink server and discord bot together?
hi
so i cannot load cogs
i had coded this bot like when discord py existed and changed it to pycord but idk how to fix this error
and this is how i load the cog inside the files
tbh any vps with over 2gb of ram can handle this easily
i think thats probably a lot too
it more of who can run java and python on the same VPS
currently on pebble host and they dont currently support it on their python discord bot hosting plan
each playing track takes smth like 350KBs as per lavaplayer docs. and my avg discord bots take around 100MB of memory.
i did that too
await client.load_extension() but it gave some error out of function
uninstall dpy
?tag replit
Installing Pycord with Replit (only use replit as a last resort) - pycord-replit-install.md
no see
my bto is comign online n all
but only the cogs isnt loading, i put a commmand in main.py and it worked but the other commands in cogs dont
i did the uninstalling discordpy and other things already
python telling you to await load_extension is a pure indication that dpy wasnt uninstalled. since py-cord is a fork of dpy, it has a lot of shared code
thats why it was working earlier
yea like 239448849 months ago
see this on how to do it correctly
leme just do it gain it might be diff rn
yea thanks
um
my .replit is completely different from the other .replit
nvm nvm
discord.py...
ok i installed py-cord in a new repl cause the other repl was an older version
I would not use repl 
i am on a chrome book right now :prau
You can install Linux and VS Code
i know
Nice. Did that fix stuff?
Oh btw vscode online is a better ide than replit lol
How can I deselect the users choice in a select menu? I'm creating a Ticket system with a select menu and after the user selects a topic a modal opens. Now I want that the bot deselect the users choice before the modal opens
i believe you would need to edit the message with a fresh instance of the select menu
ok, I will try it
that worked, thanks
cool
@bot.command(guild_ids = [996922553266360360])
async def unsubscribe_the_server(ctx,
guild_id: discord.Option(int, "Description", default = discord.Message.guild.id)):```
``` guild_id: discord.Option(int, "Description", default = discord.Message.guild.id)):
AttributeError: 'member_descriptor' object has no attribute 'id'```
What's the correct way to get the guild id?
I found a way around, but i'd like to know if it's still possible to do this in this manner (seems like it isn't tho)
slash command parameters are meant to be static, not dynamic
Using discord.on_thread_create how can I determine if it's a forum thread or a channel thread? And then how can I tell which forum it's come from?
.rtfm thread.parent
Thanks, also is on_thread_remove when a thread is closed?
Default it to None and in your code do guild_id = guild_id or ctx.guild.id
Easiest and cleanest way to do it
yup that's what I did x) thanks
Haha np
that'd be on_thread_update
Thanks, one last thing, how would I get my bot to close/delete a thread?
Anyone has an idea how I can do that commands can't executed in Text-in-voice anymore? Only in normal text channels
.rtfm discord.Thread
discord.Thread
discord.Thread.add_user
discord.Thread.applied_tags
discord.Thread.archive
discord.Thread.archive_timestamp
discord.Thread.archived
discord.Thread.auto_archive_duration
discord.Thread.can_send
discord.Thread.category
discord.Thread.category_id
discord.Thread.created_at
discord.Thread.delete
discord.Thread.delete_messages
discord.Thread.edit
discord.Thread.fetch_members
discord.Thread.fetch_message
discord.Thread.flags
discord.Thread.get_partial_message
discord.Thread.guild
discord.Thread.history
Read the docs
.rtfm discord.Thread
discord.Thread
discord.Thread.add_user
discord.Thread.applied_tags
discord.Thread.archive
discord.Thread.archive_timestamp
discord.Thread.archived
discord.Thread.auto_archive_duration
discord.Thread.can_send
discord.Thread.category
discord.Thread.category_id
discord.Thread.created_at
discord.Thread.delete
discord.Thread.delete_messages
discord.Thread.edit
discord.Thread.fetch_members
discord.Thread.fetch_message
discord.Thread.flags
discord.Thread.get_partial_message
discord.Thread.guild
discord.Thread.history
Is there a way to reload a slash command cog without restarting the bot? I have 250 slash commands and every restart = rate limit for the entire day.
I wanna update the code in commands without restarting
you can disable auto_sync_commands if you did not update the actual command structure.
and you can restart just fine without ratelimits
So every restart it won't delete/readd the slash command? How would I do that?
bot.auto_sync_commands = False
Alright thank you 🙏
or just in the constructor like so bot = discord.Bot(..., auto_sync_commands = False)
client = commands.Bot(command_prefix=commands.when_mentioned_or(db["prefix"]),case_insensitive=True,intents=intents, auto_sync_commands = False)```
Can I do this?
kk
Hey, I want to create select menu. Let say I have json file and want to create option for each key. Anyone could hoke me up with some guide or doc link how to achieve that?
- how to I "call" json data into
class MyView(discord.ui.View):
mmm dunno if you can pass data into a view, but I'll tell you what I do: I just start a view, and when the view gets interacted with, do a self.stop() (or not if the view needs to continue being interacted with) and return the state of the view, then do whatever with the data in the view calling function
subclass ui.View and ui.Select
pass options list to view init. in there create a Select menu and pass this list to the options parameter
use view.add_item to add it
Will try Thanks
When i use channel_select, the select dropdown does not include all channels (cuts off at 15 channels). Is there any way to list all text channels (30+) in a server or remove certain channels if there is a max limit?
hey i get this error when trying to view the "exempt_roles" property of an "AutoModRule"
I want to lock a thread if someone presses the archive button on it. I've attached my code below but I get an error saying the post is already archived. Is there any way of locking a thread without "archiving" it?
Code:
@bot.event
async def on_thread_update(before, after):
if not before.archived and after.archived:
await after.archive(locked=True)
I changed the last line to await after.edit and it still doesn't work.
This is the error I was receiving:
Ignoring exception in on_thread_update
Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/discord/client.py", line 377, in _run_event
await coro(*args, **kwargs)
File "main.py", line 1904, in on_thread_update
await after.edit(locked=True)
File "/usr/local/lib/python3.8/dist-packages/discord/threads.py", line 677, in edit
data = await self._state.http.edit_channel(self.id, **payload, reason=reason)
File "/usr/local/lib/python3.8/dist-packages/discord/http.py", line 366, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50083): Thread is archived
I temporarily go around it by unarchiving the post, then locking it. Is there a cleaner was of doing that?
"Thread is archived"..
You're literally checking if it's archived and you're trying to archive it again
It should display 25 but the user can type and search other channels not displayed.
Is it possible to generate different choices for a slash command option depending on the user who is going to be invoking that command?
Hypothetical usecase:
For a bot that manages a card game, a user has to play a hand by picking a card from their deck. The play slash command let's user "pick" a card from their existing deck.
The pick part is where custom choices would be generated depending upon the user
maybe if you reload the cog? but Im not sure
Choices can not be altered after runtime, for that to be possible you would have to re-register the command every time someone tried to use it. Your best bet is autocomplete.
Ah okay, thanks
you also could use a select menu for that but they have a limit of 25
Oh right, makes more sense
https://cdn.discordapp.com/attachments/1043576797423468574/__1088273049398296628__/diffuse.png
what type of object ID is the number that second long digit number?
first one Ik is channel, but I have no idea what the other one is
I tried to check for message ID, it didn't match up, guild ID not
for what do you need this?
recovering deleted images for my server
attachment ID
Isn´t discord auto deleting files after some time?
I saw it with images
not sure. My guess is no
maybe if the message with the attachment is deleted?
I'm pretty sure attachments are deleted after 1 month of not being accessed or something, not sure though
I mean I'm able to access attachments from like 4 years ago lol.
After reading a bit it seems like attachments do stay as long as the message containing them isn't deleted
Is it possible to change the logging of the botclient to a specific file?
What is "the logging of the botclient"?
yes i believe
Actually it is a bit broader. How can I specify the log file in pycord?
Earlier I used the logging module and everything would just pile up in one file. So now I write certain parts to a certain file. But that is my own code, I am not sure how to specify the log file in pycord. Or just the logger
Pycord logs errors and debug information via the logging python module. It is strongly recommended that the logging module is configured, as no errors or warnings will be output if it is not set up...
Thanks!
This line is what i was looking for:
logger = logging.getLogger('discord')
So that reads basically out as: get the logger of the module 'discord'
Never used that func before
more like "get the logger object which has the name 'discord' "
Loggers have the following attributes and methods. Note that Loggers should NEVER be instantiated directly, but always through the module-level function logging.getLogger(name). Multiple calls to getLogger() with the same name will always return a reference to the same Logger object.
many modules can use a logger with the same name
Hey, Im trying to use this code inside of slash command. Select menu sending as respond, but cant figure out how to get user select response. Thanks for help
view = discord.ui.View()
options = []
for key, values in from_station.items():
options.append(discord.SelectOption(label = key))
select = discord.ui.Select(placeholder="Select a station", options=options, max_values = 1, min_values= 1)
view.add_item(select)
message = await ctx.respond('Select a station', view = view)```
What do you mean by "get user select response"?
Oki thanks
Something like this
async def select_callback(self, select, interaction): # the function called when the user is done selecting options
await interaction.response.send_message(f"Awesome! I like {select.values[0]} too!")```
But you don't have a user select anywhere in that code
If all you want is to define a callback on your select you can do
select.select_callback = my_callback_method
Or just use subclassing, since that's way easier
Yea read the docs, but sometimes you can get lost in the jungle and a little guidance in the right derection helps alot. Appreciated!
Can you link me up with some guide 🙏
Guide for what?
How to fix it properly
There isn't a guide for everything
It's easy, just define a method and set it to the select_callback attribute of your select instance
view = discord.ui.View()
options = []
for key, values in from_station.items():
options.append(discord.SelectOption(label = key))
select = discord.ui.Select(placeholder="Select a station", options=options, max_values = 1, min_values= 1)
select.callback = select_callback
view.add_item(select)
message = await ctx.respond('Select a station', view = view)```
```python
async def select_callback(select: discord.ui.Select, interaction: discord.Interaction):
value = select.values[0]
await interaction.response.send_message(f"You selected {value}.")```
Is it something similiar to this? Or Its completely wrong
.tias
Yeah its not working
, thats why im asking if im on correct or wrong track
I can't help you if all you have is "its not working"
Got it, just in case someone searching too.
options = []
for key, values in from_station.items():
options.append(discord.SelectOption(label = key))
select = discord.ui.Select(placeholder="Select a station", options=options, max_values = 1, min_values= 1)
async def my_callback(interaction):
#await interaction.response.send_message(f'You selected {interaction.data["values"][0]}')
await interaction.channel.send(f'You selected {interaction.data["values"][0]}')
select.callback = my_callback
view = discord.ui.View(timeout=20)
view.add_item(select)
await ctx.respond('Found multiple stations', view = view, ephemeral=True)```
In case someone searching too 😉
Is it possible to use slash commands as a reply to someone?
Like: I reply to a message with /remindme 1 and the bot sets a reminder for 1 hour with a link to that message. I already had this logic done with the normal commands but I can't seem to get it done with slash commands. It says the application did not respond even though I respond with the code
@discord.slash_command()
async def remindme(self, ctx, days: int, hours: int, minutes: int):
# It's basically the same idea as the reminder command, but instead it works when you reply to a message.
if not ctx.message.reference:
await ctx.respond("In order to use this command, you need to reply to a message.")
return
total_seconds: float = days * 86400 + hours * 3600 + minutes * 60
current_timestamp = datetime.now().timestamp()
final_timestamp = current_timestamp + total_seconds
async with ReminderManager() as rm:
await rm.create_reminder(ctx.author.id, final_timestamp, ctx.message.reference.jump_url)
await self.get_reminders()
await ctx.respond("Reminder added!")
slash cmds do not have ctx.message
Ah
what you could do is, create a message command (context menu), and send a modal to get the time input
or you could accept the message link as a parameter
So just have a command with a prefix and use a modal for the time instead of typing it in
Good idea
command with a prefix
uh no? i meant the cmds you get when you right click a message on discord
.rtfm message_command
.rtfm tasks.loop
discord.ext.tasks.loop
discord.ext.tasks.Loop
discord.ext.tasks.Loop.add_exception_type
discord.ext.tasks.Loop.after_loop
discord.ext.tasks.Loop.before_loop
discord.ext.tasks.Loop.cancel
discord.ext.tasks.Loop.change_interval
discord.ext.tasks.Loop.clear_exception_types
discord.ext.tasks.Loop.current_loop
discord.ext.tasks.Loop.error
discord.ext.tasks.Loop.failed
discord.ext.tasks.Loop.get_task
discord.ext.tasks.Loop.hours
discord.ext.tasks.Loop.is_being_cancelled
discord.ext.tasks.Loop.is_running
discord.ext.tasks.Loop.minutes
discord.ext.tasks.Loop.next_iteration
discord.ext.tasks.Loop.remove_exception_type
discord.ext.tasks.Loop.restart
discord.ext.tasks.Loop.seconds
is there a way to force integer inputs in the modals?
Not right now, Discord does not support it (yet)
The best you can do is validate it on submission and send the user a message if they didn't enter a valid number.
Alrighty, thanks
Does someone know how these apps are called? I mean the Apps you see when you click a a user’s profile or a message
context menu commands
Ah thx
is there an easy way to disable slash commands based on user roles?
with has_role you could check if the user would have a role
Yeah but that doesn’t actually hide the command or like show it as disabled from the list, no?
you can only hide the command with defaul_permissions
How do i require a channel in an command(like !channel #channel) channel:discord.channel doesn’t work
Quick database question, Should i make multiple collections and store it in one database or make seperate databases for each type of data (such as guild data, user data, reports etc). [Mongo DB]
discord.TextChannel
Ah thanks i user discord.channel the whole time and it didn’t worked
You should only have one database with multiple collections for each type of data
Is there an alternative for @commands.is_owner() ? I almost have got everything on import discord, I was trying to refrain from using discord.ext
not really, why?
all checks are a part of the extension
you could just do from discord.ext.commands import is_owner
How can I edit this view/message without triggering the ratelimit?
await interaction.response.send_message(embed=embed, view=self.view)```
You can't edit a message without being rate limited
That's the whole point of a rate limit
That means if I add a button here to the view then it triggers the ratelimit?
messageembed = await interaction.response.send_message(embed=embed, view=self.view)
self.view.add_item(SpeedAgain(self.bot, self.spotdaten))
messageembed.edit_original_response(embed=embed, view=self.view)```
No? Adding one button won't get you rate limited.
If you edit a message more than 5 times every 5 seconds, yes, you will be rate limited
Okay I have a view with a select menu and when I select something the view is edited and another select menu is added. I can put a maximum of 5 select menus in the view. Then I conclude that I should not have any problems with this?
.tias
So it works. But the thoughts I have is, if a lot of users do this at the same time, can I get problems?
If a lot of users are causing the same message to be edited, yes, you will have to limit that. If every user has their own message, then no.
Okay every user has his own message, then I should not have any problems
Discord itself says the following:
Interaction endpoints are not bound to the bot's Global Rate Limit.
Do these two things count then or?
interaction.response.send_message
interaction.channel.send
Editing and sending messages are not part of interaction endpoints
Okay then are the two things both part for the ratelimit correct?
And the global rate limit has nothing to do with that either, each endpoint has its own rate limit on top of the global rate limit
Just like the docs say, the global rate limit is 50 requests per second
But the message edit endpoint has a 5/5s rate limit
Does it make a difference in the two variants when I send the message?
Related to the ratelimit
interaction.response.send_message
interaction.channel.send
db_ids = []
new_ids = [guild_id for guild_id in bot_ids if guild_id not in db_ids]
InsertIds = "INSERT INTO serverinfo (ServerID) VALUES (%s)"
bot_ids = ({new_ids})
cursor.execute(InsertIds, new_ids)
cursor.execute(InsertIds)
Connection.commit()
Connection.close()```
Whats wrong with this code? I am trying to have it get the server ids of the servers the bot is in, then compare it to the one's in the database & add the missing ones.
new_ids = [guild_id for guild_id in bot_ids if guild_id not in db_ids]
^^^^^^^
UnboundLocalError: cannot access local variable 'bot_ids' where it is not associated with a value
(I understand the error, but even if was to fix it i am struggling to do this)
Why do you have two %s?
And why on earth are you using different naming conventions for your variables? Why not just stick to one?
Ignore that, To be removed
And what is this line supposed to do?
bot_ids = ({new_ids})
Ignore it? You asked what's wrong with your code, that's one of them
Edited, And the line was supposed to store the bot ids into a variable, not sure what i exactly was doing there
The line doesn't make any sense and won't even work
Yeah, reliasing that now
And why are you committing and closing a connection that hasn't been opened? And why are you executing the same query twice, but once without a parameter?
It has been opened, Just didnt involve it in the code as the connect code had my db pass
?tag 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.
So why are you trying to loop over a variable that isn't even declared? And why are you executing twice?
Where? am i missing smth?
Did you read your own code?
So to answer your question, basically everything is wrong with your code. Conclusion, learn python and read the docs of the libraries you are using.
bot_ids = []
new_ids = [guild_id for guild_id in bot_ids if guild_id not in db_ids]
InsertIds = "INSERT INTO serverinfo (ServerID) VALUES (%s)"
cursor.execute(InsertIds)
Connection.commit()
Connection.close()
``` Little updated, still need to fix the top though
You're looping over an empty list, storing it in a variable, and then never use it again. What are you even doing?
I am trying to get all the server ids, compare them to the server ids already in my database, then insert missing ones
Where are you getting all the server ids?
Here:
new_ids = [guild_id for guild_id in bot_ids if guild_id not in db_ids]
Although obviously is wrong (Fixing atm)
Bruh, bot_ids is literally an empty list. How would looping over that get all server ids?
Is this even pycord?
have u sent ur code
When googling for that error I only see "autocode" and "javascript"
Why did you set auto_sync_commands to False?
Oh my lord
How do you have that many slash commands?
how?
I can't even imagine what you would need 300 commands for
Guess their issue was solved 🤷♂️
deleted all messages

god knows
So instead of posting a solution for others to see, you delete all your messages? Interesting method

I guess they were embarrassed about having a question posted in this channel 
Hmm nothing, I was just confused why I can use discord.Bot in some cases and in others I can just use commands from discord.ext
Well basically, before slash commands existed discord.Bot didn't exist; all command related functions were in ext.commands
Then when slash commands were introduced, discord.Bot was added so you could have slash commands without prefix commands
so why not just add it to discord.ext then?
Some stuff was moved over to the core lib like cogs, but for the most part all the other functions remain in the extension
.-. okay
Since slash commands are "official", they are in the main library
That being said, essentially everything in ext.commands is still compatible with slash commands
yeah I know I know, its just, would be nice to have everything in one I suppose, so you dont have to import discord and then discord.ext for permissions, but can just import discord and have permission decorators in that too :P
but ig that wont happen since permissions havent really changed, and are slash command compatible
Well there are permission decorators in the main lib, but that's specifically slash command default perms
Keep in mind that pycord v2 is still a fork of discord.py, they can't refactor the entire lib since that'd basically just be pycord v3
Is there a way to do this without having to use channel.send for the second message?
There are two different views so I can't work with followup 😬
self.view.add_item(ChangeSpeed(self.bot, self.spotdaten))
await interaction.response.send_message(embed=embed, view=self.view)
await interaction.channel.send( view = await View(self.bot, self.spotdaten))```
What exactly do you mean with two different views? (I might be able to help you but I am not entirely sure)
I think all followup does is channel.send. what is the issue with how it is now?
I'm generally a bit bothered that with channel.send the message is posted directly under the previous one and with response.send_message reference is made to the previous message and the bot name is always in between.
You could try chanel.send on both views. (And respond to the first with a different message) That might get rid of the gap.
Overall that is something that is on the discord client side and there is no way to control it with pycord.
are there any decorators for limiting interactions by role? like in commands
@commands.has_role("member")
the only way i can think of rn is to check if the user who interacted has a role equal to the set role
Set default permissions
.rtfm default_perm
Wait i don't think you can set that for roles. Let me check
Can I somehow remove elements from View3 when I change something in View1?
await interaction.channel.send( view = View1(self.bot))
await interaction.channel.send( view = View2(self.bot))
await interaction.channel.send( view = View3(self.bot))```
Yea i don't think you can. You could in the old perms system
so uhh is it possible to make a bot that send message like this? this from NQN
Webhooks
aight thanks
Can I remove items from View3 when I change something in View1 or do I only save the message object and have no access to the view?
thisview = await interaction.channel.send( view = View1(self.bot))
nextview =await interaction.channel.send( view = View2(self.bot))
lastview = await interaction.channel.send( view = View3(self.bot))
lastview.remove_item()```
or you make a has_role decorator yourself :D
Hi, Ive went off and learned about the python OOP so i know about that now. Ive managed to change some stuff around to define client but now im just getting an error saying client.fetch_channel(id) doesnt have the ID in it when it actually does.
@bot.event
async def on_message(message):
channel = await client.fetch_channel(1029735370969055293)
print(f'Message from {message.author}: {message.content}')
await channel.send(f'Message from {message.author}: {message.content}')
Ive brought it into vsc and it says this in the parameters (image below) . So id have to put something in front of the ID for it to notice the ID, But idk what to put.
i mean i tried it on @discord.ui.button() but it did not work
No I mean you define a function which will work as your decorator 😶
Iirc, it should get get_channel and not awaited, also you should probably sort by guild like channel = message.guild.get_channel(123) or something like that i can't remember very well
Please make a seperate thread
async def captcha(self, ctx, *, text: Option(str, "Enter the text for the captcha")):```
How can I add a min/max for strings in slash commands?
.rtfm discord.Option.min
Target not found, try again and make sure to check your spelling.
.rtfm option.min
Target not found, try again and make sure to check your spelling.
ohhhh i see thanks
What are all the types of status my bot can have?
Watching, Playing.....
The API provides some enumerations for certain types of strings to avoid the API from being stringly typed in case the strings change in the future. All enumerations are subclasses of an internal c...
thank you 🙏
Alright, will try this later
Alright, will try the above first, if that doesn't work ill make one.
What's the code to get this menu on a slash command argument?
simple way is typehinting the parameter as discord.Member
Here's the slash options example.
more info here
thanks
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
^ the above error is instance of ApplicationCommandInvokeError, how do I make it an instance of Forbidden?
I solved this with custom errors by inheriting from ApplicationCommandInvokeError instead of Exception, but i would like to know how to do this with built-in exceptions as well
in a slash command, is it possible to send messages multiple times?
Not as a response. But You can send a normal message using ctx.followup
ah so followup
.rtfm ApplicationContext.followup
I have a slash command that takes several minutes to finish running. I’m using ctx.defer() right now but I want to implement a custom loading message. Is it possible to replace the “thinking…” message with my own message? Or would I have to make the bot create a new message just for the loading msg while it also has that thinking message above it
iirc command doesn't have permission to perform it's actions, could be bot permissions. Either it doesn't have perms in the guild or something on the discord dev portal, not sure though.
Send a response and then edit the message instead of deffering
Won't that error if the command takes a long time to finish
i thought that was the point of using defer
Why?..
You already respond
Instead of telling discord you need more time to send a reply, you send respond instantly and then edit the same message
I know what forbidden is
I'm asking how to make the exception be an instance of forbidden instead of applicationcommandinvokeerror
The error cause is pretty obvious from the exception message
oh i see
makes sense. thanks
Oh sorry completely missed that 
I'm not sure how to do it with built in exceptions tho.
Wait i think i remember smth. How are you adding your error handler?
I think you are to add it using bot.listen
cog_command_error in cogs, and a separate on_error one in a view class
ApplicationCommandInvokeError.original
discord/errors.py lines 397 to 407
class ApplicationCommandInvokeError(ApplicationCommandError):
"""Exception raised when the command being invoked raised an exception.
This inherits from :exc:`ApplicationCommandError`
Attributes
----------
original: :exc:`Exception`
The original exception that was raised. You can also get this via
the ``__cause__`` attribute.
"""```
Bruh that was so easy 💀
i completely missed that when reading the docs
Lol i had no idea that existed
I looked through the code to find it. I just learned of it. I just assumed it existed.
So I know when accepting an argument you can limit to certain variable types - def thing(number : int), can you also limit the range of the int?
What hosting can I use for a small bot for a server with friends with a database?
Use discord.Option
It has a max and min value kwarg
.rtfm discord.Option
Here's the slash options example.
I think railway would be enough
Awesome, thanks!
Hi there!
I couldn't find a way to get the information of when a member in a voice channel shares his screen.
Any ideas?
try:
for memberActivity in ctx.author.activities:
print(memberActivity)
except:
print("This user does not have any activity")
Can I remove items from View3 when I change something in View1 or do I only save the message object and have no access to the view?
thisview = await interaction.channel.send( view = View1(self.bot))
nextview =await interaction.channel.send( view = View2(self.bot))
lastview = await interaction.channel.send( view = View3(self.bot))
lastview.remove_item()```
Can you give more context? I can't understand
I have 3 views and each view has 5 select menus.
When I select something in the select menu another select menu is added to the view.
That means in the end I have 3 views with 15 select menus.
If I now change something in the very first select menu in View1, I want that in View2 and View3 also only the first select menu is displayed and the other 4 select menus are removed. But I don't know how to access View2 and View3 from View1 to remove the elements from the view.
what wrong with that?
i suggest using bot.load_extensions("folder_name") instead of manually looping and loading each file individually (notice the S at the end)
With a listdir you have "\" in the link.
Print your file and you will see.
This is my cog load script.
https://github.com/Ted-18/Bot.Assistant/blob/master/BotAssistant/services/serviceCogLoad.py
if os.name == 'nt':
cogPath = root.replace("\\", ".") + "." + importedFile.cogFile
elif os.name == 'posix':
cogPath = root.replace("/", ".") + "." + importedFile.cogFile
else:
Logger.system("OS: Unknown")
ngl this is much simpler 
Not if it decides to add and remove .py files
He wants to make it dynamic, that's what I did too.
uh?? bot.load_extensions is for loading .py files only
Are you sure that what you are doing is possible in this way? Is there anything easier?
.rtfm bot.load_extensions
yikes
He wants to make it so that he can add or remove commands simply by adding .py files to the commands folder.
Like plugins in minecraft server
sorry ngl but i did not understand the difference between that and what i said. you pass the folder name to the method. the library loads all files and even files from subdirectories (uses recursion). you dont specify each individual file name
I don't know.
Can't I store the view in a variable and then access the view in another view via this variable and edit the view?
never played minecraft so dk 💀
Hooooo, okay I had not seen that there was a load_extensions and a load_extension
sorry
Change channel and check
I would especially like to know what the final objective is, because here you are talking about views and I don't understand what use you are making of them.
Wouldn't it be easier to create a next and previous button?
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)?
yeah you need to load cogs before running the bot
load command to load your bot load command??
as a workaround, add await bot.sync_commands() to the end of your /load command
Okay if I save the view like this in a variable, I can edit the view like this in another view in the callback function from the select menu:
view = await TestView(self.bot)
if view :
view.children[0].disabled = True
await view.message.edit(view=view)```
You have a View, you can put it in a variable, add an element and update your view on your message, yes.
I'm not sure I understood what you wanted but obviously what you're trying to do is possible, although it may be a bit technical.
I am planning on using "Wavelink" , If my bot reaches a lot of servers, will it get taken down?
Without the variable I have no chance to access the view or?
So I have it in mind that you can also search for a channel by name. But a view you can not give a name and then search or?

Give a name to a view? You define the name of your view in your code
Each message can have only one view.
Is this the only way I can access and modify the view?
view = await TestView(self.bot)```
Or is that also possible here?
```py
view = await interaction.response.send_message('Hello', view=await TestView(self.bot))```
import discord
view = discord.ui.View()
view.add_item(discord.ui.Button(label="Click me!"))
Yes I know that but as here I can not access the view or?
Because I would save the message object and then I can not access the view or?
view = await interaction.response.send_message('Hello', view=await TestView(self.bot))```
import discord
from discord.ext import commands
bot = commands.Bot()
view = discord.ui.View()
view.add_item(discord.ui.Button(label="Click me!"))
# Commande test
@bot.command()
async def test(ctx):
message = await ctx.respond("Hello!", view=view)
editedView = view
editedView.children[0].disabled = True
await message.edit_original_response("Hello!", view=view)
It's probably wrong but the principle is there
i dont have the most accurate advise regarding this, but as long you dont earn money from that feature it should be fine. incase you get a notice regarding it, you can remove the feature and the bot still stays up
Depends on what you're going to do with it
I can't access the view via the message object view can I?
Subclass the view
Then you can access the view
He wants to edit from a callback of another view an existing view, I don't really understand...
The hell
If you plan on playing music from any third party service that doesn't allow it, yes, your bot will most likely be taken down. Or at least warned and lose it's verification.
Why you want to edit a view from another view
I have 3 views and each view has 5 select menus.
If I'm not mistaken, your total number of choices will be 25 maximum anyway.
Isn't it easier just to have one select menu and edit the options, and pass the new edited select menu?
It is not functional but I hope you understand what I have in mind.
class TestView(discord.ui.View):
async def __init__(self, bot: discord.Bot):
super().__init__(
timeout=None
)
class TestView2(discord.ui.View):
async def __init__(self, bot: discord.Bot):
super().__init__(
await SelectMenu(bot),
timeout=None
)
class SelectMenu(discord.ui.Select):
def __init__(self, bot: discord.Bot, spotdaten):
options = [discord.SelectOption(label=name) for name in ['1','2','3']]
super().__init__(
placeholder='Test',
min_values=1,
max_values=1,
options=options,
custom_id='TestClass'
)
async def callback(self, interaction: discord.Interaction):
#Here I want to access the view (edit) to edit it
@slashcommand()
async def test(ctx):
edit = await interaction.response.send_message('Hello', view=await TestView(self.bot))
Or replace each select menu instead of adding them?
Do you want a selector with your two views and when the person selects one of the two views it is applied to the message?
My point stands
However, I have a query:
- type
- manufacturer
- name
- color
- size
And if I notice a mistake afterwards I want to be able to change it, so replacing the selection options is not optimal.
And the problem is that the selections are dependent on each other.
So if I change the type in View1 afterwards, I get only other types for selection in View2, so I have to remove the select menus there for manufacturer, name, color and size so that the user has to select them again with the new type.
Si if I select until color, and then change type, that means the select menus will need to be generated all of them again because one option changed?
from what i remember from my previous conversations with this person, yes
The Select menus appear one after the other. When I select a type, the select menu for the manufacturer appears, etc.
If all select menus have a selection and I change the type, all select menus are removed and must be selected again one after the other.
In my opinion, this is something very difficult to achieve and you don't have the skill for it
I have everything ready. My only problem is how to save the views.
Can I access the view only if I pass the view to the variable and then send it?
view = await TestView(self.bot)
await interaction.response.send_message('Hello', view=view)```
Or can I do this step in one and can access the view here as well? Because here I store the message object?
```py
view = await interaction.response.send_message('Hello', view=await TestView(self.bot))```
If I had been able to understand the objective I would have tried to code a solution for it. But I didn't understand anything
then I should be able to access the view via view.view and the elements via view.view.children right?
Assuming you're in your select menu callback
self is your select
self.view is the view your select is attached to
"view.view.children"
in callback1 I save the message like this and put it e.g. into a dict:
messagesave = await interaction.response.send_message('Hello', view=await TestView(self.bot))```
in callback2 i read the variable messagesave from the dict and should then be able to access the view from callback1 via messagesave.view or?
no
For God sake, self.view already returns the view
You just pass self.view to your next view
You don't store any message
And response.send_message doesn't return a message object
Yes it is an interaction object but you can't access the view through it because the interaction object has no attribute view
I have already saved the interaction and thought that maybe I can access the view through it so I would have 2 things done with one thing but that is not possible because the interaction object does not have a view attribute.
Then just use self.view
Yes thanks!
Hey I want to execute a task everyday at 6:19pm, but when I give the decorator the datetime.time object nothing happens at the specified time. Hope somebody can help me 😅
You shouldn't start tasks in on_ready, that event can fire multiple times.
And try this instead
@tasks.loop(time=datetime.strptime('12:00AM', '%H:%M%p').time())
Hey all, need some help with Paginator, I have this working with images which are stored as urls... but it doesn't work for attaching local files for some reason? The embed pages show no images when generating them using the following:
with open(f"graph_{key}.png", "rb") as f:
file = io.BytesIO(f.read())
image = discord.File(file, filename=f"graph_{key}.png")
embed.set_image(url=f"attachment://graph_{key}.png")
embedlist.append([embed])```
Thanks for any insight on the issue, i am stumped couldn't find anything similar
good idea to post this in #1047189308131508306 instead
oh sorry. will move it there thank you
how to get slash commands in cogs
Here's the slash cog example.
Is Discord very slow right now? Everything in Discord is slow for me 🤔
that also does not seem to work sadly
Any errors? Just does not fire? Make sure the timezone info is correct.
I was able to fix the issue, I did not specify the timezone to be utc 😅
Was a little confused since I use cet
Just curious on how to fix this import error?
Traceback (most recent call last):
File "main.py", line 4, in <module>
from pycord import Client, Intents, Member, Role
ImportError: cannot import name 'Client' from 'pycord' (/home/runner/Discord-Translator-Bot/venv/lib/python3.10/site-packages/pycord/__init__.py)```
This is what I'm trying to import
from pycord import Client, Intents, Member, Role```
Are you using pycord v3?
No, V2.4.1
Then why are you trying to import it as pycord? It's still discord
ope, my bad 😅
Still getting used to pycord here
Hey guys, Im currently trying to find how to fetch the user when a scheduled event is created (the creator)
Im looking through the documentation, but cant find any regarding that
.rtfm get_member
.rtfm fetch_member
async def sendinfo(self, ctx, discord.ApplicationContext, member: Option(discord.Member, "Select User"), duration: Option(str, "Punishment duration information.", required=False, default="Not provided"), reason: Option(str, "Punishment reason information.", required=False, default="Not Provided"), appeal: Option(str, "Can this user appeal?", choices=["yes","no"], required=False, default="Not Provided")):```
Why is this syntax incorrect? What did I do wrong
looks fine for me
Says syntax error
where?
Shouldn't it be ctx: discord.ApplicationContext ?
yes, it should be
@undone mulch
It's typehinting
It doesn't do anything but help the IDE
It doesn't mean you code will be faster or something
its still a ,
doesn't adding :type to something just add type hinting?
Example:
def func(text: str):
print (text)
```or does it like make it so you have to put in a string or something?
no, you can put a cow in there for all python cares
damn
but -> type forces your function to return a certain value... right?
Example:
def func(text) -> None:
print (text)
it definitely helps readibility
nope, you can return a cow for all python cares
They're just like comments
like comments but it appears in the IDE type checking without you having to "look" at it?
the IDE is just an abstraction on top of the Python Interpreter.
yeah
Depending on your IDE, it may somewhat enforce those Python types, but your program can still run
Don't use json as a database
embed.add_field(name="xxx", value="I[H") # output I[H
but
embed.add_field(name="xxx", value="f\w") # output f\w
why?
sorry what?
\ + [, the \ will disappear
\ is used to escape special characters like * < { [ etc
so lets say you want to show 2 *
but discord will render them as italics
if you put \ before the *
you get *italics*
get it?
this is markdown stuff
when I want to output string with \, I need only to replace one with two?
hi, how could i make a voice controlled discord bot
I have added a try and except in the callback from my select menu. But when an error occurs, is it always written multiple times in the log file? Why does this happen and can I prevent that the error message is written only 1x?
class Select(discord.ui.Select):
#__init__
async def callback(self, interaction: discord.Interaction):
try:
#something
except Exception as e:
#Write error to log file
Not sure if pycord is equipped for this. You would have to record audio and than feed it to a speech to text library.
https://github.com/Pycord-Development/pycord/blob/master/examples/audio_recording.py
because i saw this
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - pycord/audio_recording.py at master · Pycord-Development/pycord
You can try it out. But as of now you need to have a recording not a live audio stream I think. If it works to take 5 seconds recordings or something it is probably possible.
i tried the thing from the repo out and got a problem with the sinks
if i try to trigger like ?start mp3 i get discord.ext.commands.errors.BadArgument: Converting to "Sinks" failed for parameter "sink".
I think you should just use a set sink. Im not sure if there is a reason to choose per recording. The example might only work with slash commands
okay, got the sinks now working with slash commands, but the recording isnt working:
@bot.slash_command(guild_ids=[893578607941795891], description="Start Audio Recording!")
@option("sink", description="Wähle das Format aus")
@commands.has_permissions(administrator=True)
async def start(ctx: discord.ApplicationContext, sink: Sinks):
try:
"""Record your voice!"""
await ctx.defer()
voice = ctx.author.voice
if not voice:
return await ctx.send_followup("You're not in a vc right now")
print(voice)
print("connecting now.....")
vc = await voice.channel.connect()
print("connected to voice channel")
connections.update({ctx.guild.id: vc})
print(f"connections: {connections}")
vc.start_recording(
sink.value,
finished_callback,
ctx.channel,
)
print(vc)
print("test")
await ctx.send_followup("The recording has started!")
except Exception as e:
print(e)
it prints voice and connecting now then nothing happens
it connects to the vc but i dont get "connected to voice channel"
This requires Intents.voice_states.
isnt it in discord.Intents.all()?
👍
now i have
intents = discord.Intents.all()
intents.members = True
intents.voice_states = True
but its still the same problem
You add the intensts to the bot correct?
bot = discord.Bot(intents=intents)
or similar
I dont think so
yeah
class ChatBot(commands.Bot):
def __init__(self):
super().__init__(command_prefix=commands.when_mentioned_or('?'), case_insensitive=True, intents=intents)
self.persistent_views_added = False
async def on_ready(self):
if not self.persistent_views_added:
self.persistent_views_added = True
print("hi")
bot = ChatBot()
bot.remove_command('help')
Anyways the problem is about connecting to the VC not receiving audio.
- vc = await voice.channel.connect()
+ vc = await voice.channel.connect(timeout=10)
Than wait 10 seconds to see if it errors.
Something is either catching the error or blocking your code than.
@bot.slash_command(guild_ids=[893578607941795891], description="Start Audio Recording!")
@option("sink", description="Wähle das Format aus")
@commands.has_permissions(administrator=True)
async def start(ctx: discord.ApplicationContext, sink: Sinks):
try:
"""Record your voice!"""
await ctx.defer()
voice = ctx.author.voice
if not voice:
return await ctx.send_followup("You're not in a vc right now")
print("connecting now.....")
if not ctx.voice_client:
print("nuttnsohn")
vc = await voice.channel.connect(timeout=10)
print("connected to voice channel")
connections.update({ctx.guild.id: vc})
print(f"connections: {connections}")
vc.start_recording(
sink.value,
finished_callback,
ctx.channel,
)
print(vc)
print("test")
await ctx.send_followup("The recording has started!")
else:
await ctx.send_followup(f"I can't join your voice channel I am already connected to {ctx.voice_client.channel}",)
except Exception as e:
print(e)
``` added a check now
if i do /start it joins the channel like before if i switch the channel then and try to do / start i get I can't join your voice channel I am already connected to....
so its very weird
Becouse you are just checking if there is any voice client. Not a shared one with the user.
yeah
i know but if it has a voice client why isnt it working
true. Does the bot have permissions to join the VC?
it has admin perms
also it joins the vc
@bot.slash_command(guild_ids=[893578607941795891], description="Start Audio Recording!")
@option("sink", description="Wähle das Format aus")
@commands.has_permissions(administrator=True)
async def start(ctx: discord.ApplicationContext, sink: Sinks):
try:
"""Record your voice!"""
#await ctx.defer()
voice = ctx.author.voice
if not voice:
#return await ctx.send_followup("You're not in a vc right now")
return await ctx.respond("You're not in a vc right now")
print("connecting now.....")
if not ctx.voice_client:
print("kek")
try:
vc = await voice.channel.connect()
except Exception as e:
print(f"Failed to connect to voice channel: {e}")
return
print("connected to voice channel")
connections.update({ctx.guild.id: vc})
print(f"connections: {connections}")
vc.start_recording(
sink.value,
finished_callback,
ctx.channel,
)
print(vc)
print("test")
#await ctx.send_followup("The recording has started!")
await ctx.respond("The recording has started!")
else:
#await ctx.send_followup(f"I can't join your voice channel I am already connected to {ctx.voice_client.channel}",)
await ctx.respond(f"I can't join your voice channel I am already connected to {ctx.voice_client.channel}",)
except Exception as e:
print(e)
this is my code now
its not working no error
What does the bot respond with?
connecting now..... What does it print after this?
and it does not print connected to voice channel
could it be a problem, that are more bots are running on my vps?
Possibly does it work on your own PC or is it not setup there?
wait i have to set it up on my py wait
Its not a database. And how is that helpful to my question? Might as well just not say anything.
Its a hashed seed. Tell Minecraft not to use json.
Its beneficial.
I'm locally storing a json seed database
So it's not a database?
And your issue is that you're never updating the data stored in memory, you read it once, store it in a variable and never update it
i was on pycord 2.3.3.dev8+g647f00f7 and i now updated to pip 2.4.1 and itw working now
I read it, then load it again. I have tried opening and closing it to.
Oh it's the ip discovery thing
I was just about to have you try that.
XD, at least it eorks now
Packet size changed
How do you force the memory to reload?
No, in your save function you never read the value into your edb variable
So every-time I save anything I should reload the memory directly within the function?
and close is a method, you're just referencing it as an attribute
I have tried that though. Using a standard with open and .load but it doesn’t seem to update the memory
Unless there is another way I don’t know exist
Like a memory reloader
You don't "update the memory". You read the values of the file into a variable, a variable is part of your memory
What?
The json has 500 keys of content
What do you mean update? If you're reading a value, why would you update anything?
Because it seems that the json data in my bot gets cached or something. The bot can update the json live and process it. But if I change it manually directly in the ftp without commands that is where it doesn’t register my changes without a restart.
This is important because I am making a backup system command to backup the data and restore files. And it does the same problem when using OS to copy a file to replace it.
How would the bot know to re-read the file if you manually change it?
Because I made a command that opens the file again and reloads it
Of course it's not going to update, your program has no idea the file has been changed and won't read it
And that doesn’t fix it
And how does that command look?
Make sure you are actually saving the file when you manually change it.
Im on mobile right now but its standard json. Content = var.read()
Well it's impossible to say what's wrong without seeing the code.
Could be anything
Yes I am pressing save. The entire file is being replaced by the bot. So it does it.
Let me see if I can access the ftp on mobile
@limber urchin
Define the backup command
@client.command()
@commands.is_owner()
async def backup(ctx, db_number: int, backup_index: int):
# Get the backup filename for the specified index
db_backup_dir = os.path.join(backup_dir, f"DB{db_number} Backups")
db_backup_files = os.listdir(db_backup_dir)
db_backup_files.sort(reverse=True)
backup_filename = db_backup_files[backup_index - 1]
# Get the paths for the source and destination files
db_source_path = os.path.join(db_backup_dir, backup_filename)
db_dest_path = os.path.join(source_dir, f"game_database{db_number}.json")
# Copy the backup file to the source directory
shutil.copy(db_source_path, db_dest_path)
# Reload the JSON data and update the global variable
with open(db_dest_path, "r") as f:
game_data = json.load(f)
globals()[f"game_data{db_number}"] = game_data
# Send a message to confirm the backup was restored
await ctx.send(f"Backup {backup_index} for database {db_number} has been restored.")
I am on Iphone. Idk how to put it in blocks.
But you never read anything into your edb variable there
No
so i want to get someone's nickname in the server. using bot.fetch_user returns a user object that doesn't have that information
since display_name returns their discord name, not the nickname they set
.rtfm fetch_member
Users aren't part of servers, members are
ah so i have to get the guild and get the member from it
yes
got it, thanks
def retrieve_report_city(self, city: str):
response = requests.get('https://api.weatherapi.com/v1/current.json', params={"key": self.bot.WEATHER_TOKEN, "q": city})
return response.json()
weather = SlashCommandGroup("weather", "Gets weather at a location")
@weather.command()
report = self.retrieve_report_city(self, city) # <-- Unexpected argument 'city'
async def city(self, ctx, city: discord.Option(str)):
any idea why it says the city bit in this is unexpected, been perfectly fine until i moved it to a cog
?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
this is very likely something inexpicably small and it jsut went over my head
And you don't pass self to class methods
That is passed automatically since you're calling self.
is there a limit on how much text can be in an embed
so there can be 25k characters per embed when using field values
if every field value is used
yep
there is a max limit of 6k characters in a message factoring in all embeds
yea
this is really annoying, especially if you want to format URLS to look nicer
How do you have a url over 6k characters?
use url shortners?
i have multiple URLs i need to display, and with the formatting + urls it goes over the 6k char limti
You could always send them as separate messages I guess, or like mentioned, use a URL shortener
i think i'll just leave them unformatted
It's a Discord limitation, not much we can do about it unfortunately
or this 
That wouldn’t work in my specific use case
Since i rely on the urls as keys
I ended up splitting big url messages into chunks of embeds containing multiple chunks of urls as fields
whats a good way to get extra info from the user after a slash command?
let's say the user uses /commandA this helps the bot know what the user wants. but let's say depending on which option was picked by the user, if the bot needs some more info specific to that particular chosen option, what is a good way to ask a follow up question?
If it is text based input, modals should be the best way
I need some help here
When doing ctx.author.roles, i receive a list [<Role id=996922553266360360 name='@everyone'>, <Role id=1068467634317832222 name='Bots'>]
And I want to access every single id of this list. Tho, when doing for role in roles, role is equal to the name (So @everyone and Bots). How can I make role be the ID?
i think i found it ( role.id)
Oh yeah yeah it works like that
Thanks
writing a modal, can someone help why i am getting an application did not respond error even before i'm interacting with the modal?
this is how i'm sending the modal:
await ctx.send_modal(SpecialItem(ctx, amount, title = 'Please enter name of item'))
It should throw a console error
nah it isn't
You are receiving the error on the slash cmd, not the modal
Are you taking longer than 3 seconds to respond
No i wasn't, it was throwing that error as soon as the modal was invoked
But after rewriting literally the same code, it seems to be gone lol
Oh huh lmao
hello, I created a bot captcha, but there is one problem. At the first attempt of the bot, everything works for me, but when I call the command a second time, such an error occurs. It cannot open the png file. How to solve a problem?
CODE
do not pay attention to the file names CAPTCHA.png and code.png, the result will be the same
full error please
one moment
Ignoring exception in view <Message timeout=180.0 children=1> for item <Button style=<ButtonStyle.secondary: 2> url=None disabled=False label='Верификация' emoji=None row=None>:
Traceback (most recent call last):
File "C:\Users\young\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ui\view.py", line 414, in _scheduled_task
await item.callback(interaction)
File "C:\Users\young\Desktop\captcha bot\verify.py", line 41, in button_callback
await interaction.response.send_message(file=file, embed=embed1, view=Main())
File "C:\Users\young\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\interactions.py", line 825, in send_message
await self._locked_response(
File "C:\Users\young\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\interactions.py", line 1090, in _locked_response
await coro
File "C:\Users\young\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\webhook\async_.py", line 157, in request
async with session.request(
File "C:\Users\young\AppData\Local\Programs\Python\Python310\lib\site-packages\aiohttp\client.py", line 1141, in __aenter__
self._resp = await self._coro
File "C:\Users\young\AppData\Local\Programs\Python\Python310\lib\site-packages\aiohttp\client.py", line 508, in _request
req = self._request_class(
File "C:\Users\young\AppData\Local\Programs\Python\Python310\lib\site-packages\aiohttp\client_reqrep.py", line 313, in __init__
self.update_body_from_data(data)
File "C:\Users\young\AppData\Local\Programs\Python\Python310\lib\site-packages\aiohttp\client_reqrep.py", line 505, in update_body_from_data
body = body()
File "C:\Users\young\AppData\Local\Programs\Python\Python310\lib\site-packages\aiohttp\formdata.py", line 170, in __call__
return self._gen_form_data()
File "C:\Users\young\AppData\Local\Programs\Python\Python310\lib\site-packages\aiohttp\formdata.py", line 163, in _gen_form_data
self._writer.append_payload(part)
File "C:\Users\young\AppData\Local\Programs\Python\Python310\lib\site-packages\aiohttp\multipart.py", line 829, in append_payload
size = payload.size
File "C:\Users\young\AppData\Local\Programs\Python\Python310\lib\site-packages\aiohttp\payload.py", line 379, in size
return os.fstat(self._value.fileno()).st_size - self._value.tell()
ValueError: I/O operation on closed file```
The main task. The bot creates a captcha image, puts a random code there, displays this image in the embed. Everything works, but the second time when you call it, an error is raised
How is that, can you tell me please?)
yea so io.BytesIO is an in memory file like object. im not sure how you generate the image, but generally it is used the same way as using open-
with io.ByesIO() as f:
f.write(...)
x = f.read()
# any other thing you could with a normal file
the Image library creates a captcha of an image on disk with set_image before the image
path.
embed1.set_image(url="attachment://code.png")
?
?tag localfile
f = discord.File("some_file_path", filename="image.png")
e = discord.Embed()
e.set_image(url="attachment://image.png")
await messagable.send(file=f, embed=e)```
why do you open it?
by Image library ig PIL ? that has a save method. the save method which also accepts a file like object. and the set_image thing can be done with BytesIO too
yeah, PIL
the file name you set in discord.File should match with what you put in the url
Ok, I will take a look
oh btw you arent opening the file inside the button callback?
when using with open, the file gets closed when the code inside the block is executed
Opening a file, is outside the callback
yea that wont work
I did without open, the same problem
cuz it will get closed when the code gets out of the with block
try opening inside the callback like so
with open(...) as f:
...
await interaction.response.send_message(...)
notice the indentation. send is inside the with block
oksss
?
one second
yea just indent all the other lines inside the with block
Thanks bro, I got it resolved and he got up as much as he wanted. only one problem, he does not require captcha, but throws off the same way, I will solve it somehow
Imagine, the bot sent a message that has a button attached to it. While it was online since sending the message, the button worked perfectly. But why doesn't the button work after restarting thw bot?
Take a look at persistent views
Here's the persistent example.
Okay, why do I need a custom id?
How else is the bot going to know which button to run the view events on?
Does anoyone know how to add fields to modals in wich input is not required? And: before everyone says Read the docs i did i can’t find it
.rtfm InputText.required
It's literally in the docs
Than i searched at the wrong page
hey, I am having trouble installing pycord. trying the example bot it fails to import discord
is it in your venv ? run pip list and post the results of that here
?tag notpycord
The library name is py-cord not pycord
figured it out
you would also have to restart your terminal/IDE after installing
I followed directions a little to well
are the instructions ambiguous?
no I dev in python 2.5.6 to 3.12.0a6. my interp was set to 3.11 but I kept doing python3.10 -m pip .....
ic
I am tired from college so my 2 brain cells were fighting for 3rd place on that one
it happens
thank you. though unless I am blind I didnt see that on the website. Would have been helpful if it is not there. something like if your interp is 3.x.x then do this command 3.x.x vs 3.a.a and 3.a.a
but like i said it is on me thank you for your help.
How do i find the person that ran a slash command that wasn't my bot? (Using the on_message event or not doesn't really matter)
Example:
Someone runs /bump on disboard and i want to track that to give them like a bumper role after X bumps, how would i figure out who did that?
Is it message.reference?
nvm
I have this code here```py
import discord, asyncio, random
from discord.commands import slash_command, Option
from discord.ext import commands
from myfunctions import Load, Save
songs = ["CarelessWhisper"]
class Join(commands.Cog):
def init(self, client):
self.client = client
@slash_command(description="Joins a channel")
async def join(self, ctx):
if ctx.author.voice:
channel = ctx.author.voice.channel
try:
await channel.connect()
except:
await ctx.voice_client.move_to(channel)
Data = Load()
Data[str(ctx.guild.id)] = channel.id
Save(Data)
embed = discord.Embed(
title = "Joined Channel",
description = "Successfully joined channel. You can now enjoy the best music!",
color = discord.Color.green()
)
embed.set_footer(text="Powered by VersaDev.org")
if not ctx.guild.voice_client.is_playing():
ctx.guild.voice_client.play(source=f"file:{random.choice(songs)}.mp3")
Message = await ctx.respond(embed=embed)but when it comes to py
ctx.guild.voice_client.play(source=f"file:{random.choice(songs)}.mp3"), It runs into the error:
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: ClientException: Not connected to voice``` even when the bot is actually in the voice channel
- Uninstall discord.py or any other forks of discord.py you might have with the namespace
discord.
python -m pip uninstall discord.py discord -y
2a. Install py-cord
python -m pip install py-cord
2b. Update py-cord
python pip install -U py-cord
Installing other builds:
Note: You need to have git installed. Use ?tag git to find out how to install git.
Updating the module to master branch (unstable):
pip install -U git+https://github.com/Pycord-Development/pycord
ctx.message.author you can read ab it on the docs.
.rtfm message.interaction
Hi there! I am trying to embed an local gif into a message. However any local Gif (as well as any local file) is ignored.
loading_icon: discord.File = discord.File("src/downloading.gif", filename="downloading.gif")
embed.set_footer(text="Progress : 0%", icon_url="attachment://downloading.gif")
it simply does not show up in the embed. (thumbnail doesnt work either.) -> It is completely ignored not just not loading.
I am not quite sure what I am missing.
Note : It does work with any "real" url
?tag localfile
f = discord.File("some_file_path", filename="image.png")
e = discord.Embed()
e.set_image(url="attachment://image.png")
await messagable.send(file=f, embed=e)```
Ah dumb me sorry and thanks a lot!
How to get a user's account creation date in hours?
I keep getting a
TypeError: 'str' object is not callable
Full error:
Ignoring exception in command server status:
Traceback (most recent call last):
File "/home/runner/CMMSDiscorBot/venv/lib/python3.10/site-packages/discord/commands/core.py", line 124, in wrapped
ret = await coro(arg)
File "/home/runner/CMMSDiscorBot/venv/lib/python3.10/site-packages/discord/commands/core.py", line 982, in _invoke
await self.callback(ctx, **kwargs)
File "/home/runner/CMMSDiscorBot/TheBot.py", line 55, in SERVERStatus
SERstatus = Server.Serverstatus()
File "/home/runner/CMMSDiscorBot/serverHandler.py", line 46, in Serverstatus
return server.status()
TypeError: 'str' object is not callable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/CMMSDiscorBot/venv/lib/python3.10/site-packages/discord/bot.py", line 1114, in invoke_application_command
await ctx.command.invoke(ctx)
File "/home/runner/CMMSDiscorBot/venv/lib/python3.10/site-packages/discord/commands/core.py", line 375, in invoke
await injected(ctx)
File "/home/runner/CMMSDiscorBot/venv/lib/python3.10/site-packages/discord/commands/core.py", line 124, in wrapped
ret = await coro(arg)
File "/home/runner/CMMSDiscorBot/venv/lib/python3.10/site-packages/discord/commands/core.py", line 1312, in _invoke
await command.invoke(ctx)
File "/home/runner/CMMSDiscorBot/venv/lib/python3.10/site-packages/discord/commands/core.py", line 375, in invoke
await injected(ctx)
File "/home/runner/CMMSDiscorBot/venv/lib/python3.10/site-packages/discord/commands/core.py", line 132, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: 'str' object is not callable
.rtfm user.crea
2nd one
Remove the ()
Where?
Some code
def Serverstatus():
return server.status()
Another file
@server.command(name="status", description="See the server status.")
async def SERVERStatus(ctx):
SERstatus = Server.Serverstatus()
await ctx.respond(f"The status of the server is currently `{SERstatus}`")
Wait, lemme see
It works now. thanks
And please read your errors in the future, it tells you exactly what's wrong
Hey there again!
I want/need to edit an message/response from within an sync function (that runs for some time) but I cant manage to get it to work
what I tried
def hook(interaction):
await interaction.edit_original_response(text="new progress") # obv doesnt work
interaction.... # does not work cant call without await
asyncio.run(interaction....) # does nothing
asyncio.create_task(inter....) # does also nothing
@...
async def my_command(interaction):
await interaction.respond(text="Progress")
my_object.do_long_lasting_stuff(hook, interaction)
exporting my_object into its own async function didnt work either
having a task function run didnt do anything as well.
async def my_command(interaction):
await interaction.respond(text="Progress")
my_task.start() # doesnt do anything cause the next line blocks the thread
my_object.do_long_lasting_stuff(hook, interaction)
TLDR; I need a way to edit/send a message from a synchronous method
.tag lp
Official Beginner's Guide: https://wiki.python.org/moin/BeginnersGuide
Official Tutorial: https://docs.python.org/3/tutorial/
Shortcuts:
https://wiki.python.org/moin/BeginnersGuide/NonProgrammers
https://wiki.python.org/moin/BeginnersGuide/Programmers
Learn Python:
https://automatetheboringstuff.com/ (for complete beginners to programming)
https://learnxinyminutes.com/docs/python3/ (for people who know programming already)
https://docs.python.org/3/tutorial/ (official tutorial)
http://python.swaroopch.com/ (useful book)
http://www.codeabbey.com/ (exercises for beginners)
Learn python
You can’t call an asynchronous function from a synchronous function.
That’s basic python knowledge. You won’t be able to achieve what you want because you need to await the send/edit functions since they are API calls.
Yes I know that but all the "official" ways to schedule tasks/methods don't work for some reason. The only thing that works is run_in_executor but that seems hackery

Doesn't make sense. run in executor is used to run blocking functions without blocking the event loop
Not for calling async functions from sync functions
Try asyncio.create_task as that should be a best way
If not try bot.loop.create_task
Also try asyncio.run_coroutine_threadsafe
No sorry i used execute for the blocking part to have it not block
asyncio create_task did not work. netiher did the bot.loop approach. I will try threadsafe
Can you show how you tried the create_task ways
pretty much like here
but ill try to write it down better
Is it possible to make it so that only numbers can be entered in the modal?
Using the type hint TextChannel does not include announcement channels to be referenced in the slash command, what type should I use?
Unfortunately no. Discord limitation
Use options and specify channel types
Here's the slash options example.
.rtfm Option
discord.Option
discord.Option.converter
discord.Option.to_dict
discord.ThreadOption
discord.OptionChoice
discord.OptionChoice.to_dict
discord.SelectOption
discord.SelectOption.default
discord.SelectOption.description
discord.SelectOption.emoji
discord.SelectOption.from_dict
discord.SelectOption.label
discord.SelectOption.to_dict
discord.SelectOption.value
discord.commands.option
discord.ApplicationContext.selected_options
discord.ApplicationContext.unselected_options
discord.SlashCommandOptionType
discord.SlashCommandOptionType.sub_command
discord.SlashCommandOptionType.sub_command_group
1st one
Yes that's what I'm doing. Specifying TextChannel does not include announcement channels.
announcement channels are of news channel type
.rtfm news
Forgot to tell that lol
Oh okay, can I use Union types inside Option?
Uh no you would pass that to channel_types iirc
I tried that, i stated it was not from my bot, if i used that, I’d get the bot author ID.
Thank you! Ill try this when i can
gotcha
😓
I have added a try and except in the callback from my select menu. But when an error occurs, is it always written multiple times in the log file? Why does this happen and can I prevent that the error message is written only 1x?
class Select(discord.ui.Select):
#__init__
async def callback(self, interaction: discord.Interaction):
try:
#something
except Exception as e:
#Write error to log file
Your likely triggering multiple exceptions along the way, the one your code triggered and the ones thrown by the libraries because of something in your code. Seeing the actual code and traceback will make it so we might be able to help.
This is my code:
class Gewaesser(discord.ui.Select):
def __init__(self, bot: discord.Bot):
try:
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,
custom_id="Waters",
)
except Exception as e:
logger.error(f'An error occurred in Waters.__init__: {e}')
async def callback(self, interaction: discord.Interaction):
try:
if len(self.view.children) > 1 and interaction.data['custom_id'] == 'gewaesser_select':
self.placeholder = self.values[0]
await self.view.message.edit(view=self.view)
else:
self.placeholder = self.values[0]
await self.view.message.edit(view=self.view)
except Exception as e:
logger.error(f'An error occurred in Waters.callback: {e}')
finally:
await interaction.response.defer()```
and the traceback?
If I insert this line in the try block to provoke an error:
some_variable = '5' + 5```
I get this entry in the log file:
2023-03-26 19:31:34,661 : ERROR : spotinsert : An error occurred in Waters.init: can only concatenate str (not "int") to str
2023-03-26 19:31:34,661 : ERROR : spotinsert : An error occurred in Waters.init: can only concatenate str (not "int") to str
2023-03-26 19:31:34,661 : ERROR : spotinsert : An error occurred in Waters.init: can only concatenate str (not "int") to str
2023-03-26 19:31:34,661 : ERROR : spotinsert : An error occurred in Waters.init: can only concatenate str (not "int") to str
2023-03-26 19:31:34,661 : ERROR : spotinsert : An error occurred in Waters.init: can only concatenate str (not "int") to str
2023-03-26 19:31:34,661 : ERROR : spotinsert : An error occurred in Waters.init: can only concatenate str (not "int") to str
2023-03-26 19:31:34,661 : ERROR : spotinsert : An error occurred in Waters.init: can only concatenate str (not "int") to str
2023-03-26 19:31:34,661 : ERROR : spotinsert : An error occurred in Waters.init: can only concatenate str (not "int") to str
2023-03-26 19:31:34,661 : ERROR : spotinsert : An error occurred in Waters.init: can only concatenate str (not "int") to str
2023-03-26 19:31:34,661 : ERROR : spotinsert : An error occurred in Waters.init: can only concatenate str (not "int") to str
2023-03-26 19:31:34,661 : ERROR : spotinsert : An error occurred in Waters.init: can only concatenate str (not "int") to str
2023-03-26 19:31:34,661 : ERROR : spotinsert : An error occurred in Waters.init: can only concatenate str (not "int") to str
But I want to have the error message only once in my log file and not as often as now
What is the equivalent for setup_hook in pycord (migrating from discord.py)?
hey i got a boost bot that works well on my pc but when i run it on my rdp it gives me this
C:\Users\Administrator\Documents\BoostBotDemon>python main.py
Traceback (most recent call last):
File "C:\Users\Administrator\Documents\BoostBotDemon\main.py", line 72, in <module>
@bot.slash_command(
^^^^^^^^^^^^^^^^^^
File "C:\Users\Administrator\Documents\BoostBotDemon\discord\bot.py", line 894, in decorator
result = command(**kwargs)(func)
^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Administrator\Documents\BoostBotDemon\discord\commands\core.py", line 1650, in decorator
return cls(func, **attrs)
^^^^^^^^^^^^^^^^^^
File "C:\Users\Administrator\Documents\BoostBotDemon\discord\commands\core.py", line 640, in init
super().init(func, **kwargs)
File "C:\Users\Administrator\Documents\BoostBotDemon\discord\commands\core.py", line 181, in init
from ..ext.commands.cooldowns import BucketType, CooldownMapping, MaxConcurrency
File "C:\Users\Administrator\Documents\BoostBotDemon\discord\ext\commands_init_.py", line 18, in <module>
from .flags import *
File "C:\Users\Administrator\Documents\BoostBotDemon\discord\ext\commands\flags.py", line 71, in <module>
@dataclass
^^^^^^^^^
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\dataclasses.py", line 1220, in dataclass
return wrap(cls)
^^^^^^^^^
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\dataclasses.py", line 1210, in wrap
return _process_class(cls, init, repr, eq, order, unsafe_hash,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\dataclasses.py", line 958, in _process_class
cls_fields.append(_get_field(cls, name, type, kw_only))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python311\Lib\dataclasses.py", line 815, in _get_field
raise ValueError(f'mutable default {type(f.default)} for field '
ValueError: mutable default <class 'discord.utils._MissingSentinel'> for field name is not allowed: use default_factory
not a direct equivalent yet, but on the master branch you can do @client.listen(once=True) couple with on_ready or on_connect
this will run only once
I don't have a direct client object as I'm using subclasses
I read something about on_hook but doesn't seem to exist/ work
you would have an object of it in the main file right?
yea it isnt there in pycord
if you have cogs, @discord.Cog.listener(once=True) would work
TypeError: listener() got an unexpected keyword argument 'once' 🤔
master branch
It is only on the latest github version
##1801 can allow you to do what setup hook does
Summary
This is a feature pull request. It allowes you to start the bot via an async context manager.
Till now you were able to subclass Bot with something like
class MyBot(commands.Bot):
def _...
im not sure when that would be merged tho
Actually I'm already using the master branch
update once again
pip install -U git+https://github.com/Pycord-Development/pycord
it got added yesterday
I'm running it with docker so it's always getting updated automatically
If your docker container doesn't pull the latest master you won't get the updated version
aka the command that Om sent
You still need to build the image again for the latest version of libraries
yeah ofc
i did that
hmm and still the error?
yeah
can you show the py-cord line in the requirements file?
git+https://github.com/Pycord-Development/pycord
Hey there, i started my ticket bot after a long time and it works fine although on the start i get an error that doesn't compromise the work of the bot, but still i want to fix it of course.
Ignoring exception in on_connect
Traceback (most recent call last):
File "C:\Users\Federico\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 382, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Federico\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\bot.py", line 1025, in on_connect
await self.sync_commands()
File "C:\Users\Federico\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\bot.py", line 685, in sync_commands
await self.http.bulk_upsert_command_permissions(self.user.id, guild_id, guild_cmd_perms)
File "C:\Users\Federico\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\http.py", line 357, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 405 Method Not Allowed (error code: 0): 405: Method Not Allowed
If you have any idea of what can cause this error please let me know.
check if your debug_guilds / guild_ids are correct
Is your bot in all of those guilds?
Can I use custom server emojis in an embed?
yes
Ah just found it 🙂
Do you have any idea how I can get the icon image under the name with Beautiful Soup?
https://www.wowhead.com/de/item=5107/deckmatrosenhemd
url = f"https://www.wowhead.com/de/item={item_id}/"
response = requests.get(url)
content = response.content
soup = BeautifulSoup(content, 'html.parser')
item = soup.find('div', {'class': 'iconlarge'})```
My variable item always returns None...
¯_(ツ)_/¯
That entirely depends on what the HTML of the website looks like, we can't help you with that
and don't use requests for Discord bots
lol is this a bug?
await ctx.guild.change_voice_state(channel=self.connections[ctx.guild.id].channel, self_deaf=False)
the bot can still record voices
Why?
and shoulndt it look like this?
?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
can someone help
Ah okay thank you!
admin = bot.create_group("admin", "Admin/owner only commands")
cogs = admin.create_subgroup("cogs", "Cog-related commands")
i just tried to subgroup commands previously under admin in this cogs section
issue is that now they have no autofills, descriptions, etc
it also gets this error if i try to run one
AttributeError: type object '_MissingSentinel' has no attribute '_get_overridden_method'
is there some code i have to run to register those commands or this subgroup? i dont see anything on the guide or docs for this
lol is this a bug?
await ctx.guild.change_voice_state(channel=self.connections[ctx.guild.id].channel, self_deaf=False)
the bot can still record voices
Traceback (most recent call last):
File "C:\Users\sandb\AppData\Roaming\Python\Python311\site-packages\discord\commands\core.py", line 124, in wrapped
ret = await coro(arg)
^^^^^^^^^^^^^^^
File "C:\Users\sandb\AppData\Roaming\Python\Python311\site-packages\discord\commands\core.py", line 982, in _invoke
await self.callback(ctx, **kwargs)
File "C:\Users\sandb\Desktop\Jr\main.py", line 70, in staffwarn
if member.roles(role):
^^^^^^^^^^^^^^^^^^
TypeError: 'list' object is not callable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\sandb\AppData\Roaming\Python\Python311\site-packages\discord\bot.py", line 1114, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\sandb\AppData\Roaming\Python\Python311\site-packages\discord\commands\core.py", line 375, in invoke
await injected(ctx)
File "C:\Users\sandb\AppData\Roaming\Python\Python311\site-packages\discord\commands\core.py", line 132, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: 'list' object is not callable```
what does this mean?
list object is not callable
nope ive forgotten
@bot.slash_command(name="staffwarn", description="This warns the staff of galaxichost.com")
@commands.has_any_role(*role_warn)
async def staffwarn(ctx, member: discord.Member=None):
role = ['Staff Warn']
if member.roles(role):
await member.kick()
else:
await bot.add_roles(member, role)
await bot.add_roles(member, role)
channels = bot.get_channel(1089224909948977182)
await ctx.send("Reason? ")
reason = await bot.wait_for('message', timeout=3000)
await ctx.send("Time? ")
time = await bot.wait_for('message', timeout=3000)
embed = discord.Embed(title=f"Staff Member Warned: {member}", description=f"The following staff member {member} has been warned \nReason: {reason.content}")
embed.set_footer(text=f"Warned by {ctx.author} / Time: {time.content}")
await channels.send(embed=embed)
await ctx.send("Warning sent")```
#help-rules
this is the code
Learn python basics before creating bots.
Does refreshing discord fix it? Also the red one is only when a staff disables it not when you choose to disable it. If everything still works and it is just the icon pycord would not be able to do much about it.
refreshing did not fix it
how to to it with the red one?
And admin right clicks on the user and clicks server deafen
no i mean how to do it as the bot itself xD
I think it is just a permission. Edit user permissions.
no i mean how can the bot deafen it self
await ctx.guild.me.edit(deafen=True)?
Or more specifically
Models are classes that are received from Discord and are not meant to be created by the user of the library. Attributes key, url. Methods def is_animated, async read, def replace, async save, def ...
There is a difference. That will only deafen said user in that voice channel, while editing the member to be deafened would make the bot deafened guild-wide.
thanks
Hey there, is it possible to like have an embed with a button after i click it, the button should get removed and a new one get added. If yes how can i achieve that?
yea. view.add_item(button) and then edit the message to update the view.
ty
admin = bot.create_group("admin", "Admin/owner only commands")
cogs = admin.create_subgroup("cogs", "Cog-related commands")
registering a command under cogs and trying to run it gets an AttributeError: type object '_MissingSentinel' has no attribute '_get_overridden_method'
do these commands have to be registered in a special way?
this stuff is in the main file should've clarified
Here's the slash groups example.
ok yeah that works, ty
yay
i do have one question on that though, what's the reason that doesn't work first time around?
is it cause i was using the discord version instead of discord.ext.commands?
I don't have enough context here to give a definitive answer
yw
How to make it so that bot first loads the database and then set all the bot related attributes first before listening to any event ?
I know in discord.py, we use setup_hook but not sure how you do that in py-cord.
Need setup_hook. it's very good to have it
#998272089343668364 message
Can not use that..
its for a public bot and i dont use github versions for it
any other alternative available that can be done on stable version?
no stable releases yet
I don't know your bot, but if you're just using it for databases, sure
I used the example for recording audio, but I want it to loop every x seconds, however it seems If i try to loop it without disconnecting from voice first it breaks
am I missing something
Oh wair. Are you doing this in cog?the feature is only in main file
Can you elaborate how you are doing it?
is it like this?
...
recording = True
while recording:
vc.start_recording(...)
await asyncio.sleep(10)
vc.stop_recording()
Smth like that?
Yea that would block the event loop. And the bot can't heartbeat the connection to discord
Oops yeah, what should I do in the main file? 😅 I‘m normally not working with python and pycord 😂
smth on the lines of
bot = ...
@bot.listen(once=True)
async def on_ready(): # or on_connect
...
But I’m using a subclass
you can still do it
bot = MyBot(...)
@bot.listen(once=True)
async def on_ready(): # or on_connect
...
how did i not know that deco was a thing
how do i remove a message's files on edit?
quick question: When I want a slash command globaly. Do I need something extra? or do I just need to wait until the command is registered?
all you need to do is not specify a guild id
Although registering global commands can sometimes take some time. but it has always been instant for me
ok thanks
Haudi - Does pycord have the ability to create a method that will call every day/week etc?
you mean task?
Here's the background task example.
Here's the background task asyncio example.
So this example - will run every 60 seconds? I assume waiting a week just needs a bigger number.. or will something cause it to stop in between?
yea. week just needs a bigger number
you should be able to set days
Got that sorted - I want to try and update user roles using this task.. How do I.. "point" at a user without ctx.author?
I've tried using:
member = self.get_user(id)
member.add_roles(...)
you need a member object
not a user
for getting a member you need the guild
so bot.get_guild(...) followed by guild.get_member(...)
Ah, so I have guild = self.get_guild(id) for getting the roles.. I will do that then!
That makes sense, thought I could just get the user direct
This get's me the same error as before..
'NoneType' object has no attribute 'add_roles'
I can put the code here if that helps?
can you show the code?
how you get the member and guild?
async def update_membership_and_roles(self):
await self.wait_until_ready()
while not self.is_closed():
logger.info("Running role update task.")
id_list = await database_connection.get_verified_user_list()
for id in id_list:
logger.info("Attempting to update the roles of user: " + str(id))
user_info = await database_connection.get_user_verification_info(id)
membership = await rsi_lookup.get_user_membership(user_info["handle"])
rank = await rsi_lookup.get_user_rank(user_info["handle"])
# Check the org membership status and rank
guild = self.get_guild(997138062381416589)
member = guild.get_member(id)
try:
if membership == "Org Member":
await member.add_roles(discord.utils.get(guild.roles, name="BRVNS Member"))
await member.add_roles(discord.utils.get(guild.roles, name=rank))
elif membership == "Org Affiliate":
await member.add_roles(discord.utils.get(guild.roles, name="BRVNS Affiliate"))
await member.add_roles(discord.utils.get(guild.roles, name=rank))
except AttributeError as e:
logger.error(e)
await asyncio.sleep(3600) # This asyncio task runs every 1 day
Use before_loop and wait until ready
I think the docs has an example for this
.rtfm loop
discord.ext.tasks.loop
discord.ext.tasks.Loop
discord.ext.tasks.Loop.add_exception_type
discord.ext.tasks.Loop.after_loop
discord.ext.tasks.Loop.before_loop
discord.ext.tasks.Loop.cancel
discord.ext.tasks.Loop.change_interval
discord.ext.tasks.Loop.clear_exception_types
discord.ext.tasks.Loop.current_loop
discord.ext.tasks.Loop.error
discord.ext.tasks.Loop.failed
discord.ext.tasks.Loop.get_task
discord.ext.tasks.Loop.hours
discord.ext.tasks.Loop.is_being_cancelled
discord.ext.tasks.Loop.is_running
discord.ext.tasks.Loop.minutes
discord.ext.tasks.Loop.next_iteration
discord.ext.tasks.Loop.remove_exception_type
discord.ext.tasks.Loop.restart
discord.ext.tasks.Loop.seconds
when saving a vc recording, I try to run it through the python speech recognition library, but for some reason it always comes back as unintelligible. I've tried other .wav files made by elevenlabs and even from self recorded from audacity and they always come back fine. This is how i'm saving the .wav. Am I doing something wrong? The .wav sounds fine if I open it manually.
with open("recording.wav", "wb") as f:
f.write(audio.file.getbuffer())
that did it by the way thank you
