#Basic Pycord Help (Quick Questions Only)

1 messages · Page 66 of 1

thorny kindle
#

Oh Ok

#

How would i fix it?

young bone
#

channel = discord.utils.get(message.guild.text_channels, id=123)

solemn idol
#

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;
thorny kindle
young bone
#

not everytime

thorny kindle
#

Oh ok

#

Its still not working. Same error but different line

young bone
#

ok, try fetch_channel

thorny kindle
#

So just fetch_channel(id)?

young bone
#

await fetch_channel

thorny kindle
#

Nope, "fetch_channel" is not defined

young bone
#

...

#

client.fetch_channel?

thorny kindle
young bone
#

can you show the code?

full basin
#

dont tell me youre using discord.Client.fetch_channel

#

instead of an actual object

thorny kindle
# young bone 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}')
young bone
#

where is the channel =?

thorny kindle
#

Oh. I thought i had to remove it cuz of the await bit

#

But after adding it is still has an error.

full basin
#

Where did you define it

#

Because you're clearly using an instance called bot not client

frail matrix
#

can anyone help me with persistent views? i made a thread about it but i havent got much of a response

frail matrix
thorny kindle
#

Was something like client = discord.client then some stuff in brackets

limber urchin
thorny kindle
#

They are both different?

limber urchin
#

?

thorny kindle
#

Ive always had bot defined, but only defined client last night, but they are both different aren't they?

limber urchin
#

oh man...

#

Why do you need both of them?

#

There is literally no reason to have both, it will only break things

silver moat
#

client is useless since it was not initialized/connected to gateway/there's probably a better term for this.

limber urchin
#

Stick to #help-rules or find another server

thorny kindle
#

bot = commands.Bot(command_prefix=">", intents=intents)
client = discord.Client(activity=discord.Game(name='Lightbulb MC'))

meager heron
#

What would cause ctx.channel to be a PartialMessageable instead of a channel?

meager heron
#

ApplicationContext

silver moat
#

.rtfm interaction.channel

winter condorBOT
silver moat
#

Note that due to a Discord limitation, DM channels are not resolved since there is
no data to complete them. These are :class:PartialMessageable instead.

meager heron
#

It’s not a DM channel. Guild name shows up in my error log, and the command itself has commands.guild_only

proud mason
meager heron
#

How would that happen?

proud mason
#

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

frail matrix
#

How do I pass arguments from a slash command into a ui view, like a select menu?

meager heron
#

Does bot.fetch_channel automatically place the fetched channel in the cache?

limber urchin
#

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

proud mason
#

For passing options to select menus, i will subclass ui.Select and accept them in the init

frail matrix
#

ok ill try that, thanks

proud mason
#

Partial messageable is enough for sending messages if that's what you want to do

meager heron
#

Nah, I need it for checking permissions

proud mason
#

ah yes then you would need the channel object

fallen cove
#

any recommendations for a VPS that allows you to run a Lavalink server and discord bot together?

tardy kindle
#

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

proud mason
#

i think thats probably a lot too

fallen cove
#

currently on pebble host and they dont currently support it on their python discord bot hosting plan

proud mason
#

each playing track takes smth like 350KBs as per lavaplayer docs. and my avg discord bots take around 100MB of memory.

tardy kindle
#

i did that too

await client.load_extension() but it gave some error out of function

obtuse juncoBOT
tardy kindle
#

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

proud mason
#

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

tardy kindle
proud mason
tardy kindle
#

leme just do it gain it might be diff rn

tardy kindle
#

um

#

my .replit is completely different from the other .replit

#

nvm nvm

young bone
tardy kindle
#

ok i installed py-cord in a new repl cause the other repl was an older version

young bone
#

I would not use repl saisneaky

tardy kindle
young bone
#

You can install Linux and VS Code

tardy kindle
#

i know

proud mason
#

Oh btw vscode online is a better ide than replit lol

fervent cradle
#

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

proud mason
fervent cradle
#

that worked, thanks

proud mason
#

cool

ocean pumice
#
@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?
ocean pumice
#

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)

