#Basic Pycord Help (Quick Questions Only)

1 messages Β· Page 65 of 1

limber urchin
#

read #help-rules

soft girder
#

!!!

#

I know all about you tell but....

#

All what google translate for me it's .....

limber urchin
#

Then you need to find a place where they can speak your language. This server is English only, so if you don't understand English we can't help you.

limber urchin
#

No

proud mason
#

not really blobpain
start by finding general coding servers, then try to find people who speak your language

#

ask these people if they know such server

red geyser
#

Im using slash commands, they work, however everytime i use it in discord, i get the message "The application did not respond"

grizzled sentinel
#

Ctx.respond is for responding to slash commands
Ctx.send is just for sending a message like sending a second message.

red geyser
#

ah I see, thankyou

#

Is there any way to set a timeout for it, just incase it still cannot respond?

young bone
#

use ctx.defer()

fervent cradle
#
@client.slash_command(name="purgemembers", description="Purge all members with no roles.")
async def kicknorole(ctx):
    members = ctx.guild.members
    for member in members:
        test = len(member.roles) == 1
        if test:
            await member.kick()
            await ctx.respond(f"Done! Successfully kicked all members with no roles.", ephemeral=True)
            #await ctx.send(member.name)
    else:
      await ctx.respond(f"There is no members with no roles left.", ephemeral=True)```
#

How do I add a kick counter?

limber urchin
#

what do you mean by "kick counter"?

full basin
#

Om answered you in the thread

fervent cradle
limber urchin
fervent cradle
#

I was told to, set count = 0 before the loop and add 1 to it after each kick

#

But Idk how to.

limber urchin
#

That's extremely basic Python

#

Which you are expected to know before using pycord, read #help-rules

fervent cradle
limber urchin
#

?tag lp

obtuse juncoBOT
#
fervent cradle
limber urchin
#

We won't help you if you don't know OOP and async-await concepts in Python

#

Just searching on Google and copying code won't help you learn anything

fervent cradle
#

I don't want to learn anything I just need it functioning in my serve

young bone
limber urchin
#

And we don't want to help people who refuse to follow rules NPCMechanicShrug

#

If you don't want to learn, programming was the wrong choice of hobby for you my friend

fervent cradle
#

It wasn't a hobby to begin with. Just need a bot for my personal server.

#

No other bots have that feature

limber urchin
#

Unfortunately for you, making a bot requires Python knowledge

young bone
fervent cradle
#
async def button_callback(interaction:discord.Interaction):
        ticket_category = discord.utils.get(interaction.guild.categories, name='Tickets')
        channel = await ctx.guild.create_text_channel(f"ticket-{format(ticketNum, '04d')}", category=ticket_category)
        await channel.set_permissions(interaction.user, overwrite=overwrite)

        await interaction.response.send_message(f"Created Ticket at {channel.mention}", ephemeral=True)
        modal = ticketModal(title="Create a Ticket")
        modal.variables(interaction.user, channel)
        await channel.send_modal(modal)

How can i get the modal to work with a button

fervent cradle
#

AttributeError: 'TextChannel' object has no attribute 'send_modal'

#

this is the error btw

soft girder
#

why?

limber urchin
#

self.use??

fervent cradle
#

i was also confused on the self.use

soft girder
limber urchin
limber urchin
soft girder
#

ok

limber urchin
soft girder
#
class RoleButton(discord.ui.View):
    def __init__(self,author):
        super().__init__(timeout=None)

        self.user=author


    @discord.ui.button( label="Add role",custom_id="button-101",emoji="πŸ“",style=discord.ButtonStyle.success,row=1)
    async def reg2_button_callback(self, button: discord.ui.Button, interaction):
        #await interaction.response.send_message(f"{self.user}")


        guild = interaction.guild_id
        msg = interaction.message
        user = interaction.user

        if interaction.user.guild_permissions.administrator==True:           
            
            if guild == 944934277777326090:
                guildid = bot.get_guild(944934277777326090)
                role=guildid.get_role(1064856142259425350)
                await self.user.add_roles(role,reason=None, atomic=True)#here error
            if guild == 769823680695107594:
                guildid = bot.get_guild(769823680695107594)
                role=guildid.get_role(776528911269363775)
                await self.user.add_roles(role,reason=None, atomic=True)



            await interaction.response.send_message(f"{self.user}")

        else:
            pass       
fervent cradle
#

and he doesnt want to get the two mixed up

soft girder
#

ctx.author from class

limber urchin
fervent cradle
limber urchin
limber urchin
limber urchin
soft girder
#

I take the author's ID and drag it to the class with the button

limber urchin
#

And why are you passing the ID? Don't you just want a member object???

fervent cradle
#

I have a function which replies to user when the user dms the bot, but why am I receiving this exception?
discord.errors.HTTPException: 400 Bad Request (error code: 50007): Cannot send messages to this user

limber urchin
#

Because the bot can't send messages to the user

#

It probably means the user has their privacy settings turned up

fervent cradle
#

no, i have my dms turned on (it's me who is trying to dm)

limber urchin
#

and this?

fervent cradle
#

yes

limber urchin
#

You could just recursively loop over all folders and look for .py files

proud mason
#

Or just use bot.load_extensions which does this all automatically

#

Notice the s at the end

#

.rtfm load_extensions

limber urchin
#

well, if load_extensions works that'd be 100x better than doing it youself

ornate current
#

need help with quart_discord, it says discord.Permission is not an attribute. I understand but how do i fix this??

#

should i do something like discord.Permission = discord.Permissions

#

would that work?

shy crow
#

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

night slate
#

hello everyone i have a question how can i do both slash and default commands in my bot? For example, i have !ping and /ping

client = discord.Bot(intents = intents)

night slate
#

ty

night slate
#

for example /ping and !pong

silver moat
#

just use a normal @bot.command()?

night slate
#

but then how do I initialize the client, because the client variable stores discord.Bot

#

and you can't enter command_prefix there

#

sorry for the stupid question)

silver moat
#

read the guide please

hybrid flower
#

can I use Paginator in on_message event? paginator.respond function require interaction as first param, but there is no interaction in on_message event.

night cargo
#

im getting an error that says

discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In 8.options.5.options.1.choices: Must be 25 or fewer in length.

how do I find out what In 8.options.5.options.1.choices is?

minor pulsar
#

can someone help me please, I'm trying to make a message ephemeral, it has buttons and will edit the message when clicked. My problem is that it says this interaction has already been responded to before whenever i click the buttons next and previous.

ornate current
#

discord-ext-ipc has buncha errors, any alternatives?

#

or should i just switch to js lol

proud mason
#

Some group cmd with 5 subcommands?

proud mason
#

.rtfm paginator.send

winter condorBOT
proud mason
#

.rtfm get_context

proud mason
#

thats the only workaround ik of blobpain

#

ill try if i can make a pr for a better solution

hybrid flower
#

and then have a new problem for me, my bot send a image file attachment and a embed in a single message, how can I let the embed before files?

proud mason
#

i dont think you can control that. it should be a discord limitation

hybrid flower
#

tyvm

proud mason
#

np!

ornate current
#

is it the problem with quart or ipc

proud mason
ornate current
#

kk

#

support server is inactive

#

welp

fervent cradle
#

Uh so, what's wrong in the code?

    async def on_message(message):
        if message.startswith('!mail'):
            await message.author.send("Hello World!")
        else:
            return

Exception: AttributeError: 'Message' object has no attribute 'startswith'

limber urchin
#

It's message.content to get it as a str

fervent cradle
#

oh

#

fixed ty

#

Anyways I have 3 buttons that have the same callback, any way to implement the callback function without having to declare it for every single view?

limber urchin
#

You can see them as attributes by just looping over them

for button in my_view.items:
    button.callback = my_func
#

obv not exactly like that, but you get the idea

proud mason
#

You can rather subclass discord.ui.Button

#

As that would be much cleaner

#

@fervent cradle

fervent cradle
#

Can you send me an example?

minor pulsar
proud mason
errant craneBOT
#

Here's the button roles example.

fervent cradle
#

How to remove the button after it was clicked?

limber urchin
#

.rtfm clear_items

winter condorBOT
lime lotus
#

can i send a modal in response to a button callback?

young bone
lime lotus
#

can I send it through the Interaction that is passed in the callback?

#

found it, sorry

vale heath
#

A quick question can we change the variable name to show differently in bridge ?

cyan quail
#

elaborate?

vale heath
#

like im using

async def abc(self, ctx, arg: int = "None", arg2: int = "None", arg3: float = "None"):

insted of arg i wnat people to see it as name when they use slash

#

while it being as bridge

cyan quail
#

why not just change the parameter name then

vale heath
#

have to change alot in code hehe

cyan quail
#

eh any half decent ide will do it for you

#

well alternatively you could use arg: type = discord.Option(name="...", ...)

vale heath
#

im using @option but its not working

cyan quail
#

don't use it then, use the Option object

limber urchin
vale heath
proud mason
#

It even is a "None" string and not NoneType πŸ’€

blissful hazel
#

^^

#

beautiful

hushed ledge
#

One message removed from a suspended account.

limber urchin
#

No

slow halo
#

Do i need a "On_Connect()" Function to sync the Slash-Commands or does the API it on its own?

limber urchin
#

What do you mean by that? on_connect already exists on all bot instances

full basin
#

The event syncs the commands. If you override it, you must call the sync commands function in it

slow halo
#

okay, so i dont need that Stuff or "bot.sync_commands()" in my Script....that was all that i needed to know πŸ˜›

#

Thank you πŸ™‚

limber urchin
#

It's in the docs

slow halo
#

i just wasnt sure^^

#

okay, looks like i really need some glasses xD

young bone
hushed ledge
#

One message removed from a suspended account.

silver moat
full basin
#

You can look for old messages lol. There was an exact same case

proud mason
fervent cradle
#

how can i reply to an on_message event

#

like instead of sending it to the channel how can i make it reply directly

fervent cradle
#

wtf

#

i swear i tried that

fervent cradle
#

AttributeError: 'Bot' object has no attribute 'slash_command'. Did you mean: 'add_command'?

fervent cradle
silver moat
#

pip list in terminal and show output

fervent cradle
silver moat
#

so a full list is preferrable

fervent cradle
#

2.2.2

silver moat
#

yeah uninstall discord and py-cord, then reinstall py-cord and restart IDE/terminal

fervent cradle
#

@silver moat
im getting

ModuleNotFoundError: No module named 'discord'```
#