silver moat
#

slash command parameters are meant to be static, not dynamic

lethal nexus
#

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?

silver moat
#

.rtfm thread.parent

winter condorBOT
lethal nexus
#

Thanks, also is on_thread_remove when a thread is closed?

proud mason
#

Easiest and cleanest way to do it

ocean pumice
proud mason
#

Haha np

cyan quail
lethal nexus
shy crow
#

Anyone has an idea how I can do that commands can't executed in Text-in-voice anymore? Only in normal text channels

full basin
#

Read the docs

lethal nexus
#

.rtfm discord.Thread

undone mulch
#

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

silver moat
#

and you can restart just fine without ratelimits

undone mulch
silver moat
undone mulch
proud mason
#

or just in the constructor like so bot = discord.Bot(..., auto_sync_commands = False)

undone mulch
#
client = commands.Bot(command_prefix=commands.when_mentioned_or(db["prefix"]),case_insensitive=True,intents=intents, auto_sync_commands = False)```
#

Can I do this?

proud mason
#

sure

#

looks right

undone mulch
#

kk

glad remnant
#

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):
alpine kernel
#

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

proud mason
#

use view.add_item to add it

glad remnant
#

Will try Thanks

warm spire
#

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?

dusk burrow
#

hey i get this error when trying to view the "exempt_roles" property of an "AutoModRule"

lethal nexus
#

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?

full basin
#

You're literally checking if it's archived and you're trying to archive it again

full basin
tired goblet
#

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

young bone
#

maybe if you reload the cog? but Im not sure

limber urchin
young bone
tired goblet
loud holly
#

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

young bone
#

for what do you need this?

loud holly
#

recovering deleted images for my server

silver moat
young bone
#

I saw it with images

silver moat
silver moat
limber urchin
#

I'm pretty sure attachments are deleted after 1 month of not being accessed or something, not sure though

silver moat
limber urchin
#

After reading a bit it seems like attachments do stay as long as the message containing them isn't deleted

frank shale
#

Is it possible to change the logging of the botclient to a specific file?

limber urchin
#

What is "the logging of the botclient"?

frank shale
#

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

proud mason
frank shale
#

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

proud mason
#

more like "get the logger object which has the name 'discord' "

limber urchin
#

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.

proud mason
#

many modules can use a logger with the same name

glad remnant
#

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)```
limber urchin
glad remnant
limber urchin
#

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

frank shale
#

Yea read the docs, but sometimes you can get lost in the jungle and a little guidance in the right derection helps alot. Appreciated!

glad remnant
limber urchin
glad remnant
#

How to fix it properly

limber urchin
#

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

glad remnant
#
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
limber urchin
#

.tias

winter condorBOT
glad remnant
#

Yeah its not working KEK , thats why im asking if im on correct or wrong track

limber urchin
#

I can't help you if all you have is "its not working"

glad remnant
#

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 😉
heady fractal
#

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!")
proud mason
heady fractal
#

Ah

proud mason
#

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

heady fractal
#

Good idea

proud mason
#

.rtfm message_command

proud mason
#

like this

#

these cmds have ctx.message on them

heady fractal
#

Wait

#

That’s a thing???

proud mason
#

the guide covers it a bit

#

.guide

winter condorBOT
ocean pumice
#

.rtfm tasks.loop

heady fractal
#

is there a way to force integer inputs in the modals?

limber urchin
#

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.

heady fractal
#

Alrighty, thanks

distant roost
#

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

distant roost
#

Ah thx

heady fractal
#

is there an easy way to disable slash commands based on user roles?

young bone
heady fractal
young bone
distant roost
#

How do i require a channel in an command(like !channel #channel) channel:discord.channel doesn’t work

ornate current
#

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]

distant roost
#

Ah thanks i user discord.channel the whole time and it didn’t worked

limber urchin
solemn idol
#

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

cyan quail
#

all checks are a part of the extension

#

you could just do from discord.ext.commands import is_owner

green hinge
#

How can I edit this view/message without triggering the ratelimit?

await interaction.response.send_message(embed=embed, view=self.view)```
limber urchin
#

You can't edit a message without being rate limited

#

That's the whole point of a rate limit

green hinge
# limber urchin You can't edit a message without being rate limited

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)```
limber urchin
#

If you edit a message more than 5 times every 5 seconds, yes, you will be rate limited

green hinge
green hinge
# limber urchin .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?

limber urchin
#

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.

green hinge
green hinge
limber urchin
#

Editing and sending messages are not part of interaction endpoints

green hinge
limber urchin
#

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

green hinge
#

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
fervent cradle
#
 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)
limber urchin
#

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?

fervent cradle
limber urchin
#

And what is this line supposed to do?
bot_ids = ({new_ids})

limber urchin
fervent cradle
limber urchin
#

The line doesn't make any sense and won't even work

fervent cradle
#

Yeah, reliasing that now

limber urchin
#

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?

fervent cradle
#

It has been opened, Just didnt involve it in the code as the connect code had my db pass

young bone
#

?tag idw

obtuse juncoBOT
#

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.

limber urchin
limber urchin
#

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.

fervent cradle
#
    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
limber urchin
#

You're looping over an empty list, storing it in a variable, and then never use it again. What are you even doing?

fervent cradle
#

I am trying to get all the server ids, compare them to the server ids already in my database, then insert missing ones

limber urchin
#

Where are you getting all the server ids?

fervent cradle
#

Here:
new_ids = [guild_id for guild_id in bot_ids if guild_id not in db_ids]
Although obviously is wrong (Fixing atm)

limber urchin
#

Bruh, bot_ids is literally an empty list. How would looping over that get all server ids?

#

Is this even pycord?

fervent cradle
#

have u sent ur code

limber urchin
#

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?

young bone
#

how?

limber urchin
#

I can't even imagine what you would need 300 commands for

#

Guess their issue was solved 🤷‍♂️

#

deleted all messages

young bone
#

what

#

why?

limber urchin
#

god knows

#

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

young bone
limber urchin
#

I guess they were embarrassed about having a question posted in this channel doggokek

solemn idol
# cyan quail not really, why?

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

cyan quail
#

Then when slash commands were introduced, discord.Bot was added so you could have slash commands without prefix commands

solemn idol
cyan quail
#

Some stuff was moved over to the core lib like cogs, but for the most part all the other functions remain in the extension

solemn idol
#

.-. okay

cyan quail
#

That being said, essentially everything in ext.commands is still compatible with slash commands

solemn idol
#

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

cyan quail
#

Well there are permission decorators in the main lib, but that's specifically slash command default perms

limber urchin
#

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

solemn idol
#

kk

#

thanks :)

green hinge
#

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))```
solemn idol
#

What exactly do you mean with two different views? (I might be able to help you but I am not entirely sure)

grizzled sentinel
green hinge
grizzled sentinel
#

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.

leaden relic
#

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

proud mason
#

.rtfm default_perm

winter condorBOT
proud mason
#

Wait i don't think you can set that for roles. Let me check

green hinge
#

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))```
proud mason
hearty stirrup
#

so uhh is it possible to make a bot that send message like this? this from NQN

full basin
#

Webhooks

hearty stirrup
#

aight thanks

green hinge
#

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()```
solemn idol
thorny kindle
#

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.

leaden relic
solemn idol
novel jay
undone mulch
#
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?
silver moat
#

.rtfm discord.Option.min

winter condorBOT
#

Target not found, try again and make sure to check your spelling.

silver moat
#

.rtfm option.min

winter condorBOT
#

Target not found, try again and make sure to check your spelling.

tiny spire
#

What are all the types of status my bot can have?
Watching, Playing.....

silver moat
tiny spire
#

thank you 🙏

thorny kindle
thorny kindle
ocean pumice
#

What's the code to get this menu on a slash command argument?

proud mason
errant craneBOT
#

Here's the slash options example.

proud mason
#

more info here

ocean pumice
#

thanks

somber pelican
#

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

heady fractal
#

in a slash command, is it possible to send messages multiple times?

grizzled sentinel
heady fractal
#

ah so followup

grizzled sentinel
#

.rtfm ApplicationContext.followup

last mason
#

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

solemn idol
full basin
last mason
#

Won't that error if the command takes a long time to finish

#

i thought that was the point of using defer

full basin
#

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

somber pelican
#

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

solemn idol
#

Oh sorry completely missed that grumpydog
I'm not sure how to do it with built in exceptions tho.

proud mason
#

I think you are to add it using bot.listen

somber pelican
grizzled sentinel
somber pelican
#

oh bruh

#

okay thank you so much

errant craneBOT
#

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.
    """```