nvm i fixed it

tiny spire
errant craneBOT
tiny spire
#

I also want to create some if statements before a few of the commands so I can enable/disable commands from the config, would this work?

if config["Davinci"]:
  @client.slash_command(description="OpenAI Davinci Integration.")
  @option("query", description="Your message to the bot")
  async def gpt(ctx: discord.ApplicationContext, query: str):
    await Models.davinci(query, ctx)```
#

config["Davinci"] being a boolean

stuck canopy
tiny spire
#

I don't want it to show on the slash command list

stuck canopy
#

you cant do:

if value:
  def gpt():
    ...
...
#

thats just not how programming wroks

tiny spire
#

k

stuck canopy
#

but realistically I am not sure.

tiny spire
#

i'll try both methods and see if either of them work

stuck canopy
#

I remember learning C I tried this lol

tiny spire
#

i'm just learning python so I really have no idea

#

I came from discord.js

stuck canopy
#

Ah gotcha

tiny spire
#

glad I escaped that hell πŸ™

#
#/purge
@client.slash_command(description="Clears all messages.")
async def purge(ctx, channel: discord.TextChannel):
  await Messages.purge(ctx, channel)```
#

this shows a channel dropdown for me

stuck canopy
#

this weird bro

tiny spire
#

change

    async def channel(ctx: discord.ApplicationContext, chnl: discord.abc.GuildChannel):```
to
```python
     async def channel(ctx: discord.ApplicationContext, chnl: discord.TextChannel):```
and see if that works
stuck canopy
#

Yeah lol I just tried it doesnt

tiny spire
#

huh

#

idk then lol

stuck canopy
#

Ah awesome

#

Anyways reposting πŸ˜„

#

Also does anyone know why this doesn't show a channel dropdown?

@welcome.command() 
    async def channel(ctx: discord.ApplicationContext, chnl: discord.abc.GuildChannel):
        settings[ctx.guild.id]["welcome"] = chnl.id
        save_settings()
        embed = discord.Embed(title="Welcomer Channel Set!",
                              description=f"The welcomer channel has successfully been set to {chnl.mention}.")
        await ctx.respond(embed=embed, ephemeral=True)
tiny spire
#

ask ChatGPT lol

stuck canopy
tiny spire
#

it fixes everything for me shrug

#

my bot basically wrote itself

stuck canopy
#

which is a discordpy thingy i think

tiny spire
#

yeah it did that to me too

#

bing has internet access so it's up to date if you want to try that

stuck canopy
#

rather not use microsoft lmao

tiny spire
#

based

#

can't even gaslight bing AI smh

proud mason
tiny spire
proud mason
#

cuz discord.TextChannel should be able to do it

stuck canopy
#

bruv I should be on the latest

proud mason
#

wrong library πŸ˜…

#

?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

proud mason
#

py-cord (with a -)

#

also, try using the @option decorator

stuck canopy
#

bruh

#

bro....

#

I am a moron.

errant craneBOT
#

Here's the slash options example.

stuck canopy
#

its suprising that most has worked so far

proud mason
#

dang lmao

#

make sure to uninstall that, py-cord and all other discord related libraries. and then reinstall py-cord

stuck canopy
#

Yup

#

still

proud mason
#

hmm

proud mason
stuck canopy
#

I am

#

I'll show you all the code, I feel like something is really wrong.

#
class Util(commands.Cog, name="util"):
    def __init__(self, bot):
        self.bot = bot

    @commands.Cog.listener()
    async def on_member_join(self, member: discord.Member):
        if settings[member.guild.id]["welcome"] != None:
            embed = discord.Embed(title=f"{member.name} has joined {member.guild.name}!",
                                  description=f"Welcome {member.mention} to our server.")
            embed.set_author(name="TempleKeeper",
                             icon_url="https://cdn.discordapp.com/attachments/965777279106023484/1085498240155271229/tumblr_fa7b131254d314e604ac776fa7309bb9_7cc9b312_540.jpg")
            embed.add_field(name="⏱ Account Created", value=f" <t:{int(member.created_at.timestamp())}:R> ", inline=True)
            embed.add_field(name="πŸ“ˆMember Count", value=f"{member.guild.member_count}", inline=True)
            embed.set_footer(text=randomMsg())
            embed.set_thumbnail(url=member.display_avatar.url)

            channel = client.get_channel(1085439086103380003)  # Replace with the ID of your welcome channel
            await channel.send(embed=embed)

    welcome = discord.SlashCommandGroup("welcome", "Commands related to welcoming.")

    @welcome.command()
    @discord.option(
        "channel",
        Union[discord.TextChannel],
        description="Select a channel",
    )
    async def channel(ctx: discord.ApplicationContext, channel):
        settings[ctx.guild.id]["welcome"] = channel.id
        save_settings()
        embed = discord.Embed(title="Welcomer Channel Set!",
                              description=f"The welcomer channel has successfully been set to {channel.mention}.")
        await ctx.respond(embed=embed, ephemeral=True)



def setup(bot):
    bot.add_cog(Util(bot))
stuck canopy
proud mason
stuck canopy
#

That was the example lol

proud mason
#

oh huh

stuck canopy
#

I mean I can get rid of the union part

#
    @welcome.command(guild_ids=servers)
    @discord.option(
        "channel",
        discord.TextChannel,
        description="Select a channel",
    )
    async def test(ctx: discord.ApplicationContext, channel):
        settings[ctx.guild.id]["welcome"] = channel.id
        save_settings()
        embed = discord.Embed(title="Welcomer Channel Set!",
                              description=f"The welcomer channel has successfully been set to {channel.mention}.")
        await ctx.respond(embed=embed, ephemeral=True)
#

even this, I still cant get it working

soft girder
#
@commands.guild_only()
    @commands.has_permissions(administrator =True)
    @in_game.command(name='edit', description='Registration command.',guild_ids=[944934277777326090,769823680695107594])
    @option("function", description="Pick a function!", autocomplete=get_function)
    async def autocomplete_example(self,ctx: discord.ApplicationContext,function: str,team:str):
        picked_function = ctx.options["function"] #error here
        if picked_function == "remove":
            cursor.execute(f"DELETE FROM teamlist WHERE team_name = '{team}'")
            await ctx.respond(f"Team {team} deleted.",ephemeral=True)
            db.commit()
        elif picked_function == "move to vip slot":
            cursor.execute(f"UPDATE teamlist SET place = 'vip' WHERE server_id = {guild} AND team_name={team}")
            await ctx.respond(f"Team {team} now in vip slot.",ephemeral=True)
            db.commit()
        else:
            cursor.execute(f"UPDATE teamlist SET place = 'classic' WHERE server_id = {guild} AND team_name={team}")
            await ctx.respond(f"Team {team} now in classic slot.",ephemeral=True)
            db.commit()
``` What's wrong?
#

error : 'NoneType' object is not subscriptable

young bone
#

Read the error

limber urchin
soft girder
#

kek πŸ––

limber urchin
#

Is that an excuse for being lazy?

soft girder
limber urchin
#

And you keep coming back to ask questions here, even after being told to learn Python before making a bot

#

Your error is very basic

soft girder
somber pelican
#

is there a way for ApplicationCommandInvokeError exceptions to just be the base exception instead?

for example, I would like for the exception to be an instance of InvalidXml, instead of ApplicationCommandInvokeError

somber pelican
#

is this not possible...? i've searched the docs to no avail

proud mason
somber pelican
#

i'm catching the exception in cog_command_error

proud mason
#

Is that a custom error class?

somber pelican
#

it's a custom exception class inherting from Exception

proud mason
#

If yes, then you should subclass Exception

somber pelican
#
class InvalidXml(Exception):
    pass
proud mason
#

Oh nice

#

Yeah so the App cmd part is displayed as extra text to know where the error is from. If you want to handle it, then error should be an instance of InvalidXml

somber pelican
#

yea, i'm asking how i convert ApplicationCommandError into an instance of InvalidXml

proud mason
#

The error should already be an instance of InvalidXml iirc. Can you check it?

somber pelican
#
    async def cog_command_error(self, ctx: ApplicationContext, exception: Exception) -> None:
        if isinstance(exception, InvalidXml):
            embed = await build_embed(0xff0000, "Error", """
            Invalid data was returned from the API, or there was an error parsing it.
            Please remove "account-verifier" from your friends list or friend requests, and try again.
            """)

        else:
            [title, description] = await return_proper_exception(exception)
            embed = await build_embed(0xff0000, title, description)

            self.bot.logger.error(f"{title}: {description}", exc_info=True)

        return await ctx.respond(embed=embed)

here's my cog_command_error code

#

the error is instance of ApplicationCommandInvokeError

proud mason
#

Hmm

#

That is weird. Can you inherit from ApplicationCommandInvokeError instead and see what happens?

somber pelican
#

sure, just one second

#

@proud mason
inherting from ApplicationCommandInvokeError throws TypeError: ApplicationCommandInvokeError.__init__() missing 1 required positional argument: 'e'

editing my exception to

class InvalidXml(ApplicationCommandInvokeError):
    def __init__(self):
        super().__init__(self)

worked tho! tysm!!

proud mason
#

Oh nice

fervent cradle
#