proud mason
somber pelican
#

i completely missed that when reading the docs

proud mason
#

Lol i had no idea that existed

grizzled sentinel
#

I looked through the code to find it. I just learned of it. I just assumed it existed.

deep wasp
#

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?

blissful hazel
#

What hosting can I use for a small bot for a server with friends with a database?

full basin
#

It has a max and min value kwarg

#

.rtfm discord.Option

errant craneBOT
#

Here's the slash options example.

deep wasp
wary rover
#

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")
green hinge
#

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()```
wary rover
green hinge
# wary rover 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.

proud mason
#

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)

wary rover
#

With a listdir you have "\" in the link.
Print your file and you will see.

#
if os.name == 'nt':
  cogPath = root.replace("\\", ".") + "." + importedFile.cogFile
elif os.name == 'posix':
  cogPath = root.replace("/", ".") + "." + importedFile.cogFile
else:
  Logger.system("OS: Unknown")
wary rover
#

He wants to make it dynamic, that's what I did too.

proud mason
wary rover
proud mason
#

.rtfm bot.load_extensions

proud mason
#

yikes

wary rover
#

Like plugins in minecraft server

proud mason
green hinge
proud mason
#

never played minecraft so dk 💀

wary rover
#

Hooooo, okay I had not seen that there was a load_extensions and a load_extension

#

prayadge sorry

#

Change channel and check

wary rover
#

Wouldn't it be easier to create a next and previous button?

proud mason
#

are you overloading the on_connect event?

#

.tag slashnoshow

winter condorBOT
#

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)?

proud mason
#

yeah you need to load cogs before running the bot

wary rover
#

load command to load your bot load command??

proud mason
#

as a workaround, add await bot.sync_commands() to the end of your /load command

green hinge
proud mason
#

yea looks right

#

haha np

wary rover
#

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.

scenic stone
#

I am planning on using "Wavelink" , If my bot reaches a lot of servers, will it get taken down?

green hinge
#

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?

wary rover
#

Give a name to a view? You define the name of your view in your code

#

Each message can have only one view.

green hinge
# wary rover 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))```
wary rover
#
import discord

view = discord.ui.View()
view.add_item(discord.ui.Button(label="Click me!"))
green hinge
wary rover
#
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

full basin
#

At this point, subclass

#

Making it difficult for no reason at all

proud mason
limber urchin
green hinge
full basin
#

Then you can access the view

wary rover
full basin
#

The hell

limber urchin
full basin
#

Why you want to edit a view from another view

wary rover
full basin
#

Isn't it easier just to have one select menu and edit the options, and pass the new edited select menu?

green hinge
#

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))
full basin
#

Or replace each select menu instead of adding them?

wary rover
#

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?

full basin
#

My point stands

green hinge
# full basin Or replace each select menu instead of adding them?

However, I have a query:

  1. type
  2. manufacturer
  3. name
  4. color
  5. 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.

full basin
#

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?

proud mason
#

from what i remember from my previous conversations with this person, yes

green hinge
full basin
#

In my opinion, this is something very difficult to achieve and you don't have the skill for it

green hinge
# full basin In my opinion, this is something very difficult to achieve and you don't have th...

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))```
full basin
#

I'm sure objects have a .view attribute

#

.rtfm Select.view

winter condorBOT
wary rover
#

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

green hinge
full basin
#

Assuming you're in your select menu callback

#

self is your select
self.view is the view your select is attached to

proud mason
#

"view.view.children"

green hinge
#

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?
full basin
#

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

green hinge
full basin
#

Then do what I said

#

Why you want to force the interaction to have a view attribute

green hinge
full basin
#

Then just use self.view

green hinge
stray bison
#

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 😅

limber urchin
#

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())
dull carbon
#

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

proud mason
#

good idea to post this in #1047189308131508306 instead

dull carbon
#

oh sorry. will move it there thank you

shell coral
#

how to get slash commands in cogs

errant craneBOT
#

Here's the slash cog example.

green hinge
#

Is Discord very slow right now? Everything in Discord is slow for me 🤔

stray bison
grizzled sentinel
stray bison
prisma atlas
#

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```
limber urchin
#

Are you using pycord v3?

prisma atlas
limber urchin
#

Then why are you trying to import it as pycord? It's still discord

prisma atlas
#

ope, my bad 😅
Still getting used to pycord here

sand nebula
#

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

full basin
#

.rtfm get_member

winter condorBOT
full basin
#

.rtfm fetch_member

undone mulch
#
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

young bone
#

looks fine for me

undone mulch
#

Says syntax error

young bone
#

where?

undone mulch
#

console

#

at that line

solemn idol
young bone
#

@undone mulch

undone mulch
#

It doesn’t even need the ApplicationContext

#

I tried without works fine

full basin
#

It's typehinting

#

It doesn't do anything but help the IDE

#

It doesn't mean you code will be faster or something

young bone
#

its still a ,

novel jay
#

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?
silver moat
#

no, you can put a cow in there for all python cares

novel jay
#

damn

#

but -> type forces your function to return a certain value... right?
Example:

def func(text) -> None:
    print (text)
silver moat
#

it definitely helps readibility

silver moat
novel jay
#

damn...

#

i really thought it forced types

#

for all these years

silver moat
#

They're just like comments

novel jay
#

like comments but it appears in the IDE type checking without you having to "look" at it?

silver moat
novel jay
#

yeah

silver moat
#

Depending on your IDE, it may somewhat enforce those Python types, but your program can still run

limber urchin
#

Don't use json as a database

hybrid flower
#

embed.add_field(name="xxx", value="I[H") # output I[H
but
embed.add_field(name="xxx", value="f\w") # output f\w
why?

hybrid flower
#