This is my directory tree:

.
β”œβ”€β”€ bot/
β”‚   └── f1/
β”‚       └── cmd.py
└── main.py

I have a cog (cmd.py) inside the f1 folder, but why can't I load it using bot.load_extension('bot.f1.cmd') in main.py?

fervent cradle
#

yes i am

young bone
#

and what is the error?

fervent cradle
#

wait it's working now

#

nevermind

analog trellis
#

hi can someone please tell me why my chat bot isnt working?

limber urchin
analog trellis
analog trellis
limber urchin
analog trellis
young bone
limber urchin
young bone
#

Also that ^

analog trellis
#

i am sorry i just dont know how to send the code

#

i need help with that

limber urchin
#

How do you not know how to send code? Do you know how to copy and paste text on your computer??

analog trellis
#

yes of course i do

limber urchin
#

and what's stopping you from copying and pasting your code here?

analog trellis
#

oh okay one second

#

#question:answer

qna = {
"hi":"hey",
"how are you":"I am fine",
"what is your name":"My name is Steve",
"how old are you":"I am 20 years old",
}

while True:
qs = input()

if(qs == "quit"):
    break

else:
     print(qna.get(qs))
#

thats my code although when for example i press 'hi' on the terminal its not working

grizzled sentinel
#

are you typing hi (space) or just hi

analog trellis
#

hi without space

limber urchin
grizzled sentinel
#

Yeah, i will need to see the whole file to determine more

analog trellis
limber urchin
analog trellis
#

i am still learning you see

limber urchin
#

Still learning how to use a computer? Dude.. copy and paste

young bone
grizzled sentinel
analog trellis
limber urchin
analog trellis
#

i mean did i do the code correct?

grizzled sentinel
#

It looks correct

analog trellis
#

great then why it can not work?

limber urchin
analog trellis
#

okay Spaxter i will

solemn idol
#

Why do my commands inside of my cog still seem to be loaded whenever I unload them using client.unload_extension? (client is the same as bot as most of you prefer to use, client=commands.Bot(intents=intents etc.))

My terminal shows that it has successfully been unloaded and my help command (which is mostly automatically generated using client.get_cog() and cog.get_commands() ) doesn't show my commands and the cog in general as being loaded anymore. I am using debug sync to my dedicated guild but my commands still seem to be active and I have no idea why. Any help is appreciated :)

grizzled sentinel
#

you need to sync commands after unloading

limber urchin
#

Unloading a cog won't unregister the commands

grizzled sentinel
#

However it still does not work that great. for some reason

solemn idol
#

So you're saying even when I unload my cog the commands still completely work (what I mean with work is that whenever I do for example /meme it still gives me a meme, even though the cog containing the command is unloaded).
To prevent that I need to resync basically everything in that cog after loading / unloading a cog?

grizzled sentinel
#

after unloading you should run self.bot.sync_commands() Show your code for unloading the cog as well please.

analog trellis
# grizzled sentinel It looks correct
#question:answer

qna = {
    "hi":"hey",
    "how are you":"I am fine",
    "what is your name":"My name is Steve",
    "how old are you":"I am 20 years old",
}

while True:
    qs = input()

    if(qs == "quit"):
        break

    else:
         print(qna.get(qs))
    
#

thats my code

#

forchatbot

solemn idol
#
    @commands.is_owner() 
    @discord.slash_command(name = "unload", description = "Unloads a category.")
    async def unload(self, ctx, category: Option(str, required = True)):
        try:
            client.unload_extension(f'cogs.{category}')
            print(colorama.Fore.RED + f'Unloaded : {category}')
            await ctx.respond(f':white_check_mark:  **Unloaded {category}!**  :white_check_mark:')
        except:
            em = discord.Embed()
            em.title = ('Invalid category!')
            em.description = (f'This category does not exist or has already been unloaded.')
            em.color = em_red
            await ctx.respond(embed = em)

This command is in a cog called developer.py too btw. idk if that's of any relevance

#

I mean I'll try

grizzled sentinel
young bone
analog trellis
analog trellis
limber urchin
grizzled sentinel
#

How is your code printing I'm sorry, I dont understand. Can you please try again? if it is not in your code?

young bone
#

^

grizzled sentinel
solemn idol
#

Yup

#

the print statement is for my terminal

#

and the client.unload_extension unloads the cog I selected

fervent cradle
#

Is there any way I can delete the bot's message that is sent in dm?

solemn idol
grizzled sentinel
solemn idol
limber urchin
analog trellis
solemn idol
#

I believe you could just auto delete it using
await channel.send('this message will delete after 3 seconds', delete_after = 3)

solemn idol
limber urchin
analog trellis
analog trellis
solemn idol
#

or... do I just use remove_cog

grizzled sentinel
#

That should work

#

Tell me if it does

solemn idol
#

I'll try it later gtg rn, I'll let you know. Thank you very much for your help :)

true pewter
#

I want to make a command that allows to choose if the message is going to be done by a channel or by private message.

So the idea is that in the first option they choose the place, if it is going to be by private or by channel and depending on what they have chosen, the second option will choose the user or the channel. Ns if anyone has tried it or not. feedback?