\ + [, the \ will disappear

proud mason
#

put 2 \ then

#

\[ (wrote \\[)

#

see

hybrid flower
#

why?

#

\ add other chars is will not disappear.

proud mason
#

\ 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

hybrid flower
#

when I want to output string with \, I need only to replace one with two?

proud mason
#

yes

#

somewhat like escape the escaping

#

💀

wind jay
#

hi, how could i make a voice controlled discord bot

green hinge
#

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
grizzled sentinel
wind jay
grizzled sentinel
wind jay
#

if i try to trigger like ?start mp3 i get discord.ext.commands.errors.BadArgument: Converting to "Sinks" failed for parameter "sink".

grizzled sentinel
#

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

wind jay
# grizzled sentinel I think you should just use a set sink. Im not sure if there is a reason to choo...

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"

grizzled sentinel
#

This requires Intents.voice_states.

wind jay
#

isnt it in discord.Intents.all()?

grizzled sentinel
#

👍

wind jay
# grizzled sentinel 👍

now i have

intents = discord.Intents.all()
intents.members = True
intents.voice_states = True

but its still the same problem

grizzled sentinel
#

You add the intensts to the bot correct?

#

bot = discord.Bot(intents=intents)

#

or similar

wind jay
#

do i need this scope? in dev portal?

grizzled sentinel
#

I dont think so

wind jay
# grizzled sentinel `bot = discord.Bot(intents=intents)`

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')
grizzled sentinel
#

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.

wind jay
#

nothing happens

#

no error

grizzled sentinel
#

Something is either catching the error or blocking your code than.

wind jay
# grizzled sentinel 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

grizzled sentinel
#

Becouse you are just checking if there is any voice client. Not a shared one with the user.

wind jay
#

yeah

wind jay
grizzled sentinel
#

true. Does the bot have permissions to join the VC?

wind jay
wind jay
wind jay
# grizzled sentinel true. Does the bot have permissions to join 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

grizzled sentinel
#

What does the bot respond with?

grizzled sentinel
#

connecting now..... What does it print after this?

grizzled sentinel
#

and it does not print connected to voice channel

wind jay
#

nothing more

wind jay
grizzled sentinel
#

Possibly does it work on your own PC or is it not setup there?

wind jay
undone mulch
#

Its a hashed seed. Tell Minecraft not to use json.

#

Its beneficial.

wind jay
#

@grizzled sentinel wtf

#

i found the problem

limber urchin
#

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

wind jay
undone mulch
proud mason
grizzled sentinel
#

XD, at least it eorks now

proud mason
#

Packet size changed

undone mulch
#

How do you force the memory to reload?

limber urchin
undone mulch
#

So every-time I save anything I should reload the memory directly within the function?

limber urchin
#

and close is a method, you're just referencing it as an attribute

undone mulch
#

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

limber urchin
#

You don't "update the memory". You read the values of the file into a variable, a variable is part of your memory

undone mulch
#

But then how to access it via keys

#

If you are putting it into a variable

limber urchin
#

What?

undone mulch
#

The json has 500 keys of content

limber urchin
#

So just access it by the key from your variable?

#

How else would you do it?

undone mulch
#

But then it wouldn’t update

#

Without a bot restart

limber urchin
#

What do you mean update? If you're reading a value, why would you update anything?

undone mulch
#

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.

limber urchin
#

How would the bot know to re-read the file if you manually change it?

undone mulch
#

Because I made a command that opens the file again and reloads it

limber urchin
#

Of course it's not going to update, your program has no idea the file has been changed and won't read it

undone mulch
#

And that doesn’t fix it

limber urchin
#

And how does that command look?

grizzled sentinel
#

Make sure you are actually saving the file when you manually change it.

undone mulch
#

Im on mobile right now but its standard json. Content = var.read()

limber urchin
#

Well it's impossible to say what's wrong without seeing the code.

#

Could be anything

undone mulch
#

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.

limber urchin
#

But you never read anything into your edb variable there

undone mulch
#

Idk what you mean

#

Example?

limber urchin
#

Why do you need an example?

#

Do you know how to read a value to a variable?

heady fractal
#

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

limber urchin
#

.rtfm fetch_member

limber urchin
#

Users aren't part of servers, members are

heady fractal
#

ah so i have to get the guild and get the member from it

limber urchin
#

yes

heady fractal
#

got it, thanks

drowsy python
#
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

limber urchin
#

?tag requests

obtuse juncoBOT
#

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

drowsy python
#

this is very likely something inexpicably small and it jsut went over my head

limber urchin
#

And you don't pass self to class methods

#

That is passed automatically since you're calling self.

drowsy python
#

oh ok now that makes more sense

#

ty

#

i'll do that aiohttp bit too, good insight

heady fractal
#

is there a limit on how much text can be in an embed

heady fractal
#

so there can be 25k characters per embed when using field values

#

if every field value is used

limber urchin
#
  • the description
#

and title and footer

heady fractal
#

yep

proud mason
heady fractal
#

ah

#

so no matter what, max limit is 6k

proud mason
#

yea

heady fractal
limber urchin
#

How do you have a url over 6k characters?

proud mason
#

use url shortners?

heady fractal
limber urchin
#

You could always send them as separate messages I guess, or like mentioned, use a URL shortener

heady fractal
#

i think i'll just leave them unformatted

limber urchin
#

It's a Discord limitation, not much we can do about it unfortunatelyNPCMechanicShrug

heady fractal
#

yeh

#

or an option would be to send multiple embeds

proud mason
heady fractal
#

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

tired goblet
#

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?

proud mason
tired goblet
#

okay

#

thanks!

ocean pumice
#

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?

#

Oh yeah yeah it works like that

#

Thanks

tired goblet
#

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'))

full basin
tired goblet
proud mason
#

Are you taking longer than 3 seconds to respond

tired goblet
#

But after rewriting literally the same code, it seems to be gone lol

proud mason
#

Oh huh lmao

fervent cradle
#

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?

#

do not pay attention to the file names CAPTCHA.png and code.png, the result will be the same

fervent cradle
#

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

proud mason
#

btw why not use BytesIO instead of storing the image to disk?

fervent cradle
proud mason
# fervent cradle 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
fervent cradle
fervent cradle
obtuse juncoBOT
#
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)```
fervent cradle
#

yes

young bone
#

why do you open it?

proud mason
fervent cradle
#

yeah, PIL

proud mason
#

the file name you set in discord.File should match with what you put in the url

fervent cradle
#

Ok, I will take a look

proud mason
#

when using with open, the file gets closed when the code inside the block is executed

fervent cradle
proud mason
#

yea that wont work

fervent cradle
proud mason
#

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

fervent cradle
#

oksss

proud mason
fervent cradle
fervent cradle
#

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?

blissful hazel
errant craneBOT
#

Here's the persistent example.

fervent cradle
#

Okay, why do I need a custom id?

limber urchin
#

How else is the bot going to know which button to run the view events on?

distant roost
#

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

limber urchin
#

.rtfm InputText.required

winter condorBOT
limber urchin
#

It's literally in the docs

distant roost
#

Than i searched at the wrong page

shut hedge
#

hey, I am having trouble installing pycord. trying the example bot it fails to import discord

copper dew
obtuse juncoBOT
#

The library name is py-cord not pycord

silver moat
#

you would also have to restart your terminal/IDE after installing

shut hedge
#

I followed directions a little to well

silver moat
shut hedge
#

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 .....

silver moat
#

ic

shut hedge
#

I am tired from college so my 2 brain cells were fighting for 3rd place on that one

silver moat
#

it happens

shut hedge
#

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.

novel jay
#

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

warm grotto
#

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

silver moat
#

update

#

?tag install

obtuse juncoBOT
#
  1. 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

solemn idol
proud mason
#

that is what you are looking for

#

2nd one

dry urchin
#

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

obtuse juncoBOT
#
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)```
dry urchin
#

Ah dumb me sorry and thanks a lot!

fervent cradle
#

How to get a user's account creation date in hours?

livid wolf
#

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
proud mason
winter condorBOT
proud mason
#

2nd one

livid wolf
#

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}`")
livid wolf
#

Where???

limber urchin
#

server.status is not a method

#

it's an attribute

livid wolf
#

Wait, lemme see

livid wolf
limber urchin
#

And please read your errors in the future, it tells you exactly what's wrong

dry urchin
#

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

winter condorBOT
# dry urchin Hey there again! I want/need to edit an message/response from within an sync fun...
rare ice
#

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.

dry urchin
rare ice
proud mason
proud mason
dry urchin
proud mason
dry urchin
#

but ill try to write it down better

soft girder
#

Is it possible to make it so that only numbers can be entered in the modal?

magic pendant
#

Using the type hint TextChannel does not include announcement channels to be referenced in the slash command, what type should I use?

proud mason
proud mason
errant craneBOT
#

Here's the slash options example.

proud mason
#

.rtfm Option

proud mason
#

1st one

magic pendant
proud mason
#

.rtfm news

proud mason
#

Forgot to tell that lol

magic pendant
proud mason
novel jay
novel jay
magic pendant
soft girder
green hinge
#

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
strange beacon
green hinge
# strange beacon Your likely triggering multiple exceptions along the way, the one your code trig...

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()```
green hinge
# strange beacon 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
thorny bloom
#

What is the equivalent for setup_hook in pycord (migrating from discord.py)?

fervent cradle
#

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

proud mason
thorny bloom
#

I read something about on_hook but doesn't seem to exist/ work

proud mason
proud mason
silver moat
thorny bloom
grizzled sentinel
#

master branch
It is only on the latest github version

proud mason
#

##1801 can allow you to do what setup hook does

errant craneBOT
proud mason
#

im not sure when that would be merged tho

thorny bloom
proud mason
#

pip install -U git+https://github.com/Pycord-Development/pycord

#

it got added yesterday

thorny bloom
limber urchin
#

If your docker container doesn't pull the latest master you won't get the updated version

#

aka the command that Om sent

proud mason
proud mason
thorny bloom
#

yeah

proud mason
#

can you show the py-cord line in the requirements file?

thorny bloom
#

git+https://github.com/Pycord-Development/pycord

coarse cargo
#

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.

silver moat
#

Is your bot in all of those guilds?

green hinge
#

Can I use custom server emojis in an embed?

silver moat
green hinge
green hinge
# silver moat yes

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...
silver moat
#

¯_(ツ)_/¯

limber urchin
#

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

chrome skiff
#

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

green hinge
chrome skiff
#

and shoulndt it look like this?

limber urchin
obtuse juncoBOT
#

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

drowsy python
#
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

chrome skiff
#

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

shell coral
#
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?

full basin
#

list object is not callable

shell coral
#

i dont understand what that means

#

ive been gone for a while

full basin
#

This is a basic python error

#

Do you even know what a list is?

shell coral
#

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")```
full basin
#

#help-rules

shell coral
#

this is the code

full basin
#

Learn python basics before creating bots.

shell coral
#

i know it

#

ive just forgotten

#

but thanks for your response

grizzled sentinel
chrome skiff
#

how to to it with the red one?

grizzled sentinel
#

And admin right clicks on the user and clicks server deafen

chrome skiff
#

no i mean how to do it as the bot itself xD

grizzled sentinel
#

I think it is just a permission. Edit user permissions.

chrome skiff
silver moat
grizzled sentinel
#

Or more specifically

silver moat
chrome skiff
coarse cargo
#

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?

silver moat
coarse cargo
#

ty

drowsy python
#
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?

errant craneBOT
#

Here's the slash cog example.

#

Here's the slash cog groups example.

drowsy python
#

this stuff is in the main file should've clarified

errant craneBOT
#

Here's the slash groups example.

drowsy python
#

ok yeah that works, ty

silver moat
#

yay

drowsy python
#

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?

silver moat
#

I don't have enough context here to give a definitive answer

drowsy python
#

understandable

#

ty again tho, and have a good day/night

silver moat
#

yw

wild socket
#

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

silver moat
#

#998272089343668364 message

wild socket
silver moat
#

no stable releases yet

wild socket
#

okay...
what abt i use bot.start()?

#

will that work ?

silver moat
#

I don't know your bot, but if you're just using it for databases, sure

violet bear
#

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

proud mason
proud mason
violet bear
#

hmmmmm

#

i was not using asyncio sleep

#

i was using time maybe thats why

proud mason
#

Yea that would block the event loop. And the bot can't heartbeat the connection to discord

thorny bloom
proud mason
proud mason
#
bot = MyBot(...)

@bot.listen(once=True)
async def on_ready(): # or on_connect
    ...
verbal marten
#

how did i not know that deco was a thing

lime lotus
#

how do i remove a message's files on edit?

fervent cradle
#

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?

proud mason
#

Although registering global commands can sometimes take some time. but it has always been instant for me

fervent cradle
#

ok thanks

wicked helm
#

Haudi - Does pycord have the ability to create a method that will call every day/week etc?

errant craneBOT
#

Here's the background task example.

wicked helm
#

Yes, yes I do

#

I had forgotten the name 😄

errant craneBOT
#

Here's the background task asyncio example.

wicked helm
#

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?

proud mason
wicked helm
# young bone 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(...)

proud mason
#

not a user

#

for getting a member you need the guild

#

so bot.get_guild(...) followed by guild.get_member(...)

wicked helm
#

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

wicked helm
young bone
#

how you get the member and guild?

wicked helm
#
    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
proud mason
proud mason
#

.rtfm loop

violet bear
#

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())
violet bear