class SendMessage(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
    
    async def get_destiny(self, integration: AutocompleteContext):
        if integration.options["select"] == "User":
            return [discord.Member]
        elif integration.options["select"] == "Channel":
            return [discord.TextChannel]
        else:
            return []

    @discord.slash_command(name="send")
    async def mention(self, ctx:  discord.ApplicationContext, select: str = Option(choices=["User", "Channel"]),
                      destiny: str = Option(autocomplete=get_destiny)):

        if select == "User":
            await ctx.send(f"Hey {destiny.mention}")
limber urchin
#

Do you have an issue or do you just want feedback on the code?

fervent cradle
#

Can someone link me a quick reference or example to unpack_audio
The docs are really vague

thorny kindle
#

How would i add a timestamp to my embed? Right now i am trying to use

timestamp=datetime.now()
#
    embed = discord.Embed(title='Help', description=f'{helpdesc1}\n {embedchannels}', color=discord.Color.yellow())
    embed.set_footer(text='Lightbulb MC')
    embed.set_author(timestamp=datetime.now())
limber urchin
#

set_author does not take a timestamp?

thorny kindle
#

Oh?

young bone
limber urchin
#

Where do you see that in the docs?

thorny kindle
#

I didnt see anything in the docs. This is all i found:

silver moat
#

.rtfm embed.timestamp

winter condorBOT
limber urchin
thorny kindle
young bone
thorny kindle
limber urchin
#

What makes you believe that's a parameter of set_author? Thats just an attribute

thorny kindle
#

Idk

thorny kindle
#

How would i make this disable? I cant have the 2 interaction.reponse. with it but without it it wont disable. If i remove the edit one it wont disable, If i remove the send one the interaction fails as it has nothing to edit.

    @discord.ui.button(label="Server IP", style=discord.ButtonStyle.primary, emoji='🎈')
    async def servip_callback(self, button, interaction):
        embed = discord.Embed(title='Server IP', description='To play on the server, Use the version **1.19.3** and the IP: play.lightbulbmc.xyz', color=discord.Color.random())
        embed.set_footer(text='Lightbulb MC')
        button.disabled = True 
        button.label = "No more pressing!" 
        await interaction.response.send_message(embed=embed)
        await interaction.responce.edit_message(view=self)
limber urchin
#

.rtfm edit_original_message

winter condorBOT
solemn idol
#

also what is the difference between unloading an extension and remove cog?

dry echo
#

how can i pin a thread in a forum like here the "Basic Pycord Help"

silver moat
dry echo
full basin
#

How can I keep the option of a select menu selected after the callback?

solemn idol
silver moat
full basin
#

Ah cool. I was looking at the Select menu itself not selectoptions

#

Do I have to init a new view class? Or can I just edit self.options?

proud mason
proud mason
proven mantle
#

How can i hide/remove the message? Thats my ErrorHandler.

sage bear
#

do bots need to be verified to do this?

proven mantle
#

No

proud mason
proud mason
proud mason
proven mantle
#

from discord.ext import commands

#

The function works. i get the embed

#

But it also prints the error

proud mason
#

Also, add a print statement at the end of your error handler, and print type(error)

proud mason
#

Hmm. Nope idk sorry

young bone
sage bear
#

yea

#

is it against tos?

proud mason
#

No it is completely valid

sage bear
#

i don’t plan on doing it it’s just the one i took a ss of

sage bear
proven mantle
#

You can also use a ip or localhost

#

Thats what i do. But you should change that in production

uncut current
#

so I got a small question, shouldn't this

client = DragonBot(
    command_prefix=commands.when_mentioned,
    case_insensitive=True,
    strip_after_prefix=True,
    intents=discord.Intents.all(),
    debug_guilds=config.GUILDS,
    activity=discord.Activity(type=discord.ActivityType.playing, name="starting"),
    state=discord.Status.idle,
)

start the bot as the yellow presence icon?
it starts with the green presence...

young bone
#

did you import it like that?

granite stratus
#
@bot.listen('on_message')
async def on_message(message):
    if message.author == bot.user:
        return
    print(message.content)
    if '@fluid hound' in message.content:
        await message.add_reaction(":jeanpinged:")
    if "https://pokepast.es/" in message.content:
      print("Pokepaste link")
      if " " in message.content:
        link=re.search("https://pokepast.es/(.*) ",message.content)
      else:
        link=message.content
      response = requests.get(link)
      soup = BeautifulSoup(response.text, 'html.parser')
      title = re.search('<h1>(.*)</h1>', str(soup)).group(1)
      auteur= re.search('<h2>&nbsp;by (.*)</h2>', str(soup)).group(1)
      page = str(soup.text)[0:3750]
      if len(page)>3750:
        page+="\n (...)"
      embed=discord.Embed(title=title,description=f"{page}")
      embed.set_footer(text=f"Par {auteur}")
      await message.channel.send(embed=embed)

Hello, I dont know why I can't get message.content, its blank

#

I granted the permission during the creation of the bot in the portal so I'm confused

obtuse juncoBOT
#

https://docs.pycord.dev/en/master/intents.html
https://discord.com/developers/docs/topics/gateway#gateway-intents

import discord
from discord.ext import commands

# Get specific intents for fine control
intents = discord.Intents()
intents.emojis = True
intents.guilds = True
intents.messages = True  # Required for prefix commands!
...
# Get all non-priveliged intents; this excludes presences, members and message_content 
intents = discord.Intents.default()

# Set priveliged intents: these must be enabled on dev portal
intents.members = True
intents.presences = True
intents.message_content = True  # Required for prefix commands >= 2.0.0b5

# Get all intents; all intents must be enabled on dev portal.
intents = discord.Intents.all()

# Apply intents when creating your bot
bot = commands.bot(prefix="?", intents=intents)
Discord Developer Portal

Integrate your service with Discord β€” whether it's a bot or a game or whatever your wildest imagination can come up with.

uncut current
granite stratus
#
intents = discord.Intents.all()
bot = discord.Bot(intents=intents)```
#

this would do it?

#

tried but my problem is not fixed yet

worldly pelican
#

The docs imply that it's receiving audio data from a voice channel but it is taking in bytes received as an argument?

solemn idol
mild sigil
uncut current
thorny kindle
#

How would i get the top message button to be disabled after someone presses it? So far ive tried quite a bit but i cannot get it to disable the right button.

    @discord.ui.button(label="Server IP", style=discord.ButtonStyle.primary, emoji='🎈')
    async def servip_callback(self, button, interaction):
        embed = discord.Embed(title='Server IP', description='To play on the server, Use the version **1.19.3** and the IP: play.lightbulbmc.xyz', color=discord.Color.random())
        embed.set_footer(text='Lightbulb MC')
        button.disabled = True 
        button.label = "No more pressing!" 
        await interaction.response.send_message(embed=embed)
        await interaction.edit_original_message(view=self)
full basin
#

And send the server ip response as a follow up

thorny kindle
solemn idol
#

Or do you mean the things I've tried?

#

I currently don't have it written anymore but I tried using cog_remove too

mild sigil
#

Ahh, meant the other code that wasn’t working

tiny spire
#

How do I make this command:

if config["MySQL"]:
  #/MySQL
  @client.slash_command(description="Configures your database (if enabled) to work with the bot.")
  async def dbconfigure(ctx):
    await MySQL.setup(ctx)

Visible and usable only to users with the Administrator permission

silver moat
#

.rtfm default_permission

winter condorBOT
silver moat
#

Note that people with guild permissions can still alter these permissions

fervent cradle
#

How to send a message to a specific channel?

silver moat
#

.rtfm partialchannel.send

winter condorBOT
#

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

silver moat
#

.rtfm partialmessageable.send

winter condorBOT
fervent cradle
#

This code doesn't work:

        report_channel = bot.get_channel(1081907386928857109)
        await report_channel.send(embed=report)```
Error: `AttributeError: 'NoneType' object has no attribute 'send'`
silver moat
#

yeah because the channel isn't cached

fervent cradle
#

hm? how do i do that?

silver moat
#

Don't do that

#

.tag partial

winter condorBOT
#

Partial Objects

These can be used to make API calls when you have channel id and/or message id, and you don't want to rely on the cache to have their objects.

Methods which can be used on them are -

Example Usage:

async def star_message(channel_id: int, message_id: int):

    # Get Partial Messageable object. Docs-
    # https://docs.pycord.dev/en/stable/ext/commands/api.html#discord.ext.commands.Bot.get_partial_messageable
    partial_channel = bot.get_partial_messageable(channel_id)

    # Get Partial Message. Docs-
    # https://docs.pycord.dev/en/stable/api/models.html#discord.PartialMessageable.get_partial_message
    partial_message = partial_channel.get_partial_message(message_id)

    # Add a reaction
    await partial_message.add_reaction(":star:")
fervent cradle
#

..?
AttributeError: '_MissingSentinel' object has no attribute 'request'

        report_channel = bot.get_partial_messageable(1081907386928857109)
        await report_channel.send(embed=report)```
silver moat
#

use

await bot.fetch_channel(id_here)

then

fervent cradle
#

RuntimeWarning: Enable tracemalloc to get the object allocation traceback

#

lmao

#

wait

#

I forgot to add await at first, but this is what I get after using what you said:
AttributeError: '_MissingSentinel' object has no attribute 'request'

#

same error

#
        report_channel = await bot.fetch_channel(1081907386928857109)
        await report_channel.send(embed=report, view=Actions())```
proud mason
#

Full traceback would help confirm this

fervent cradle
#

I'll send the traceback once I am on pc

unique latch
#

hi, discord.ui.View.add_item seems to hang the command

#

This is my code

await ctx.defer()
        data = get_proxy()
        print(data)
        view = discord.ui.View()
        options = []
        for domain in data.get('domains'):
            options.append(discord.SelectOption(label=domain.get('name'), value=domain.get('name')))
        select = discord.ui.select(placeholder="Select a domain", options=options)
        async def callback(interaction):
            await interaction.response.edit_message(f"Awesome! Lets configure {select.values[0]}")
        select.callback = callback
        view.add_item(select)
        print('added view')
proud mason
unique latch
#

OH

fervent cradle
# proud mason Full traceback would help confirm this
  File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\ui\modal.py", line 341, in dispatch
    await value.callback(interaction)
  File "c:\Users\User\Documents\Coding\Otto\bot\moderation\reportMessage.py", line 41, in callback
    await report_channel.send(embed=report)
  File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\abc.py", line 1616, in send
    data = await state.http.send_message(
  File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\http.py", line 283, in request
    async with self.__session.request(
AttributeError: '_MissingSentinel' object has no attribute 'request```
true pewter
proud mason
#

Can you confirm you are on latest py-cord version?

#

Also update aiohttp if possible

fervent cradle
#

But I am sure I'm using the latest version

proud mason
#

That's how

fervent cradle
#

py-cord 2.4.0

proud mason
#

Or you can just do pip install -U py-cord aiohttp to check and update

proud mason
fervent cradle
#

I updated aiohttp, but still get the same error

#

Is there anything wrong with the code?

report_channel = bot.get_partial_messageable(1081907386928857109)
await report_channel.send(embed=report)
#

hm what's this? #discussion message

fervent cradle
#

okay

proud mason
#

It's about partial messages in partial channel

fervent cradle
#

so how do i fix my issue?

proud mason
#

Can you recreate this with a basic bot? One that only has on ready event and maybe a command

#

Try sending using partial messageable in either on ready or in the cmd

fervent cradle
#

lmao it works

#

but not when i try to send the message to a specific channel via a modal's callback

#

Code:

class ReasonInput(discord.ui.Modal):
    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)
        self.add_item(discord.ui.InputText(label="Enter Reason", style=discord.InputTextStyle.long))

    async def callback(self, interaction: discord.Interaction):
        # Success message
        await interaction.response.send_message(embed = discord.Embed(description=f"**The [selected message]({msg.jump_url}) has been successfully reported to the moderators!**", color=0x2B2D31), ephemeral=True)
        # Sending the report to mods
        global report
        report = discord.Embed(
            title = f"A new message has been reported by {reporter.name}!",
            description = f"{msg_author.mention}'s message has been reported by {reporter.mention}.\n**Member:** {msg_author} [`{msg_author.id}`]",
            color = 0xf95e5e
        )
        report.set_author(name="New report has been submitted")
        report.add_field(name="Reported Message:", value=f"[Jump to message]{msg.jump_url}")
        report.add_field(name="Reason:", value=f"{self.children[0].value}")
        report_channel = bot.get_partial_messageable(1081907386928857109)
        await report_channel.send(embed=report)```
#

anything wrong?

proud mason
#

oh hmm

young bone
proud mason
#

yea try sending a simple hi message

fervent cradle
#

also i need to make the global embed var since I had to customize the embed outside of the class & function lol

fervent cradle
proud mason
#

Without the embed

fervent cradle
#

no doesn't work

#

same error

fervent cradle
#

does anyone have a example of cogs and using different files for different commands

fervent cradle
fervent cradle
young bone
#

can you do fetch_channel?

proud mason
#

Where did you define bot...

#

Don't define another bot object in the file blobpain

#

Use interaction.client

young bone
#

^

fervent cradle
# proud mason Use interaction.client

so, something like this?

class aCog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot 
    async def on_ready():
        print(f"Logged in as {interaction.client.user}!")```
young bone
#

what?

#

Do you know what we are talking about?

proud mason
#

.rtfm interaction.client

winter condorBOT
proud mason
#

Returns the bot object

fervent cradle
#

What's the difference between user_command & message_command?

fervent cradle
errant craneBOT
#

Here's the button roles example.

errant craneBOT
#

Here's the modal dialogs example.

proud mason
#

to access the bot instance, you always use self.bot

proud mason
#

user cmd sends the user object, while msg cmd sends the msg object

limber urchin
gaunt junco
#

having some issues running my bot on replit, despite having installed the requisite dev version

#

this is the version that my actual machine displays

gaunt junco
#

the only line that currently returns an error is the bot = discord.Bot() command
should i send everything subsequent?

fervent cradle
#

sure

gaunt junco
#

it functions properly on my actual machine
trying to host it permanently on replit

fervent cradle
#

Yeah, replit occurs error sometimes for no reason idk why

#

Also replit isn't a good option for hosting

gaunt junco
#
import discord
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
import asyncio
from keep_alive import keep_alive # flask script to host the bot on a web server

bot = discord.Bot()

# [commands and such]

TOKEN = "the thing"

keep_alive()
bot.run(TOKEN)
fervent cradle
#

Replit isn't a hosting platform, it is a browser IDE like vscode

gaunt junco
#

im aware
but it can be exploited using uptime robot for free 24/7 hosting

fervent cradle
#

bruh

#

it sucks

blissful hazel
fervent cradle
#

very poor performance

blissful hazel
#

it has

gaunt junco
fervent cradle
#

Doesn't matter

gaunt junco
#

i was considering purchasing a raspberry pi but even the zero 2 w has inflated 10x of its msrp

young bone
#

?tag norepl

obtuse juncoBOT
#

Why NOT to use Repl as a hosting platform

You should not use Repl.it to host your bot.
It may be a nice option as its "free" but you should use something else considering the major flaws.

  • The machines are super underpowered.
    • This means your bot will lag a lot as it gets bigger.
  • You'll need a web server alongside your bot to prevent it from being shut off.
    • This isn't a trivial task, and eats more of the machines power.
  • Repl.it uses an ephemeral file system.
    • This means any file you saved via your bot will be overwritten when you next launch.

IMPORTATNT

  • They use a shared IP for everything running on the service.
    This one is important - if someone is running a user bot on their service and gets banned, everyone on that IP will be banned. Including you.

Please avoid using repl.it to host your bot. It's not worth the trouble.

If you're looking for free options, consider using AWS/Google Cloud Platform/Azure and its respective free tiers or just pay for an actual VPS.

fervent cradle
#

I used to host a bot via uptime & it became offline every 5 mins

gaunt junco
#

is there any free alternative i can utilize
i dont see the reason to pay a subscription to aws or azure
but i dont want my data stolen by the random conceal hosting discord server
sorry im really new to bot development

young bone
#

I use a Raspberry Pi to host my Bot

limber urchin
gaunt junco
#

it's $150 for the zero 2 w, which was initially $15
all associated sellers are out of stock
i just dont see the reason of making such a substantial investment for a trival bot that is meant to just have some humorous commands my friends can tinker with

gaunt junco
limber urchin
#

Or just find a cheap hosting provider like Vultr, DigitalOcean or GalaxyGate

thorny kindle
#
    @discord.ui.button(label="Server IP", style=discord.ButtonStyle.primary, emoji='🎈')
    async def servip_callback(self, button, interaction):
        embed = discord.Embed(title='Server IP', description='To play on the server, Use the version **1.19.3** and the IP: play.lightbulbmc.xyz', color=discord.Color.green())
        embed.set_footer(text='Lightbulb MC')
        button.disabled = True 
        button.label = "No more pressing!" 
        await interaction.response.edit_message(view=self)
        await interaction.responce.send_message(embed=embed)
full basin
#

Response.send_message is not a folleoup

thorny kindle
#

Oh?

full basin
#

interaction.followup.send

thorny kindle
#

Alr

young bone
full basin
#

I guess

#

A followup will look like a reply

#

While channel.send is the plain message

thorny kindle
#

Alright, Working now. Thanks alot!

fervent cradle
limber urchin
storm oyster
# fervent cradle Hey, how do I host by railway?

I've been wanting to make a video on this for so long, but only got around to it now. Enjoy, and ask any questions in the support server.
Reupload due to aspect ratio issues

Railway: https://railway.app/
Railway's support server: https://discord.gg/FStNuv52jc
Simple Discord Bot: https://gist.github.com/FaztTech/e17ea3fde6988f7215301b888ccaaf5c
...

β–Ά Play video
#

Pretty simple tbh

fervent cradle
thorny kindle
#

How would i use discord.ButtonStyle.link?

limber urchin
limber urchin
thorny kindle
#

I tried adding url='google.com' into it but that just crashed my bot lol

#

@discord.ui.button(label="Store", style=discord.ButtonStyle.link, url='google.com')

limber urchin
fervent cradle
thorny kindle
#

Ok

limber urchin
#

Sometimes you have to do things yourself, shocker, I know

thorny kindle
#

@discord.ui.button(label="Store", style=discord.ButtonStyle.link, url='https://www.google.com') crashed it too

limber urchin
#

Are you getting any error messages?

thorny kindle
#

yea

#
  File "/home/container/main.py", line 151, in <module>
    class HelpCommand(discord.ui.View):
  File "/home/container/main.py", line 165, in HelpCommand
    @discord.ui.button(label="Store", style=discord.ButtonStyle.link, url='https://www.google.com')
TypeError: button() got an unexpected keyword argument 'url'
limber urchin
#

Then show those too facepalm

#

Oh, the decorator doesn't take a url?

thorny kindle
#

ig so

#

I tried link='' too but that didnt work too

limber urchin
#

I dunno then, guess you have to create the button without the decorator

full basin
#

Url buttons don't have a callback

#

So the decorator doesn't take a url kwarg lol

limber urchin
#

Oh yeah, right. Makes sense

limber urchin
thorny kindle
#

OK. How would i add the link?

limber urchin
#

You create the button through a class instance instead and add it to the view

#

the class init takes a url kwarg

thorny kindle
#

So add it to this bit then?

class HelpCommand(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=60)
limber urchin
#

Yes

thorny kindle
#

Ok, Where would i add it? Next to timeout?

full basin
#

With the add_item method

thorny kindle
#

Ok.

full basin
#

Below the super init

thorny kindle
#

How would i use it? Ive searched it on the pycord docs and it doenst show any examples of it

limber urchin
#

Just create an instance of the button class and add it using add_item

#

You don't need an example for that if you know basic OOP

hybrid flower
#

hi can I define My Guild Class that extends from discord.Guild, and make the bot can use My Guild Class to instantiate guild entity?

limber urchin
#

Sure, why not?

red geyser
#

Im getting this error when trying to use slash commands
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: 'SlashCommand' object is not subscriptable

#
@bot.command()
async def withdraw(ctx):
    global league_message
    if ctx.author in participants:
        participants.remove(ctx.author)
        await ctx.respond(f"{ctx.author} is no longer participating in the race!")
    elif ctx.author in reserve_participants:
        reserve_participants.remove(ctx.author)
        await ctx.respond(f"{ctx.author} is no longer participating in the race!")
    elif ctx.author in commentary_participants:
        commentary_participants.remove(ctx.author)
        await ctx.respond(f"{ctx.author} is no longer commentating in the race!")
    else:
        await ctx.respond(f"{ctx.author} You have not joined the race yet!")
    if league_message:
        await league_message.edit(embed=await get_embed())```
red geyser
#

py-cord==2.4.0

#

its throwing the error because of this line if current_race is not None and int(current_race['date'][3:-2].replace(':', '')) <= current_time:

limber urchin
#

That line isn't even in the code you sent

proud mason
#

lmao

fervent cradle
#

How do I delete the button when the button is pressed?

mild sigil
#

Can someone help me understand why this for loop isn't working?

    @commands.slash_command(guild_ids=testingServers, description="Display Weekly Options")
    async def weekly(self, ctx: discord.ApplicationContext):
        view = discord.ui.View(timeout=20)
        row = 0
        but_count = 0
        for mode_standard in weekly_modes:
            view.add_item(WeeklyButtonMain(mode_standard, row))
            but_count += 1
            if but_count <= 4:
                row += 1
                but_count = 0

The button count variable gets reset to 0 each time through. Do I need another for loop inside to loop through?
weekly_modes has 8 string variables.

proud mason
proud mason
limber urchin
mild sigil
#

I'm an idiot, thank you

desert path
#

hi

#

how do i create group cmds with pycord

#

and like bridge cmds

fervent cradle
proud mason
#

.guide

winter condorBOT
winter condorBOT
proud mason
#

Use that

desert path
#

so i chcked the guide out but i cant find grp cmds for bridge

#

just for regular commands

proud mason
#

.rtfm bridge_group

desert path
#

oh thanks

proud mason
desert path
#

oh alr

livid wolf
#

Very, very quick question

#

How do I have an option in a command

#

Like this for example

errant craneBOT
#

Here's the slash options example.

livid wolf
#

thanks

leaden relic
#

any reason why

await interaction.response.send_message(f"{discord.utils.get(interaction.guild.roles, name='Member').mention}")```
is not pinging the role? just mentioning it?
limber urchin
#

If the bot doesn't have permission to mention the role, or the role isn't mentionable it won't ping it

uncut current
#

is it possible to print out the guild where this error

Ignoring exception in on_connect
Traceback (most recent call last):
  File "E:\DragonBot\venv\Lib\site-packages\discord\client.py", line 378, in _run_event
    await coro(*args, **kwargs)
  File "E:\DragonBot\venv\Lib\site-packages\discord\bot.py", line 1164, in on_connect
    await self.sync_commands()
  File "E:\DragonBot\venv\Lib\site-packages\discord\bot.py", line 738, in sync_commands
    app_cmds = await self.register_commands(
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "E:\DragonBot\venv\Lib\site-packages\discord\bot.py", line 531, in register_commands
    prefetched_commands = await self._bot.http.get_guild_commands(
                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "E:\DragonBot\venv\Lib\site-packages\discord\http.py", line 365, in request
    raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access

is thrown?

leaden relic
proud mason
#

check that

leaden relic
mild sigil
#

If I respond to a comment with a bot command, what information can I glean from the original comment?

solemn idol
#

@grizzled sentinel (I am not sure if you want to keep getting pinged on this if not, I apologize I wont anymore in the future.)
So anyway I still haven't resolved the issue with the loading of extensions, I have tried not loading a specific extension in my cog loader:

for filename in os.listdir('./cogs'): # Loads all files (*.py)
    if filename.endswith('.py') and filename != 'developer.py':
        bot.load_extension(f'cogs.{filename[:-3]}') # Loads the file without ".py" for example: cogs.fun
        print(colorama.Fore.BLUE + f'Loaded : {filename[:-3]}')

the bot did as expected not see the cog. But then when I loaded it, (it gave me a confirmation it loaded) it would still not see the cog at all no commands in it nothing.
My help command raised an error then too;

discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'NoneType' object has no attribute 'mention'

Because obviously it had not found the command it wanted to mention.

Soo, my suspicion is that indeed it has something to do with the discord synching. But how am I supposed to sync that so damn fast so it can even be mentioned with .mention on my help embed?

I just did some testing and as it turns out, the bot itself notices the extension is being unloaded but the /commands are still not synced with discord... so the question still remains.

The Question:

"how am I supposed to sync my commands so damn fast so it can even be mentioned with .mention on my help embed after I have loaded the cog in?"
It has to do something with synching. But what I still don't understand is how can a not loaded command (because the cog isn't loaded) still be called?
If I were to shutdown my bot no command would work anymore, it would just say interaction failed to respond, so why does it still respond after having unloaded the entire cog with the command which shouldn't be callable?

Ty for reading, sorry x2 for the ping if it's annoying you.

#

I printed the command names to see if the bot would actually see them while being unloaded / loaded

grizzled sentinel
solemn idol
#

So like this;

for filename in os.listdir('./cogs'): # Loads all files (*.py)
    if filename.endswith('.py') and filename != 'developer.py':
        print(sum(1 for _ in bot.walk_application_commands())) # Temporary test command
        bot.load_extension(f'cogs.{filename[:-3]}') # Loads the file without ".py" for example: cogs.fun
        print(sum(1 for _ in bot.walk_application_commands())) # Temporary test command

? or do you mean in the unloading / loading command I made extra?

solemn idol
grizzled sentinel
#

Try it in the loading command

solemn idol
#

red is when I did unload blue is where I loaded

#

so 34 and 27 are from unloading
and 27 and 34 were from loading

grizzled sentinel
#

Hmm. So the bot does think it is removing the commands. Im not sure why they are still working. That tells me that there migfht be a bug deep within the lib.

#

How sure are you that you do not have another bot running at the same time

solemn idol
#

Because when I kill the application I can do /help it first wont respond and after a few minutes the bot status goes offline

grizzled sentinel
#

πŸ‘ I will take a look at the libraries unload code in a bit.

solemn idol
mild sigil
#

If I reply to a message and give a bot command, can I pull the information from the original message like date-time, user/user-id, etc.? Is this a case of message reference or another class?

grizzled sentinel
#

You cannot reply to a message when using slash commands

mild sigil
#

:/

red geyser
# limber urchin That line isn't even in the code you sent

Sorry, wrong command.

@bot.command()
async def current_race(ctx):
    embed = await get_embed()
    await ctx.respond(embed=embed)

async def get_embed():
    global current_race, participants, reserve_participants, commentary_participants
    
    driver_role = discord.utils.get(bot.guilds[0].roles, name='Driver')
    reserve_role = discord.utils.get(bot.guilds[0].roles, name='Reserve Driver')
    commentator_role = discord.utils.get(bot.guilds[0].roles, name='Commentary Team')

    # Check if it's time to move to the next race
    if current_race is not None and int(current_race['date'][3:-2].replace(':', '')) <= current_time:
        # Clear the participant lists
        participants = []
        reserve_participants = []
        commentary_participants = []
        # Move to the next race
        current_race = next((race for race in races if int(race['date'][3:-2].replace(':', '')) > current_time), None)

    if current_race is None:
        description = "All races have already happened."
    else:
        description = f"πŸ“… **{current_race['round']} at {current_race['location']} on <t:{current_race['date'][3:-2]}F>**.\n\n"
    embed = discord.Embed(title=f"Current Race", description=description, color=discord.Color.red())
    embed.set_author(name=bot.user.name, icon_url=bot.user.avatar.url)

    if current_race is not None:
        for race in races:
            if race['location'] == current_race['location']:
                embed.set_thumbnail(url=race['flag'])
                break

    if participants:
        embed.add_field(name=f"βœ… Participating ({len(participants)})", value="\n".join([p.display_name for p in participants]), inline=False)
    else:
        embed.add_field(name="βœ… Participating (0)", value="\n", inline=False)

    if driver_role:
        driver_members = driver_role.members
        not_participating = [member for member in driver_members if member not in participants]

        if not_participating:
            embed.add_field(name=f"❌ Not Participating ({len(not_participating)})", value="\n".join([m.display_name for m in not_participating]), inline=False)
        else:
            embed.add_field(name="❌ Not Participating (0)", value="\n", inline=False)

    if reserve_role:
        reserve_members = reserve_role.members
        if reserve_participants:
            not_participating = [member for member in reserve_members if member not in reserve_participants]
            embed.add_field(name=f"πŸ“ Reserve ({len(reserve_participants)})", value="\n".join([r.display_name for r in reserve_participants]), inline=False)
        else:
            embed.add_field(name="πŸ“ Reserve (0)", value="\n", inline=False)

    if commentator_role:
        commentary_members = commentator_role.members
        if commentary_participants:
            not_participating = [member for member in commentary_members if member not in commentary_participants]
            embed.add_field(name=f"πŸŽ™οΈ Commentators ({len(commentary_participants)})", value="\n".join([c.display_name for c in commentary_participants]), inline=False)
        else:
            embed.add_field(name="πŸŽ™οΈ Commentators (0)", value="\n", inline=False)

    return embed```
hybrid flower
# limber urchin Sure, why not?

I have defined the new guild class, and how to let the framework to use it when I call bot.get_guild, message.guild, channel.guild etc.

limber urchin
limber urchin
#

Those names are going to conflict and you have no way to predict what the code will do, use better naming

tiny spire
#

This code:

if config["Reddit Scraper"]:
  @client.group()
  async def reddit(ctx: discord.ApplicationContext):
    pass

  #/images <subreddit> <quantity>
  @reddit.slash_command(description="Pull images from a subreddit.")
  @option("subreddit", description="What subreddit to scrape from? (case sensitive)")
  @option("quantity", description="How many images to download? (Maximum 6)")
  async def images(ctx: discord.ApplicationContext, subreddit: str, quantity: int):
    await Image.images(ctx, subreddit, quantity)

  #/videos <subreddit> <quantity>
  @reddit.slash_command(description="Pulls a video from a subreddit.")
  @option("subreddit", description="What subreddit to scrape from? (case sensitive)")
  @option("quantity", description="How many videos to download? (Maximum 6)")
  async def videos(ctx: discord.ApplicationContext, subreddit: str, quantity: int):
    await Video.reddit_video_main(ctx, subreddit, quantity)```
This error:

File "G:\ChatLGPT\main.py", line 62, in <module>
@client.group()
^^^^^^^^^^^^^^
File "C:\Users\Under\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\bot.py", line 1015, in inner
group = cls(
^^^^
TypeError: reddit() got an unexpected keyword argument 'guild_ids' File "G:\ChatLGPT\main.py", line 62, in <module>
@client.group()
^^^^^^^^^^^^^^
File "C:\Users\Under\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\bot.py", line 1015, in inner
group = cls(
^^^^
TypeError: reddit() got an unexpected keyword argument 'guild_ids'```

errant craneBOT
#

Here's the slash groups example.

tiny spire
#

thx

fallen cove
#

is there a way to hide slash commands so only dm slash commands show in DMs and guild commands in guilds?

silver moat
fallen cove
silver moat
fallen cove
#

i have an issue with slash commands disappearing and ideas?

fallen cove
#

some are there

silver moat
fallen cove
fallen cove
silver moat
#

Well, we're being super vague and all so what are the exact steps that it takes for the commands to disappear?

#

and then you don't respond...

tiny spire
#

So I have this python command that checks for a few permissions:

    @admin.slash_command(description="Clears all messages.")
    @has_permissions(manage_channels=True, manage_messages=True)
    async def purge(ctx, channel: discord.TextChannel):
      await Messages.purge(ctx, channel)```
How do I make it return a message if the user doesn't have the required permissions?
#

and is it possible to have commands such as this one invisible to specific users?

silver moat
silver moat
#

.rtfm default_permission

winter condorBOT
solemn idol
crystal fjord
#

I have just watched a video on youtube of how to create a discord bot using python and I followed what he did and it's not working for me. pls someone help me;)

from discord.ext import commands

client = commands.Bot(command_prefix = '!')

@client.event
async def on_ready():
    print("The bot is on")
    print("------------------------------------------------------------------")

@client.command()
async def Hi(ctx):
    await ctx.send("Hello, I'm a tapuh")

client.run('my token is here thats not the problem')```
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.

young bone
#

Also pls dont crosspost

crystal fjord
#

In my server where the bot is in I wrote !hi and nothing happend

obtuse juncoBOT
#

https://docs.pycord.dev/en/master/intents.html
https://discord.com/developers/docs/topics/gateway#gateway-intents

import discord
from discord.ext import commands

# Get specific intents for fine control
intents = discord.Intents()
intents.emojis = True
intents.guilds = True
intents.messages = True  # Required for prefix commands!
...
# Get all non-priveliged intents; this excludes presences, members and message_content 
intents = discord.Intents.default()

# Set priveliged intents: these must be enabled on dev portal
intents.members = True
intents.presences = True
intents.message_content = True  # Required for prefix commands >= 2.0.0b5

# Get all intents; all intents must be enabled on dev portal.
intents = discord.Intents.all()

# Apply intents when creating your bot
bot = commands.bot(prefix="?", intents=intents)
Discord Developer Portal

Integrate your service with Discord β€” whether it's a bot or a game or whatever your wildest imagination can come up with.

true pewter
proud mason
#

.guide

winter condorBOT
crystal fjord
#

Thank you mate

crystal fjord
proud mason
thorny kindle
#

How could i get this to work, Right now when i start my bot i get a error saying

  File "/home/container/main.py", line 197
    embed.set_footer(text=f'Announced by: {ctx.author}')
                                                        ^
IndentationError: unindent does not match any outer indentation level
#

This is my command:

@bot.slash_command()
@commands.has_guild_permissions(kick_members=True)
@option(
"Channel", 
Union[discord.TextChannel]
)
async def sayembed(
    ctx: discord.ApplicationContext,
    channel: Union[discord.TextChannel],
    title,
    description
):
    embed = discord.Embed(title=f"{title}", description=f'{description}', color=discord.Color.random())
    embed.set_footer(text=f'Announced by: {ctx.author}')
    await channel.send(embed=embed)
    await ctx.respond('t')
thorny kindle
#

I have

#

But no matter what i do it wont start. Ive tried getting it under the async bit. It appears to be but the bot doesnt think so.

#

This is what that bit looks like. Its under the ): from async and in the correct column. But its saying its not. Ive tried deleting it back to the last line then pressing enter on it.

#

nvm, Fixed lol

thorny kindle
#

How would i make a command only be used by a role without using has_guild_permission?

thorny kindle
#

Ok. Would i put the role ID after then?

young bone
#

name or id

thorny kindle
#

Ok

young bone
#

or just both xd

young bone
thorny kindle
#

How would i use it?

@commands.has_role('718080067032449124'=True)

Ive tried without the '', With the ''. Role name, Without =True, With = true lol.

#

Got it

#

forgot about int()

limber urchin
#

Why would you need int()?

#

Why not just pass at as an int initially?

young bone
thorny kindle
#

Idk, Didnt work without the int. Works with it lol

#

@commands.has_role(int('718080067032449124'))

young bone
thorny kindle
#

Oh, its working lol

tired goblet
#

from the giude: title should be name

crystal fjord
#

"TypeError: token must be of type str, not NoneType" Does someone know what's causing this?

#

import discord
import os # default module
from dotenv import load_dotenv

load_dotenv() # load all the variables from the env file
bot = discord.Bot()

@bot.event
async def on_ready():
    print("The bot is ready and online!")

@bot.slash_command(name = "hello", description = "Say hello to the bot")
async def hello(ctx):
    await ctx.respond("Hey!")

TOKEN = "MTA4NzAyNDk4MDg5OTkyMTk3MQ.GCTJZj.fpzAuDD8not-TKf_Pjkd0"
bot.run(os.getenv(TOKEN)) # run the bot with the token```
tired goblet
#

where have you defined TOKEN

crystal fjord
#

line 16

#

TOKEN = "MTA4NzAyNDk4MDg5OTkyMTk3MQ.GCTJZj.fpzAuDD8not-TKf_Pjkd0"

tired goblet
#

oh i see

#

is that how youre supposed to use getenv?

#

i am not familiar with it

crystal fjord
proud mason
#

please reset it

crystal fjord
#

Dont worry it's not my real one

tired goblet
#

youre supposed to define it in the env file

#

youre doing it in the code

#

might as well just do client.run(TOKEN)

proud mason
#

yea os.getenv(TOKEN) will get it from the environment variables

tired goblet
proud mason
#

does it error?

tired goblet
#

do we need to make an issue for it?

proud mason
#

(it should ig)

tired goblet
#
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: Embed.add_field() got an unexpected keyword argument 'title'``` yeah
proud mason
#

yea it should be name

young bone
tired goblet
#

sorry thats not the full traceback

young bone
#

why title at add_field()?

tired goblet
#

oh it was in the guide

tired goblet
young bone
#

lol

#

use (name="", value="")

tired goblet
#

aye, thanks

young bone
tired goblet
#

right

tired goblet
#

is it possible to have each field be displayed in a new line?

young bone
tired goblet
#

do you mean inline?

young bone
#

ye

tired goblet
#

nah it doesn't seem to be working

young bone
tired goblet
#

oh i haven't tried False

tired goblet
#

but doesn't it default to false if i don't define it? so how is defining it to false different?

proud mason
#

i dont remember

tired goblet
#

oh

limber urchin
thorny kindle
fervent cradle
#

How do I create a link button?

full basin
#

.rtfm discord.ui.Button

fervent cradle
#
class Actions(discord.ui.View):
    @discord.ui.button(label="Delete Message", style=discord.ButtonStyle.green)
    async def delete(self, button, interaction):
        try: 
            await msg.delete()
            button.disabled = True
            button.label = "Message Deleted"
            await interaction.response.send_message("The message has been deleted successfully.", ephemeral=True)
        except discord.errors.NotFound:
            button.disabled = True
            button.label = "Message Not Found"
            await interaction.response.send_message("The message could not be found.", ephemeral=True)

Why is that not disabling the button after pressing it?

thorny kindle
#

How would i make it so i only need 1 of the roles to execute a command from a list of roles?

#

Figured it out, used or

full basin
lime lotus
#

a modal's callback() is called when it's data is submitted. is there some event when the modal is closed without submission of data, other than timeout?

fervent cradle
full basin
fervent cradle
#

hm?

full basin
#

...

#

Literally what I said. You have to edit the message passing the view again

proud mason
green hinge
#

Is there an advantage to sending my views with my select menus as a response instead of a message?

proud mason
#

(interaction.followup does have them tho)

green hinge
proud mason
# green hinge What does ratelimits mean exactly?

ratelimits are a way for discord to stop bots (and even users) from spamming the discord infrastructure with lots of requests. if many users decided you use your bot at the same time, your bot could send even hundreds of requests in a very short time. to stop discord's servers and databases from overloading, it ratelimits you. meaning you are blocked from sending requests for a short time

frequent ratelimits can even get your bot banned from discord

#

interaction.response doesnt have any ratelimits

#

so using that instead of other ways can reduce your chance of getting ratelimited

green hinge
proud mason
#

the interaction itself or interaction followup is for 15 mins

green hinge
proud mason
#

(if timeout is None)

green hinge
# proud mason select menu can be active for eternity too

So the select menu would always be active or?

await interaction.response(view=TestView())

class TestView(discord.ui.View):
   def __init__(self, bot: discord.Bot):
        self.bot = bot
        super().__init__(await Farbe(self.bot), timeout=None)

class Farbe(discord.ui.Select):
    def __init__(self, bot: discord.Bot):
        self.bot = bot
        options = [discord.SelectOption(label=farbe) for farbe in ['Green','Blue','Red']
        super().__init__(
            placeholder="WΓ€hle die Farbe aus",
            min_values=1,
            max_values=1,
            options=options,
        ) 

    async def callback(self, interaction: discord.Interaction):
      await interaction.response(self.values[0])```
green hinge
# proud mason yes it would be

response = interaction.response I can cache just like message = interaction.channel.send or?
And then I can also use response.edit instead of message.edit or?

lime lotus
proud mason
#

if you only want to edit or delete, await interaction.edit_original_response and await interaction.delete_riginal_response

green hinge
green hinge
green hinge
# young bone what?

I add a second select menu to my view after selecting something in the first one.
What is the best way to update the view so that the second select menu is also displayed?

gleaming falcon
#

Getting confused on message references within a View.
User invokes command and gets a confirmation with a button. The button creates a response that I can delete using delete_original_response(), but how do I access the original message that the View is attached to so I can delete that?

interaction.message.delete() isn't it.

Ah. self.message.delete()

green hinge
radiant pewter
#

Trying to have a command that reloads my cogs and resyncs them after. After searching for a while I found bot.sync_commands() but it doesn't seem to work

my code: ```py
@bot.slash_command(name="reload", description="Reloads the Gameserver Cog")
async def reload(ctx):
if commands.is_owner == False:
await ctx.respond("You are not the owner of this bot!",ephemeral=True)
return
try:
bot.reload_extension("cogs.gameservers")
await bot.sync_commands(delete_existing=True)
except Exception as e:
await ctx.respond(f"Error while reloading Gameserver Cog: {e}",ephemeral=True)
return
await ctx.respond("Reloaded Gameserver Cog",ephemeral=True)

Error:

400 Bad Request (error code: 50035): Invalid Form Body
In 2: Application command names must be unique

Did I miss anything obvious? (I know delete_existing is True by default ignore that)
green hinge
radiant pewter
# young bone and if you do without it?

Without sync_commands? Deleted commands stay and timeout and new commands dont show up, tried refreshing discord with ctrl + r but that didnt change anything either

grizzled sentinel
radiant pewter
radiant pewter
grizzled sentinel
#

I'm not sure than I can try to look into it over the next few days but I hope a core dev can try and work out the bug.

radiant pewter
green hinge
#

Is there a better way to check and reset the 2 other select menus here?
I have the feeling that my approach is not quite optimal, although it works like this. πŸ€”

async def callback(self, interaction: discord.Interaction):
        if len(self.view.children) > 1:
            for i, children in enumerate(self.view.children):
                name = children.__class__
                self.view.remove_item(self.view.children[i])
                self.view.add_item(await name(self.bot, self.spotdaten, self.message_collection))
            await self.view.message.edit(view=self.view)
        else:
            self.spotdaten.gewaesser = self.values[0]
            self.view.add_item(await BuchstabeFisch(self.bot, self.spotdaten, self.message_collection))
            self.placeholder = self.values[0]
            await self.view.message.edit(view=self.view)
        await interaction.response.defer()```
solemn idol
grizzled sentinel
#

I am trying to read the code but I am not sure if I understand it all. Plus command registration/callbacks is like the core of the lib XD. I will try my best.

green hinge
#

How many select menus can be added to a view?

young bone
fallen cove
green hinge
# young bone I would say 25 like buttons?

Okay i will try πŸ™‚

If I have a select menu in my view and call the modal there in the callback function. Do I have to pass the view so that I can add a button to the view in the callback function of the modal or is the modal automatically in the view like the select menu?

await interaction.response.send_modal(AddSpot(self.bot, interaction.channel, self.spotdaten))```
fallen cove
#

is there a timeline for the fix for 74 byte UDP packets for voice connections?

solemn idol
smoky forge
#
hook_msg = await self.board_hook.send(msg.content,
                                   username=author.name,
                                   avatar_url=author.display_avatar.url,
                                   embed=embed,
                                   thread_name=f"Art by @{author.name}")

Why is hook_msg returning None?

#

self.board_hook is a Webhook object btw

#

According to the docs the return should be a WebhookMessage object

#

Alright I fixed it, all I had to do was set wait to True

#

Now this code is throwing this exception ???

hook_msg = await self.board_hook.send(msg.content,
                                      username=author.name,
                                      avatar_url=author.display_avatar.url,
                                      embed=embed,
                                      thread_name=f"Art by @{author.name}",
                                      wait=True)

if attachments is not None:
    await hook_msg.edit(attachments=msg.attachments) # The line that calls the exception for some reason
Exception has occurred: NotFound
404 Not Found (error code: 10008): Unknown Message
  File "E:\Documents\GitHub\wooperbot\cogs\artboard.py", line 73, in _artboard_add
    await hook_msg.edit(attachments=msg.attachments)
  File "E:\Documents\GitHub\wooperbot\cogs\artboard.py", line 94, in _forcestar
    await self._artboard_add(message)
  File "E:\Documents\GitHub\wooperbot\cogs\artboard.py", line 119, in mc_forcestar
    await self._forcestar(ctx, message)
  File "E:\Documents\GitHub\wooperbot\cogdebug.py", line 33, in start_bot
    self.run(self.token)
  File "E:\Documents\GitHub\wooperbot\cogdebug.py", line 38, in <module>
    bot.start_bot()
discord.errors.NotFound: 404 Not Found (error code: 10008): Unknown Message
green hinge
#

Can I add an embed to a view so that the sequence is Select Menu -> Embed -> Select Menu or is that not possible?

dense gorge
#

Question: when making a Select of type user_select, how does one filter the users added as options?

rare ice
#

You can’t.

#

Discord does that for you

#

You can’t customize channel or user selects

dense gorge
#

I don't want every gdamn user added...sigh.

rare ice
dense gorge
#

Alright, back to the old string Selects.

#

I suppose.

green hinge
# rare ice Not possible

Okay so I am forced to use two views, in the first view a select menu and in the second view the embed + second select menu or?

rare ice
#

Select menus can send messages

#

So you can have a select menu interaction send an embed

#

If that’s what you want

#

You’re not being very clear catbite

smoky forge
green hinge
# rare ice Explain what you want

I have a select menu. When I select something in it, I call a modal in the callback function where I can enter a number. After sending the modal I check in the callback function of the modal if the format and the input is correct or not.
If the input is wrong, an embed should appear where it says error and below it should be a button with "re-enter".
But if the input is correct, an embed should appear with the value, below it a button "Change entry" and below it the next select menu.

Unfortunately I can't put the embed in the view of the first select menu which would show a clean picture because a new response is not sent and the botname is in there again. I am then forced to create a new view with the embed and all other content or?

smoky forge
rare ice
#

.rtfm discord.Interaction.response.send_message

winter condorBOT
#

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

rare ice
#

.rtfm discord.InteractionResponse.send_message

winter condorBOT
smoky forge
#

The message gets sent in the forum channel, hook_msg has an ID attribute yet somehow the message doesn't exist

green hinge
# rare ice Send an embed with `interaction.response.send_message`

Yes and there I can also send a view that contains the button and depending on the next select menu.

But for this I need a new view and can not use the already existing view from the first select menu.

And I have the bot name above the message so that it is not quite clean what can not be avoided but with respons, not as with Message.send or?

smoky forge
#

:/

rare ice
#

I seem to be getting this error when I return a normal string to get_prefix when doing custom prefixes:

class MyBot(commands.Bot):
  def __init__(self, db):
    self.config = db
    # other stuff
  super().__init__(command_prefix=get_prefix)
  def get_prefix(self, message):
    return self.config['prefix']
#

self.config['prefix'] returns '!'

limber urchin
rare ice
#

Oh ok

#

Thanks

lime lotus
#
author_voice = ctx.author.voice
print("1")
voice_client = await author_voice.channel.connect()
print ("2")```
I execute this code in the callback of a slash command. The await VoiceChannel.connect() function I run does not seem to finish execution. The bot joins the channel as desired but this function does not stop execution, and hence the code thereafter does not execute. In the console, I see the output `1` printed before I call this function, not `2` which I print afterwards. All intents are enabled. Any idea why this could be occurring?
silk spindle
#

was someone able to display svg images in discord?

analog trellis
#

hey does anyone knoes hoe to install nltk in python?

opaque cloak
#

when calling the command, the console should show a line that contains the name of the argument (that is, the command itself) and its passed parameter if the command has it, but I can’t figure out how to get this parameter, can someone help with this?

@bot.event
async def on_application_command_completion(context):
    print("_________________")
    print(">on_application_command")

    command = context.command  #get command object
    args = command.options  # get a list of arguments
    args = [f'{o.name}: {o.value}' for o in args]

    args_str = ' '.join(args)  # form a string in the format 'argument_name: argument_value'
    print(f'Called command {command.name} with arguments: {args_str}')```
green hinge
#
class AddSpot(discord.ui.Modal):
    async def callback(self, interaction: discord.Interaction) -> None:
        embed = discord.Embed(title="Spot eingetragen", 
                            description=f"Du hast den Spot {spot} eingetragen", 
                            color=discord.Color.blurple()
                            )
        if not pattern_spot.match(spot):
            embed = discord.Embed(title="Fehler", 
                                description=f"Format min X:X max XXX:XXX", 
                                color=discord.Color.blurple()
                                )          
            if len(self.spotview.children) < 1:
                self.spotview.add_item(SpotAgain(self.bot, self.spotdaten))
                self.spotdaten.message = await interaction.response.send_message(embed=embed, view=self.spotview)
            else:
                self.spotview.remove_item(self.spotview.children[0])
                self.spotview.add_item(SpotAgain(self.bot, self.spotdaten))
                await self.spotdaten.message.edit_original_response(embed=embed, view=self.spotview)
                await interaction.response.defer()
        else:
            self.spotdaten.spot = spot
            if len(self.spotview.children) == 1:
                self.spotview.remove_item(self.spotview.children[0])
                self.spotview.add_item(ButtonSpotaendern(self.bot, self.spotdaten))
                await self.spotdaten.message.edit_original_response(embed=embed, view=self.spotview)
                await interaction.response.defer()
            else:
                self.spotview.add_item(ButtonSpotaendern(self.bot, self.spotdaten))
                self.spotdaten.message = await interaction.response.send_message(embed=embed, view=self.spotview)
                await interaction.followup.send(view=AngelArtView(self.bot, self.spotdaten))```
green hinge
solemn idol
#

How do I make a command with options like these?

Or at least what do I use to make these? Because I have no idea what they are called.

errant craneBOT
#

Here's the slash options example.

solemn idol
#

thank you :)

young bone
solemn idol
#

I have been using Option instead of option so far. Now that I see how simple option is I will probably just use that

green hinge
#

When I send a response I can't prevent the bot name from reappearing and not the messages being directly below each other like when I send a message, can I?

proud mason
green hinge
proud mason
#

Can't have best of both worlds

cerulean yarrow
#

where can i see the possible interactions for a button? I only know how to edit and send a message as interaction

green hinge
# proud mason Yes lol

Okay but a mixture of both then I think makes sense. I think I need only 5x channel.send that should then yes no problems I think or?
I will do the rest with response

proud mason
#

for a button, you only really have 4. send message, edit msg, send modal, defer

cerulean yarrow
# proud mason .rtfm interactionresponse

it is possible to make more than one interaction?, for example: a command that creates a voice channel for you, when you click on the button it edits the message confirming that the channel was created and creates the channel

proud mason
cerulean yarrow
silver moat
#

.rtfm interaction.guild

proud mason
#

this lol upvote

cerulean yarrow
#

it worked, thanks πŸ™‚

green hinge
# proud mason Can't have best of both worlds

I send after each other about 30 select menus, if I do the whole thing with channel.send() and many users use the function at the same time, do I get problems with the ratelimits?
And does it also count to the ratelimits if I edit a view? With self.view.message.edit ?

proud mason
#

ratelimits is a potential problem. you shouldnt worry about it too much if your bot is small/private

green hinge
proud mason
#

if you hit ratelimits quite often then you can ask discord to increase the limit for you lol

silver moat
#

shared hosts may also have something to do with ratelimits

green hinge
silver moat
green hinge
cyan quail
#

just

#

do it

#

if you hit ratelimits it will tell you

#

ratelimits are dynamic so most of the time we can't really tell you how much it will take to hit them

green hinge
#

Okay

green hinge
#

Can I also edit a response without affecting the ratelimits?

silver moat
green hinge
solemn idol
#

Ok I might be stupid but why does this not work?

If I print the for loop, it prints out a list just fine. I tried putting it as a string or list... but I have got no clue what I am doing wrong.
any help is appreciated.

proud mason
#

This is a python limitation

#

You would need to use autocomplete

solemn idol
proud mason
errant craneBOT
#

Here's the slash autocomplete example.

proud mason
#

Got it

solemn idol
#

Ah okay, thanks

proud mason
#

Autocomplete is a way to dynamically load option choice for users

#

It is infact the only way to do it

errant craneBOT
#
Internal indicator of special typing constructs.
See _doc instance attribute for specific docs.```
thorny kindle
#

How can i define client with my bot?

#

count it i think

#

Ran into another problem :/

#
@bot.event
async def on_message(message):
    channel = client.get_channel(1029735220938801253)
    print(f'Message from {message.author}: {message.content}')
    await channel.send(f'Message from {message.author}: {message.content}')
#

Whats "NoneType"?

thorny kindle
young bone