#Basic Pycord Help

1 messages · Page 18 of 1

deft kestrel
#

What to do if when you press a button "Unknown interaction" When you press it again everything works.
As far as I understand, the problem is not in the code, but if it is not, how can I fix it?

cerulean lake
#

Command.can_run is propagating past my try except block

try:
  if not await command.can_run(ctx):
    continue
except:
  continue
#

the command is of type BridgeCommand

cerulean lake
deft kestrel
#

Oh, I thought this was my answer

cerulean lake
#

Learn to code? That question has nothing to do with ui.

cerulean lake
little cobalt
#

and not a error handler

cerulean lake
little cobalt
#

you could also do it for only one command ;3

#
@command_name.error
reef lake
#

i want to write a line that looks for channel named after the command user and it does simply work, it said nonetype has no attribute delete, i d like to know whats preventing this from working and a solution and thanks

lfg_channel = discord.utils.get(interaction.guild.channels, name=f'{sanitize_author_name(interaction.author.name)})
lofty parcel
#

interaction.author doesn't exist

#

It is interaction.user

little cobalt
#

ctx.author or interaction.user

quiet siren
#

Hm, I don't know what happened, but after an update to my bot every single commands have lost it's parameters

#

Like all of them

#

Like the parameters are just gone

#

any idea why?

lofty parcel
#

Comment out the command, run the bot, remove the comment, run the bot again

quiet siren
#

I mean like it's for every single commands

#

I'm just attaching it on as an example of what the structure is

#

but okay

#

i'll just try that

#

And.. that didn't work

#

It's confusing though

#

Nothing changed, beside the addition of 2 commands

#

Okay

#

So I've just tried to reinstall the main version of pycord

#

instead of installing from git repo

#

and that worked

#

So maybe something happened up there

autumn lantern
#

Slash command are not passing options on master for me as well. Application Commands in slash command groups work, but not top level @bot.slash_command() methods.

autumn lantern
#

does

pip show py-cord | grep Version

return Version: 2.4.1.dev214+gfc7b1042?

little cobalt
autumn lantern
#

Rolling back to 8af8454 fixes it. fc7b104 introduced the bug.

robust ginkgo
#
Ignoring exception in view <ProccessingOrder timeout=None children=2> for item <Button style=<ButtonStyle.success: 3> url=None disabled=True label='Accept Order' emoji=None row=None>:
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/ui/view.py", line 414, in _scheduled_task
    await item.callback(interaction)
  File "/Users/appletumu/Documents/GitHub/Tumbot/cogs/iaf.py", line 223, in accept_order
    await IAF.qm_ordering_logs(self, interaction, "interaction", "finish_order", send="qm_orders_log")
  File "/Users/appletumu/Documents/GitHub/Tumbot/cogs/iaf.py", line 120, in qm_ordering_logs
    user = self.bot.fetch_user(dsc_user_id)
           ^^^^^^^^^^^^^^^^^^^
AttributeError: module 'discord.bot' has no attribute 'fetch_user'

This happens with fetch_user, get_user, fetch_member and get_member

    user = self.bot.fetch_user(dsc_user_id)
           ^^^^^^^^^^^^^^^^^^^
AttributeError: module 'discord.bot' has no attribute 'fetch_user'
#

I have checked pip list and checked that I have the correct intents

autumn lantern
#

lowercase b

robust ginkgo
#

oh wait

#

i forgot to await it

little cobalt
#

but you also read the error right?

robust ginkgo
#

oh shoot wait

#

i see now

little cobalt
#

;3

robust ginkgo
#

💀

reef spire
#

how do i fix the certifcate problem?

wooden yew
#

Just updated pycord to its latest version. Now getting an error when trying to get the top role of a user.
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'User' object has no attribute 'top_role'

async def ban(self, ctx : commands.Context, member : discord.Option(discord.SlashCommandOptionType.user, description="The user you want to ban", required=True)...
if member.top_role >= ctx.author.top_role:

Calling the authors top role is not an issue, just the mentioned members.

lofty parcel
wooden yew
lofty parcel
wooden yew
#

thanbks

#

thanks&*

bitter scroll
#

Hi, is there an easy way to get the thread a command is used in (or null if used outside of a thread)? I don't see one in the context api and trying to get it roundabout through trying to use the response message also seems to mess up.

plucky moss
#

This is most likely the wrong channel to do so, but ill still ask: Recently, replit updated their policies, so now you can't host on replit with webservers. Does anyone else have any other methods of hosting for free? Heroku isn't working for me.

lofty parcel
plucky moss
lofty parcel
#

you won't really find a company that offers a free tier which doesn't ask you for a payment info ¯_(ツ)_/¯

#

Github student developer pack offers alternatives too.

plucky moss
dim raptor
#

how do i make a webhook post smth when i run a cmd

#

is it requests module?

shell radish
dim raptor
#

Ah thanks

oak onyx
#

How long can a view wait?

subtle moth
#

Hey, so i have a view that uses select menu and its callback edits the orignal message depending on the user's choice. This works fine but for some reason after editing the message the select option gets cleared. How do i prevent it?

class ProfileView(discord.ui.View):
    def __init__(
        self,
        author:int,
        general_embed_:discord.Embed,
        rpg_embed_:discord.Embed,
    ) -> None:
        
        super().__init__(disable_on_timeout=True)
        
        self.author = author
        self.embeds = {
            "General Stats": general_embed_,
            "RPG Stats": rpg_embed_,
        }

    @discord.ui.select(
        placeholder = "Choose the profile page",
        options = [
            discord.SelectOption(label="General Stats"),
            discord.SelectOption(label="RPG Stats")
        ]
    )
    async def select_callback(self, select:Select, interaction: discord.Interaction):
        await interaction.response.defer()
        if interaction.user.id != self.author:
            return await interaction.followup.send("This command isn't for you", ephemeral=True)
        
        await interaction.followup.edit_message(interaction.message.id, embed=self.embeds[select.values[0]])
pine yacht
#

Can I use discord.ext.commands.Greedy[T] in application commands? Or will I have to implement it myself?

little cobalt
#

#1193446964176617534

subtle moth
pine yacht
# pine yacht Can I use `discord.ext.commands.Greedy[T]` in application commands? Or will I ha...

I tried to do this:

    @root.command()
    @discord.guild_only()
    @commands.check(channel_must_support_webhooks)
    @discord.option("roles", commands.Greedy[discord.Role])
    async def mention(
        self,
        ctx: CommandContext,
        *,
        message: str,
        roles: commands.Greedy[discord.Role],
    ):
        """Minimize collateral pings by only mentioning members with all the roles you select.

        Args:
            ctx (CommandContext): The invocation context.
            message (str): The message to attach to the mention.
            roles (commands.Greedy[discord.Role]): The roles to select.
        """
        ...

but it keeps erroring with this log message: (see attachment)

little cobalt
#

Why? ;3

pine yacht
#

if I replace roles: commands.Greedy[discord.Role], with roles: list[discord.Role],, I get this instead:

little cobalt
#

role: discord.Role

pine yacht
#

I need to be able to take in any number of roles greater than 1...

little cobalt
#

I know ;3

#

The problem is, its not gonna work

#

you would have to use a role select

pine yacht
#

...i GUESS i could do that. but i would very much prefer if you could just put the list of roles in the invocation instead of in its own thing.

rugged lodgeBOT
pine yacht
#

Is there an elegant way to specify no maximum selection? i.e. you can choose any number of options from 1 to every. single. one.

#

My solution to this:

async def role_select_prompt(
    ctx: CommandContext, *args, **kwargs
) -> list[discord.Role]:
    assert ctx.guild is not None

    class RoleSelectView(View):
        selected: list[discord.Role]

        @role_select(
            placeholder="Select roles...", max_values=len(ctx.guild.roles)
        )
        async def update(
            self, select: Select, interaction: discord.Interaction
        ):
            self.selected: list[discord.Role] = select.values  # type:ignore
            await interaction.response.defer()

        @button(label="Submit")
        async def submit(
            self, button: Button, interaction: discord.Interaction
        ):
            assert self.message
            self.stop()
            self.disable_all_items()
            await interaction.edit_original_response(view=self)

    view = RoleSelectView(disable_on_timeout=True)
    await ctx.respond(*args, **kwargs, view=view, ephemeral=True)
    await view.wait()
    return view.selected
silk spire
#

That will error if you got more than 25 roles

#

Which is the max value of max value (lol)

#

Also defining a class in a function is disgusting

torpid ivy
#

so i was thinking that I could do something like "own_message = await ctx.reply("stuff") and then reply to my own message with own_message.reply("other stuff") later. but my interpreter is complaining about it

#

and I mistaken or does that work

#

seems like own_message becomes a WebhookMessage which inherits from Message which means i THINK i'm fine doing it that way?

little cobalt
#

is it a slash command?

torpid ivy
#

originally it's a slash command, and I want to reply to the user with a "Loading whatever, please wait" message, and then once the slash command function is done I want it to reply to that "Loading whatever, please wait" message with the image output

#

Or maybe there's even a better way to do that too

#

particularly because I vaguely remember discord complaining if you respond to a slash command too late, and the function running in the background takes up to like 45-60 seconds

#

though i suppose i COULD just send messages instead of replying to a slash command. so maybe that'd be better

little cobalt
#

you could just do ctx.respond again

#

but I would defer it

torpid ivy
#

I just don't like ctx.respond'ing to slash commands because you just get a reply to a message that doesn't exist

#

like it works but it looks ugly

dim raptor
#

so for the webhook in a cmd i put this code inside the cmd function but its not working at all

#

anyone know why

little cobalt
#

nice webhook ;3

#

do you have anything else installed?

red mist
little cobalt
#

xd

dim raptor
torpid ivy
#

boo. I have two slash command groups defined seemingly exactly the same way and the newer ones won't show

#

is there still some sorta timer or should it be instant

#

like does anyone see something here I don't

#

ignore the botw

#

i typed that by accident while taking the screenshot

little cobalt
#

How do you load the cog?

torpid ivy
#

just like the other one

#

I figured it out, sort of

#

The command shows up on one server, but not the other

little cobalt
#

so... you import the cogs to the main file?

torpid ivy
#

Yes

#

the main file is literally just a tiny file that initializes the bot, loads the cogs, and runs it

little cobalt
#

you could use client.load_extension(name="cogs", recursive=True) and dont have to import the stuff and adding the cog at the main file

shell radish
dim raptor
#

anyone know how to turn the button into a link

lofty parcel
dim raptor
lofty parcel
dim raptor
#

nah its reply

#

that part works

#

wait lemme test smth

loud kayak
#

Since user.mutual_guilds only returns mutual guilds that are in the cache, would I need to set chunk_guilds_on_startup back to True if I want all mutual guilds to be returned even on startup? My bot is in 5.8k servers do not setting it to false makes it take a while to startup.

edgy nest
#

yes

hallow blade
#

Want a custom selector view for role joining. Selector options would be a subset of roles on the server. Ideally would have the buttons enable if the user has/doesn'thave that role. Is this possible with the decorator style selector, and is there an example close to what I'm looking for? Specifically an example with the discord.ui.role_select as well.

#

In specific, I'm having trouble finding an example of dynamically adding something to a selector if that's an easy answer.

stray pasture
#

You cannot change permissions of individual slash commands in a slash command group ? It seems you can only change the permissions of the slash commands group but not the individual ones via the integration menu of your server

loud kayak
#

Is there an event that is fired before a command's function is executed so I can listen to it and do something before all commands?

shell radish
#

but not just slash comands

#

if normal commands, then on_message

loud kayak
shell radish
loud kayak
#

Like I don’t want commands to be usable while the bot is chunking guilds, since that takes a while for a big bot

#

Wait when is bot.is_ready set to True? After chunking guilds?

#

Oh according to the docs yes

rugged lodgeBOT
#
Specifies if the client's internal cache is ready for use.```
edgy nest
#

on_command supposedly is called before commands are run but it offers no way to control whether or not they execute

#

i think a check would be your best bet

pine yacht
#

There! ni li pona ala pona tawa sina? (is this good to you?)

class RoleSelectView(View):
    selected: list[discord.Role]

    @role_select(placeholder="Select roles...", max_values=25)
    async def update(self, select: Select, interaction: discord.Interaction):
        self.selected: list[discord.Role] = select.values  # type:ignore
        await interaction.response.defer()

    @button(label="Submit")
    async def submit(self, button: Button, interaction: discord.Interaction):
        assert self.message
        self.stop()
        self.disable_all_items()
        await interaction.response.edit_message(view=self)

    @classmethod
    async def prompt(
        cls, ctx: CommandContext, *args, **kwargs
    ) -> list[discord.Role]:
        assert ctx.guild is not None
        view = cls(disable_on_timeout=True)
        await ctx.respond(*args, **kwargs, view=view, ephemeral=True)
        await view.wait()
        return view.selected
silk spire
#

Yes

pine yacht
#

In other, class-factory news... ||i'm just doing this to trigger someone||

T = TypeVar("T")


def function_converter_factory(fn: Callable[[str], T]) -> Converter[T]:
    class FunctionConverter(Converter):
        async def convert(self, ctx: Context, argument: str) -> T:
            return fn(argument)

    return FunctionConverter()
silk spire
#

That's useless

#

You can use a lambda with Annotated

pine yacht
#

tenpo suno ale la sina kama sona e ijo sin. (you learn something new every day.)

#

how do you do that, exactly? i have never seen that in the docs!

silk spire
#

Nvm pycord doesn't support that mb

pine yacht
#

Confused it with Hikari? 💀

pine yacht
#

...Am I the only one who uses hash(" ") as a global interpreter session ID?

#

For idempotency?

deft kestrel
#

How can i make it not show this when someone uses a slash command

#

like it shows what they input

#

how do i hide that

little cobalt
#

you cannot hide it

#

you can only hide it if you send it as a ephemeral

deft kestrel
#

how do i do that though

little cobalt
#

?tag ephemeral

limber wagonBOT
#

An 'ephemeral' message is one that's only visible to the person who invoked a command. If you ever got a command error with a blue background, this is an example of one.

To do this, set ephemeral=True when you first use an ApplicationContext. (This includes .defer()ing it; the choice of whether a message is ephemeral or not must be made up front. If you .respond() to a deferred message, setting the ephemeral flag at that time will have no effect.)

This is the equivalent of hidden=True if you're coming from interactions.py

e.g.

await ctx.respond("Imagine a message!", ephemeral = True)

await interaction.response.send_message("Imagine a message!", ephemeral = True)
pine yacht
#

I use a fairly simple structure for my bot's cogs:

import logging

import discord
from pydantic import BaseModel

from core.bot import Bot, CommandContext
from core.embed_styles import OK

NAME = __name__.split(".")[-1].lower()
LOG = logging.getLogger(__name__)


class CogConfig(BaseModel):
    pass


class Cog(discord.Cog, name=NAME):
    def __init__(self, bot: Bot):
        super().__init__()
        self.bot = bot
        self.config = CogConfig(**self.bot.config.cogs.get(NAME, {}))

    root = discord.SlashCommandGroup(NAME)

    @root.command()
    async def hello(self, ctx: CommandContext, *, user: discord.User):
        await ctx.respond(
            embed=OK.embed(title="Hello", description=f"Hello {user.name}!")
        )

When I add a @discord.default_permissions decorator to a command, like:

class Cog(discord.Cog, name=NAME):
    # ...
    @root.command()
    @discord.default_permissions(administrator=True)
    async def delete(self, ctx: CommandContext, name: str):
      ...

I can still see and successfully invoke the command on my alt that lacks the specified permissions, with no overrides set. ||well, about as successfully as it can be invoked while my dev database isn't running||
When I go to my bot's integration settings, I only see the top-level command groups--mod, tags, etc.
Is it possible to set default permissions per command in a group, or will I have to break them out into separate commands/use a @commands.has_permissions decorator instead?

loud kayak
shell radish
ancient cosmos
#

Finally noticed this note on discord.File, which explains why I'm having issues "crossposting" a message with an attachment to multiple servers.

(Workflow: A user uses a slash command, provides some information via args, and optionally provides an attachment. That info then gets "broadcast" to a number of servers that want to receive the messages, including reposting the attachment, if provided, onto each of the broadcast messages that gets sent out.)

#

Okay, I can accept that Files are single-use; that said, is there a suggested pattern for posting the same attachment / file in multiple places?

shell radish
#

copy the link

ancient cosmos
#

Oh, so just grab attachment.url and repost that?

shell radish
#

think so. I don't have documentation memorized

ancient cosmos
#

👍, makes sense. Thanks

round heart
#

I don’t like Pycord’s “username (Display)” when printing users, and would prefer it to be the opposite “Display (username)”

What would be the best way of adjusting this from my own code (especially without having to import a custom class anytime I want to reference a User)

deft kestrel
#

why does it take so long to sync commands

#

like i put a command over 5 minutes ago it still doesnt show

#

is there a way to force sync them

#

?

little cobalt
#

you mean after a bot restart?

deft kestrel
#

yeaj

deft kestrel
little cobalt
deft kestrel
#

i use client

#

its been like 10 minutes now no cap

#

and idk why its still not here

#

wtf

little cobalt
#

refresh your discord client -> ctrl + r

deft kestrel
#

i even got on discord canary

#

on another account

#

still not there

#

idk

#

...

little cobalt
#

is the command at a cog?

lapis dock
sly karmaBOT
# deft kestrel ...

Application Commands Not Showing Up?

  • Uninstall libraries that conflict with the discord namespace (e.g. discord.py).
  • Invite your bot with the application.commands scope.
  • Load cogs before bot.run() (e.g. not in on_ready).
  • Do not override on_connect.
  • Update to the newest version of py-cord (see ?tag install).
  • Turn off User Settings > Accessibility > Chat Input > Use legacy chat input.
  • Share your code and errors.
round heart
# shell radish format(user)

Not sure I follow. Seems like it would be best to monkey-patch the __str__ so I don't have to think about it, but was just looking for other ways of accomplishing this.

shell radish
deft kestrel
#

AttributeError: module 'discord' has no attribute 'Bot'

#

how to fix this

little cobalt
deft kestrel
little cobalt
#

uninstall discord, discord.py and py-cord and only reinstall py-cord

deft kestrel
#

ok

#
Traceback (most recent call last):
  File "c:\Users\usern\Downloads\Bot\main.py", line 10, in <module>
    bot = discord.bot()
          ^^^^^^^^^^^^^
TypeError: 'module' object is not callable```
#

Still same error

vivid zodiac
lofty parcel
#

It is Bot not bot

vivid zodiac
#

Yeah

deft kestrel
#

It works now

vivid zodiac
#

😄

deft kestrel
#
import discord
from discord import app_commands
from discord.ext import commands


class ExampleCog(commands.cog):
    def __init__(self, bot):
        self.bot = bot

    @app_commands.slash_command(name='ping', description='pong')
    async def ping(self, ctx):
        await ctx.respond('Pong!')

def setup(bot):
    bot.add_cog(ExampleCog(bot))

this is returning
Failed to load cogs.test: Extension 'cogs.test' raised an error: ImportError: cannot import name 'app_commands' from 'discord' (/home/pi/.local/lib/python3.7/site-packages/discord/__init__.py)

#

this is my first time working with slash commands

#

I used to work with discord.py but just upgraded to py-cord

#

hmmmm i uninstalled discord.py and installed py-cord

#

so i don't think so?

#

unless i'm wrong

#

this is literally my fist time working with py-cord so I need basic basic help lol

#

any help would be appreciated

shell radish
shell radish
#

just use edit_original_response

rugged lodgeBOT
lofty parcel
#

Why interaction tho?

#

Commands receive ApplicationContext

#

so ctx.respond and ctx.edit should do it, the library handles it

loud kayak
#

Anyone know how user oauth works for connecting an application to your Discord account to get guilds?

#

I did create a separate help post but idk if anyone knows

lofty parcel
lofty parcel
#

when i said oauth/token i meant the endpoint

shell radish
#

it’s semantics, but user token is just not correct

#

and there’s a client secret

lofty parcel
#

Well it was a quick guide lolz

shell radish
loud kayak
#

What I was going to do is have the bot provide the user with the link. to connect, then once they are done connecting, they click a Done button, then bot uses bot.http to fetch guilds. If the user didn't connect it - meaning it says no access/permission from the api - the bot would use cached guilds.

shell radish
#

the user shouldn’t need to click a done button

lofty parcel
shell radish
round heart
#

Not if you don't know enough about OAuth 🙂

loud kayak
#

at least that is simple

shell radish
loud kayak
#

wdym

lofty parcel
#

You can pretty much integrate a Web server with the bot

loud kayak
#

im so bad with web servers

lofty parcel
#

And do some "caching"

loud kayak
#

i have no idea how to do it

lofty parcel
#

To store the user waiting for a response

shell radish
loud kayak
#

no

lofty parcel
#

I have a cog with a web server, sec

round heart
#

Polling is "Are we there yet? Are we there yet? ..."
Events are "We're here"

shell radish
loud kayak
#

I just don't know how to do the oauth and with a web server you're talking about

round heart
#

Of course, it'd have to be connected to the public web somewhere. Running through it in my head, wouldn't it be better to have a public endpoint simply passes messages (webhooks?) to the bot instance running internally

shell radish
lofty parcel
loud kayak
#

tbh if someone helps me create a system that does all that and gets the servers ill give nitro

#

i have too much stress from school to learn something new

shell radish
#

dark basically already did it

loud kayak
round heart
lofty parcel
#

And it's just a small bot so it's enough for me

shell radish
loud kayak
#

yeah i have no clue how to do that

#

tbh if someone helps me create a system that does all that and gets the servers ill give nitro

shell radish
#

you have a website right?

loud kayak
#

yeah

#

i didnt create it from scratch

lofty parcel
#

I'd do it, but not for nitro kek SCfloppaBIG

shell radish
#

you have the code for it tho

round heart
lofty parcel
loud kayak
#

o

shell radish
loud kayak
#

how much

loud kayak
#

or

lofty parcel
#

I mean, it is just there

loud kayak
#

hear me out

#

you could do it out of the kindness of your heart SA_rainbow_heart

lofty parcel
#

If you find my heroku link, then you can just spam requests cause I don't use authorizations or something

shell radish
#

hire dark as a part-time employee

lofty parcel
#

I never really planned protection for it

loud kayak
round heart
# lofty parcel If you find my heroku link, then you can just spam requests cause I don't use au...

Gotcha. In context of this conversation, that endpoint would naturally become public for oauth.
In any case, I'd love to hear more about how the env and code is set up, because I would like to do something like this myself and just want to get as much info as possible.

Is the bot that's running on Heroku open-source? I could get info from that instead of bugging you. (e.g. are you using FastAPI? If there's storage, is it just redis, since Heroku doesn't(?) have storage)

lofty parcel
# round heart Gotcha. In context of this conversation, that endpoint would naturally become pu...

Heroku provides config vars (aka env vars or secrets) which you can just access with os.getenv

I dunno what you mean by heroku open-source.
For the web server I use aiohttp.Web
If you mean storage as dB, I use motor. If you mean storage as cache, I don't use redis or something. If I have to store something temporarily, I just use a bot var to store stuff and then add/remove on use. (Which I kinda do for other cog which isn't the web server, I store active queues )

round heart
lofty parcel
#

Uhh, I think so

#

If you can't access that, then it isn't kek

round heart
#

It is. Will steal glean some inspiration. Thank you for sharing 🙏

lofty parcel
#

It is not the best bot, or the "cleanest" one. But yet my best creation. I am still learning so code can be messy.

round heart
#

We all are! But I still always seem to learn something new when I look at Pycord bot source.

.. for instance, putting generic error handlers in their own class

loud kayak
lofty parcel
shell radish
#
@bot.slash_command()
async def guilds(ctx):
    button = discord.Button(
        label="Click me to sync guilds!",
        style=discord.ButtonStyle.link,
        url=get_oauth_url(),
    )

    await ctx.respond(
        content="Click the button below to sync guilds!", view=discord.ui.View([button])
    )

    for attempts in range(12):
        user_oauth2_exists = ...  # probably some database endpoint
        if user_oauth2_exists:
            guilds = await get_user_guilds(ctx.author.id)
            break

        await asyncio.sleep(5)
    else:
        return await ctx.edit("Timed out!")

    await ctx.edit(f"Synced guilds!")


def get_oauth_url():
    return discord.utils.oauth_url(
        client_id=bot.user.id, redirect_uri="...", scopes=("identify", "guilds")
    )


async def get_user_guilds(user_id):
    access_token = {} # probably some database endpoint

    guilds = ... # api call to get guilds

    return []
``` this is my basic structure for the bot code i would think
loud kayak
lofty parcel
#

I do have examples with my own testing, but they're in my laptop. I can show you tomorrow morning.

lofty parcel
loud kayak
#

They do something with bot.state? What even is that?

#

Is that built into the library or was that custom?

#

It seems like that's how they store the user tokens

#

But it doesn't look like they have a webserver

lofty parcel
#

Sounds like some cache

loud kayak
#

But if they have no webserver, how are they getting the token?

lofty parcel
#

I dunno

loud kayak
#

What if instead of having a select menu for it, I have a panel in the server, voiding having to do any of the oauth. The user would select Open Thread.

lofty parcel
#

Up to you, but doesn't seem effective

loud kayak
#

I'm honestly open to ideas

#

I'm really increative when it comes to these things, that's why i didnt build my own stuff in Minecraft cat_clown

#

idk wtf im saying

lofty parcel
#

Looks like they do have a web

loud kayak
#

Oh

deft kestrel
shell radish
#

?tag install

limber wagonBOT
#

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

shell radish
#

in this case, you should uninstall pycord befeore re-installing

deft kestrel
shell radish
#

what IDE are you using

deft kestrel
#

VSC

shell radish
#

restart it

deft kestrel
shell radish
#

do you know how pycord slash commands work

deft kestrel
#

not really. my first time working with pycord

#
import discord
from discord import app_commands
from discord.ext import commands


class ExampleCog(commands.cog):
    def __init__(self, bot):
        self.bot = bot

    @app_commands.slash_command(name='ping', description='pong')
    async def ping(self, ctx):
        await ctx.respond('Pong!')

def setup(bot):
    bot.add_cog(ExampleCog(bot))
shell radish
deft kestrel
shell radish
#

.slashnoshow

sly karmaBOT
#

Application Commands Not Showing Up?

  • Uninstall libraries that conflict with the discord namespace (e.g. discord.py).
  • Invite your bot with the application.commands scope.
  • Load cogs before bot.run() (e.g. not in on_ready).
  • Do not override on_connect.
  • Update to the newest version of py-cord (see ?tag install).
  • Turn off User Settings > Accessibility > Chat Input > Use legacy chat input.
  • Share your code and errors.
deft kestrel
steep cliff
#

I’ll have to add a db to my discord bot. I’d prefer an oop approach to a functional one. Currently have a MySQL database, but have access to a vps as well, which would allow my to use some kinda self hosted db as well.
How would you go about this? Which library would you use?

reef ermine
#

how do I exactly use delete_original_response? heres my code for example


@bot.slash_command(name="пурдж", description="Очищает указанное количество сообщений в указанном канале")
@default_permissions(manage_messages=True)
async def purge(
    ctx, 
    количество: Option(int, description="Количество сообщений для удаления. По умолчанию - 10.") = 10,
    канал: Option(discord.TextChannel, description="Канал, в котором нужно удалить сообщения. По умолчанию - текущий канал.") = None
    ):
    if канал is None:
        канал = ctx.channel
    if ctx.guild.me.guild_permissions.manage_messages:
        try:
            deleted_messages = await канал.purge(limit=количество + 1)
            await ctx.respond(f"Удалено {len(deleted_messages)} сообщений в канале {канал}!", ephemeral=True)
        except discord.Forbidden:
            await ctx.respond(f"У меня нет прав на удаление сообщений {saj_emoji}", ephemeral=True)
    else:
        await ctx.respond("У меня нет прав на управление сообщениями.", ephemeral=True)```
#

I dont really understand how it works, because I cant use just ctx.delete_original_response()

plucky palm
sly karmaBOT
reef ermine
#

yea I've seen the documentation

#

its just me being dumb

#

cuz I still dont understand

plucky palm
# reef ermine cuz I still dont understand

You need to use await ctx.delete() if you want to delete the response your bot sent earlier; if you want to use specifically delete_original_response(), use await ctx.interaction.delete_original_response(), since neither Context nor ApplicationContext classes have this method, and Interaction (can be gotten with ApplicationContext.interaction) does have it.

reef ermine
#

ooh

#

now I understand

#

thanks a lot

plucky palm
#

just set name="your_option_name" in your Option()

reef ermine
#

thanks

plucky palm
reef ermine
#

Also, I can edit the interaction response, right?

plucky palm
#

Yes

#

await ctx.edit()

reef ermine
#

what about the ephemeral messages?

#

I dont think I can edit them

little cobalt
#

uh

#

you can edit them

reef ermine
#

thats insane

#

because last time

#

I remember myself developing a bot on pycord

#

it was impossible, or, maybe I was dumb

plucky palm
plucky palm
reef ermine
#

I remember also that was one of the reasons I moved to discord.js

#

and started making a bot on javascript

#

but thats hella hard

#

when I compare it to python bot

little cobalt
#

you cannot really compare it to a python bot

#

and they all still doing the same at the end

plucky palm
# reef ermine but thats hella hard

Pretty sure you're just unused to it and/or that's just not your thing; there ain't a thing like "hard" or "easy", if you already learned and use the language. As Zervy have already said, they all still do the same at the end.

balmy dome
#

Should I add cogs with slash commands to bot(bot.load_extention()) before "on_ready()" or in "on_ready()"?

shell radish
#

before

balmy dome
deft kestrel
#

how would i make the bot do something i tell it for example every 30 minutes

#

i saw somewhere that with sleep it will make events not working or whatever

#

or something like that

#

it will mess with the rest of the program

shell radish
deft kestrel
#

i got it working

#

can i only have 1 task runnijng at a time

shell radish
deft kestrel
#

look

lofty parcel
#

You can't start a task that you already started

sage tendon
#

Alright so very quick question

I have a on member join
I wanna sleep for 10 seconds and then check whether the member is still in
if i just use asyncio.sleep then check if member in member.guild.members, does that use the most-up-to-date version of the guild? or the one that was passed while the event was called?

lofty parcel
sage tendon
#

yea im testing rn, but i fear it is that

sage tendon
#

okay then

lapis condor
#

Does anyone have an updated/ just a working version of sending an embed as a dm to a user? i cant for the life of me get my code to work even though it has worked before...

I just keep getting "discord.errors.HTTPException: 400 Bad Request (error code: 50006): Cannot send an empty message" even though this is from the documentation for pycord.

little cobalt
#

"Cannot send an empty message"

young cove
#

I have an autocomplete that isn't searching properly. It populates the dropdown perfectly, but when a user starts typing one of the items instead of clicking on it, they receive "No Options Match your Search"

#

async def get_list_from_db(ctx: discord.AutocompleteContext):
    user = str(ctx.interaction.user)
    async with bot.db.cursor() as cursor:
        await cursor.execute([sql command])
        result = await cursor.fetchall()
        stringsList = [i[0] for i in
                       result]  # This takes the first item in each tuple from 'result' and converts it into a new list of strings
        return [name for name in stringsList if name.startswith(ctx.value.lower())]


@bot.slash_command(name="post", description = "Post a character book")
async def autocomplete_example(
        ctx: discord.ApplicationContext,
        name: discord.Option(str, "Select a character", autocomplete=get_list_from_db),
)
#

Works fine if they just click it, but a lot of people have been trying to type it and I can't figure out why it won't work. Thanks in advance for any thoughts

lofty parcel
young cove
lofty parcel
#

Lower all the items in stringslist

#

To then compare

young cove
lofty parcel
#

No idea. I dont use such thing.

young cove
#

No problem, thanks anyway

deft kestrel
#

why does it take a while for my slash command to register in a server?

#

like /ping is working but /translate is missing

outer niche
sly karmaBOT
# deft kestrel like `/ping` is working but `/translate` is missing

Application Commands Not Showing Up?

  • Uninstall libraries that conflict with the discord namespace (e.g. discord.py).
  • Invite your bot with the application.commands scope.
  • Load cogs before bot.run() (e.g. not in on_ready).
  • Do not override on_connect.
  • Update to the newest version of py-cord (see ?tag install).
  • Turn off User Settings > Accessibility > Chat Input > Use legacy chat input.
  • Share your code and errors.
outer niche
#

Wrong tag whoops

little cobalt
#

can you try from discord.commands

#

Can you show your pip list pls

little cobalt
#

@deft kestrel still there? ;3

fresh totem
#

if you're trying to import Option for Commands, it's
from discord.commands import Option

#

Hey, how can I create a slash command name with a blank space in between words instead of the _

I've tried

async def play_game(ctx: discord.ApplicationContext):```

won't let me run
little cobalt
#

else you would have to use a - or _

valid panther
little cobalt
#

;3

valid panther
fresh totem
rugged lodgeBOT
#

Here's the slash cog groups example.

little cobalt
#

its also ctx.respond and not ctx.send

valid panther
#

@little cobalt Is there a planned date for the update?

hazy turret
#

It is not possible to read the text in About me from the profile/server profile of a member on the server to check it for unauthorized words etc., is it?

subtle moth
hazy turret
fresh totem
fresh totem
#

uninstall all other discord libraries and keep py-cord only

sage tendon
#

Will the member.guild.members use an up-to-date status of the guild?

Like, if the member leaves before the 20s pass, will the member still be in member.guild.members?

robust turret
#

Any idea why is the except not working?

lofty parcel
#

.rtfm Member.ban

fresh totem
lofty parcel
#

It only raises Forbidden or HttpException

robust turret
wild hill
#

What is the var for dming a user from the bot been a bit since I was codeing.

marsh nymph
#

is there a way to defer() modal responses?

#

so they fill out the form but the bot needs more time to respond

#

to the filled out modal

little cobalt
#

if Im not wrong

marsh nymph
wild hill
little cobalt
#

you mean sending a dm message to a user?

wild hill
#

Ya from whatever user in said in the slash command.

#

it is for my warn command.

little cobalt
#

.rtfm Member.send

sly karmaBOT
little cobalt
#

@wild hill ^

wild hill
#

Also what do the error AttributeError: '_MissingSentinel' object has no attribute mean?

tender latch
#

Hi there, having a bot problem where I attempted to run a command while the code had an erroneous line in it, and now it is permanently stuck on (... Sending Command ...) despite restarting it several times.

#

Anyone has experience with this?

sage tendon
#

restart your discord

wild hill
#

Me?

sage tendon
#

no

tender latch
#

Hmm! Oh, that's embarrassing. Thank you. ^-^

wild hill
#

How would I go about getting the title of a server that a command is called in?

#

Like the name of the server not the id.

little cobalt
#

you can use stuff like ctx: commands.Context for more autocomplete at the IDE

sage tendon
#

or the docs :>

little cobalt
#

or that ;3

wild hill
# little cobalt ctx.guild.name

How would I define it in the function part as I am trying to store the name of the server and the mods name of the mod that warned said user.

little cobalt
#

The problem at saving the name is that you can change the name of the server or user

#

you should also store the server id

wild hill
#

Also is FastAPI a good thing to use to make a dashboard with?

little cobalt
#

I cannot say that

#

But you can use FastAPI, Flask

wild hill
little cobalt
#

I never used it

#

same for Django

wild hill
little cobalt
#

I would use Flask

wild hill
#

Do you know any good Tutorials that I can use to start off?

little cobalt
#

yea, but its in german x3

marble grotto
#

Is it possible to view webpages in Embed using a Bot?

lofty parcel
#

What?

deft kestrel
#

Hi guys, what should I do if I need to get, for example, 10 people using fetch_member, and 2 of them are not on the server and I need the bot to skip out, but the rest are not

deft kestrel
karmic solar
#

guys can u help me pls?

when I view my account, there is no problem, the variables are translated into different languages (depending on the choice), but if I try to view another user's account, then the variables if result:
status = "Premium" if user_language == 'ru' else "Premium"
else:
status = "Free" if user_language == 'en' else "Free"

if member.id == id:
permissions = "Admin" if user_language == 'ru' else "Admin"
else:
permissions = "User" if user_language == 'ru' else "User" remain in Russian

dawn prism
#

Hello, this is an emergency if anyone can help me.
I'm running a task like this :

def __init__(self, bot: Hackbot):
    self.bot = bot
    self.update_teams.start()

@tasks.loop(minutes=5.0)
async def update_teams(self):
    ...

I get the following error : Extension raised an error: RuntimeError: There is no current event loop in thread 'MainThread'

#

It occurs in all my loop but i don't understand why since I didn't changed my working method and how I create them and still there's this error now

#

Thanks in advance for any help

glass gyro
#

how do i make two tasks looping at the same time?

fresh totem
lofty parcel
#

Read the docs and you will see.

robust turret
lofty parcel
#

ApplicationCommandInvokeError is from the error handler iirc. Not from the method itself

fresh totem
sage tendon
#

If I have a listener for on_member_join, and do asyncio.wait(20) in it, and check the member's roles after those 20s using the passed member object, will that member object be up-to-date or be a snapshot of the time when the member joined?

lofty parcel
steep cliff
#

I have both a on_error and an on_application_command_error handler. Yet, I still get errors that bypass either handler when clicking buttons. Is it possible to catch them too using a global error handler?

deft kestrel
#

why is it that when I add a new slash command it takes forever to finally show up in the server?

lofty parcel
#

view.children is a list of all the items in your view

silk spire
lofty parcel
#

0

silk spire
#

It's a python list so 0

lofty parcel
#

It is a list.

lofty parcel
#

?

#

What am I suppsed to tell you

#

Youre trying to index an item that doesnt exist

silk spire
sage tendon
#

im p sure it worked in another command of mine like that lol

lofty parcel
#

Then its from 0 to 23, "bruv"

#

Then it is from 0 to 23 lmao

#

Python isnt dumb

#

If its telling you out of range, then youre out of range

edgy nest
stray pasture
#

Is on_audit_log_entry guarantied to be called with logs in order from the oldest to more recent on the same Guild. In the doc, it says it is called as log are created, so can I assume it is called in the right order ?

young skiff
#

How can I send an embed with a video?

lofty parcel
#

You cant

young skiff
#

thanks

lofty parcel
#

Don't know what you mean called in the right order

#

Each event is one audit log entry

stray pasture
#

yes, but I mean if they are a lot of events at near the same time in the guilds, can the function be called in a different order that they where created initially in the guild. Example: 2 log are created one after the other, but for some reason, the bot receives the second one before for whatever reason like network

young skiff
stray pasture
#

it is called in order the log are created or in order the events arrives to the bot

stray pasture
shell radish
steep cliff
dire quartz
#

How to fix

cannot import name 'Option' from 'discord'

?

little cobalt
short rivet
#

is it possible to get the ram usage of a specific shard ?

sage tendon
#

I'm tired as shit rn but i have an async def, so i need to do if await function() right

silk spire
#

Not specifically using an if statement but sure you need to await it in an async environment

sage tendon
#

well the function returns a boolean
and it's all inside of an event which is async
so idk

silk spire
#

Then sure

sage tendon
#

yea okay the main issue ended up being that i have a utils file, and within that file, i import discord.utils, and that messed things up a bit lol

open stone
#

why does ssl not working

lofty parcel
#

Thats the most unspecific question ive ever seen

open stone
lofty parcel
#

Show the error

open stone
#

Traceback (most recent call last):
File "C:\Users\PC\OneDrive\Dokumente\coding\Smarthelpo\main.py", line 21, in <module>
client.run('')
File "C:\Users\PC\OneDrive\Dokumente\coding\Smarthelpo\venv\Lib\site-packages\discord\client.py", line 717, in run
return future.result()
^^^^^^^^^^^^^^^
File "C:\Users\PC\OneDrive\Dokumente\coding\Smarthelpo\venv\Lib\site-packages\discord\client.py", line 696, in runner
await self.start(*args, **kwargs)
File "C:\Users\PC\OneDrive\Dokumente\coding\Smarthelpo\venv\Lib\site-packages\discord\client.py", line 659, in start
await self.login(token)
File "C:\Users\PC\OneDrive\Dokumente\coding\Smarthelpo\venv\Lib\site-packages\discord\client.py", line 515, in login
data = await self.http.static_login(token.strip())
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\PC\OneDrive\Dokumente\coding\Smarthelpo\venv\Lib\site-packages\discord\http.py", line 418, in static_login
data = await self.request(Route("GET", "/users/@me"))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\PC\OneDrive\Dokumente\coding\Smarthelpo\venv\Lib\site-packages\discord\http.py", line 283, in request
async with self.__session.request(
File "C:\Users\PC\OneDrive\Dokumente\coding\Smarthelpo\venv\Lib\site-packages\aiohttp\client.py", line 1187, in aenter
self._resp = await self._coro
^^^^^^^^^^^^^^^^
File "C:\Users\PC\OneDrive\Dokumente\coding\Smarthelpo\venv\Lib\site-packages\aiohttp\client.py", line 574, in _request
conn = await self._connector.connect(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\PC\OneDrive\Dokumente\coding\Smarthelpo\venv\Lib\site-packages\aiohttp\connector.py", line 544, in connect
proto = await self._create_connection(req, traces, timeout)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\PC\OneDrive\Dokumente\coding\Smarthelpo\venv\Lib\site-packages\aiohttp\connector.py", line 911, in _create_connection
_, proto = await self._create_direct_connection(req, traces, timeout)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\PC\OneDrive\Dokumente\coding\Smarthelpo\venv\Lib\site-packages\aiohttp\connector.py", line 1154, in _create_direct_connection
sslcontext = self._get_ssl_context(req)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\PC\OneDrive\Dokumente\coding\Smarthelpo\venv\Lib\site-packages\aiohttp\connector.py", line 967, in _get_ssl_context
return self._make_ssl_context(True)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\PC\OneDrive\Dokumente\coding\Smarthelpo\venv\Lib\site-packages\aiohttp\connector.py", line 919, in _make_ssl_context
return ssl.create_default_context()
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\PC\AppData\Local\Programs\Python\Python311\Lib\ssl.py", line 775, in create_default_context
context.load_default_certs(purpose)
File "C:\Users\PC\AppData\Local\Programs\Python\Python311\Lib\ssl.py", line 596, in load_default_certs
self._load_windows_store_certs(storename, purpose)
File "C:\Users\PC\AppData\Local\Programs\Python\Python311\Lib\ssl.py", line 588, in _load_windows_store_certs
self.load_verify_locations(cadata=certs)
ssl.SSLError: [ASN1] nested asn1 error (_ssl.c:4035)

Process finished with exit code 1

round heart
#

I want to create a slash command to set some configuration data.
Can I have the default value of the Option be its current value? If so, how can I reference that value from inside a Cog, because self isn't accessible within the decorator.

dawn prism
#

Hi everyone, i have a small issue.
I have a code where i store the ID of the last CategoryChannel created in a json file. When i read it i successfully get a CategoryChannel but when I try to execute the ̀create_text_channel function I get the following error : ̀'Object' object has no attribute 'create_text_channel'.

Does anybody knows why it's happening ? Thanks in advance 🙂

P.S. : I'm checking at the start and I get a good discord.CategoryChannel object by checking with type() function

lofty parcel
round heart
# lofty parcel Just handle it in your command callback

How do you mean?


@my_config.command('set')
async def config_set(
  self,
  ctx: discord.ApplicationContext,
  cfg1: Option(int, default=?, min_value=0, max_value=99),
  cfg2: Option(int, default=?, ...)
):
  # Handle what and how?
lofty parcel
#

default=None

#

if not cfg2:

use the default values

round heart
#

My question was whether the default value could be changed in such a way that when the next end-user uses the command, any updated values will be the default presented value

lofty parcel
#

default doesn't show to the user

#

It just makes the option not required

round heart
#

...oh. I thought for sure the default was auto-filled. Well alright then.

round heart
#

Still wish there was a good way to make dynamic changes to Application commands, though. Discord could make these much more user-friendly.

round heart
#

For Command Groups using default_member_permissions, if you set something like manage_channels=True, does that only allow people who have global (Role) access to it, or would someone that has access to manage a specific channel be able to use that command?

Edit: Was able to quickly test. They can use it in channels they have the associated access to. Kinda neat, but also ruins what I'm trying to do (which is gate it without explicitly changing it from Integrations)

timid shuttleBOT
#

Heads up @ember flint! We've detected one or more tokens in your attachments!

  • Found token of 1191231690446753803 (ultra mod) in attachment message.txt. You can regenerate it here.

Fyi: Each token might trigger a system message by discord, if it's valid.
Please avoid uploading tokens in future, even if they aren't valid anymore.

Stay Safe!

ember flint
lapis dock
# ember flint

try this article. FYI this is not directly a py-cord issue and is not due to issues in your code. You just have some installs wrong.

shadow junco
#
import discord
from discord.commands import SlashCommandGroup, option
import json
from discord.ext import commands

intents = discord.Intents.all()
bot = discord.Bot(intents=intents)

# ------ 讀取json檔案 ------
def load_file(file_name: str) -> dict:
    with open(file_name, 'r', encoding='utf-8') as files:
        loaded_file = json.load(files)
    return loaded_file

# ------ 儲存json檔案 ------
def save_file(file_name: str, data) -> None:
    with open(file_name, 'w', encoding='utf-8') as file:
        json.dump(data, file, indent=4, ensure_ascii=False)

@bot.event
async def on_ready():
    await bot.change_presence(activity=discord.Game(name="廢土伺服器 | mcFallout.net"))
    print(f'Logged in as {bot.user.name}')
    
check = SlashCommandGroup('check', '資料')
check_player = check.create_subgroup('player', '玩家')

async def get_ban(ctx: discord.AutocompleteContext):
    ban_data = load_file('ban.json')
    result_list = []
    
    for key in ban_data:
        result_list.append(key)

    return result_list

async def get_mute(ctx: discord.AutocompleteContext):
    mute_data = load_file('mute.json')
    result_list = []
    
    for key in mute_data:
        result_list.append(key)

    return result_list

@check_player.command(name='mute', description="取得指定被mute玩家的資訊")
@option(name = 'playerid',
        description='你要查詢的玩家',
        autocomplete=discord.utils.basic_autocomplete(get_mute),
        required=True)
async def search_muted_player(ctx: discord.ApplicationContext, playerid):
    await ctx.defer()
    if playerid is None:
        await ctx.respond('請輸入玩家 id')
        return
    elif playerid not in [target_player for target_player in load_file('mute.json')]:
        await ctx.respond('這個玩家並沒有被封鎖,或這個玩家不尚未被紀錄')
        return
    else:
        try:
            mute_data = load_file('mute.json')
            embed = discord.Embed(
                title=f'玩家: {mute_data[playerid]["player"]}',
                color=0x00ff00
            )
            
            embed.add_field(name='原因', value=mute_data[playerid]["reason"], inline=False)
            embed.add_field(name='時間', value=mute_data[playerid]["time"], inline=False)
            embed.add_field(name='連結', value=', '.join(mute_data[playerid]["links"]), inline=False)
            
            await ctx.respond(embed=embed)
        except Exception as e:
            await ctx.respond(f'發生錯誤:\n{e}')

@check_player.command(name='ban', description="取得指定被ban玩家的資訊")
@option(name = 'playerid',
        description='你要查詢的玩家',
        autocomplete=discord.utils.basic_autocomplete(get_ban),
        required=True)
async def search_banned_player(ctx: discord.ApplicationContext, playerid):
    await ctx.defer()
    if playerid is None:
        await ctx.respond('請輸入玩家 id')
        return
    elif playerid not in [target_player for target_player in load_file('ban.json')]:
        await ctx.respond('這個玩家並沒有被封鎖,或這個玩家不尚未被紀錄')
        return
    else:
        try:
            ban_data = load_file('ban.json')
            embed = discord.Embed(
                title=f'玩家: {ban_data[playerid]["player"]}',
                color=0x00ff00
            )
            
            embed.add_field(name='原因', value=ban_data[playerid]["reason"], inline=False)
            embed.add_field(name='時間', value=ban_data[playerid]["time"], inline=False)
            embed.add_field(name='連結', value=', '.join(ban_data[playerid]["links"]), inline=False)
            
            await ctx.respond(embed=embed)
        except Exception as e:
            await ctx.respond(f'發生錯誤:\n{e}')
            
            
bot.add_application_command(check)

bot.run('token')

why it doesn't show the options

#

for example, i use the code

@bot.slash_command(name="hi")
async def global_command(
    ctx: discord.ApplicationContext, num: int
):  # Takes one integer parameter
    await ctx.respond(f"This is a global command, {num}!")

and it shows that

Ignoring exception in command hi:
Traceback (most recent call last):
  File "C:\Python312\Lib\site-packages\discord\commands\core.py", line 131, in wrapped
    ret = await coro(arg)
          ^^^^^^^^^^^^^^^
  File "C:\Python312\Lib\site-packages\discord\commands\core.py", line 1006, in _invoke
    await self.callback(ctx, **kwargs)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: global_command() missing 1 required positional argument: 'num'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Python312\Lib\site-packages\discord\bot.py", line 1133, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "C:\Python312\Lib\site-packages\discord\commands\core.py", line 381, in invoke
    await injected(ctx)
  File "C:\Python312\Lib\site-packages\discord\commands\core.py", line 139, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: global_command() missing 1 required positional argument: 'num'
manic glen
#

Hello quick question I'm using v2.3.2 pycord

@commands.command()
    async def reload(self, ctx, type, filePath="0"):
```|
but bot is giving me error
```'BridgeCommand' object has no attribute 'name'```
deft kestrel
#

i have a command like this but it shows to people who dont have administrator aswell how can i make it not show to people who dont have administrator?

heavy sky
deft kestrel
heavy sky
#

default_permissions is global

little cobalt
empty fog
#

@plucky palm When we receive audio from discord in a voice channel, do we only get the data without any silence? If so, how can one interpolate the appropriate amount of silence between audio segments?

lapis dock
glossy latch
#

why when i use slash command, it doesnt appear when i type /

little cobalt
glossy latch
little cobalt
#

How do you load the cog?

glossy latch
#

when i replace that slash_command with commands.command it works

#

@little cobalt

little cobalt
glossy latch
glossy latch
sly karmaBOT
glossy latch
# loud kayak .idw
@discord.slash_command(name="reset", description = "Reset all verification points.")
    async def reset_verification(self, interaction: discord.Interaction):
        data = self.load_counting_data() 
        guild_id_str = str(interaction.guild.id)

        if guild_id_str not in data:
            data[guild_id_str] = []
        
        for user in data[guild_id_str]:
            user[0] = 0

        self.save_counting_data(data)

        await interaction.response.send_message("All verification points have been reset.", ephemeral=True)
#

for example this command it doesn't appear in slash commands list

#

should the bot have slash command supports badge ?

loud kayak
glossy latch
torpid ivy
#

I'm a tiny bit confused where to actuall put/define on_command_error to catch cooldown errors

loud kayak
loud kayak
torpid ivy
#

gotcha

#

I guess you can have separate handlers per cog or just an overall catch-all?

#

depending on where you do it

little cobalt
glossy latch
torpid ivy
#

instead of just erroring and saying the bot did not respond

loud kayak
proper bough
#

Hello, im getting this error:

discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: classic() missing 1 required positional argument: 'custom'

while im trying to add optional parameters to this command:

from discord import option

@bot.slash_command(description='Starts a classic game')
@option(
    "custom",
    description="Set a custom time for the game to start.",
    min_value=1,
    max_value=120,
    default=60
)
async def classic(ctx, custom: int):
  # OTHER CODE

ive tried, reading docs, checking the official github examples but with no luck, what could possibly be the problem, or its just that the parameters take time to register?

proper bough
little cobalt
little cobalt
#

at the option

proper bough
#

let me try rq

torpid ivy
#

ive never looked at the @option decorator, i've always just done them inline. interesting

#

assume its slightly different functionality

little cobalt
#

you can use the @option or discord.Option or discord.commands.Option

proper bough
loud kayak
# glossy latch

Uninstall discord-protos and discord-py-slash-command, don’t know why you thought you needed those installed.

proper bough
short rivet
#

when applying a cooldown to a command its only applied when the command is properly invoked which means if any of the checks of the command interupted the cooldown will not be applied but i wanted it such that even when the check is executed it applies a cooldown to it so i did this

def func_cooldown():
    def decorator(func):
        @wraps(func)
        async def wrapper(ctx: Context):
            dt = ctx.message.edited_at or ctx.message.created_at
            current = dt.replace(tzinfo=timezone.utc).timestamp()
            bucket = ctx.command._buckets.get_bucket(ctx.message, current)
            if bucket is not None:
                retry_after = bucket.update_rate_limit(current)
                if retry_after:
                    raise CommandOnCooldown(bucket, retry_after, ctx.command._buckets.type)
            return await func(ctx)

        return wrapper

    return decorator

what i wanted to ask is ... is there a inbuilt way to do this or am i good to go with this method ?

little cobalt
torpid ivy
#

fair

#

good to know

proper bough
#

ig my error is unique

torpid ivy
#

woo, got cooldown response working

little cobalt
#

^^

little cobalt
torpid ivy
#

i love how complicated this always looks but then it actually just works exactly like how you think it should

#

one thing i've noticed about this library lol

proper bough
torpid ivy
#

i should probably make sure i'm on the latest pycord too, heh

#

i just worry about breaking things

torpid ivy
#

whee, i get to make my first button. isn't it exciting

proper bough
torpid ivy
#

i changed my mind, brain not up to it rn

#

it's going to be quite an annoying button to build lol

loud kayak
short rivet
#

should i go with this only ?

shell radish
#

the code could be cleaner, but it looks like it works

zinc burrow
#

The answer you provided was exactly what I was looking for. However, I also wanted to preserve the state of the command, as you mentioned in the comment. Is there any way through which I can do it?

empty fog
lapis dock
#

As far as I know discord only gives a split audio stream. ChatGPT is not good at discor dbot development stuff.

empty fog
lapis dock
#

yes

wild tartan
#

I couldnt find anything on setting "edit custom message" in automod block messages.

        await guild.create_auto_moderation_rule(name='noWORD',
                                                event_type=discord.AutoModEventType.message_send,
                                                trigger_type=discord.AutoModTriggerType.keyword,
                                                trigger_metadata=discord.AutoModTriggerMetadata(
                                                    regex_patterns=[f'{regex_word}']),
                                                actions=[discord.AutoModAction(
                                                    discord.AutoModActionType.block_message, metadata
                                                ),
                                                    discord.AutoModAction(
                                                        discord.AutoModActionType.send_alert_message, metadata
                                                    ),
                                                    discord.AutoModAction(
                                                        discord.AutoModActionType.timeout, metadata
                                                    )
                                                ],
                                                enabled=True,
                                                exempt_roles=None,
                                                exempt_channels=None,
                                                reason=f'bad: {word}'
                                                )
#

also why does it seem like i need to add the same metadata 3 times?

#

metadata = discord.AutoModActionMetadata(channel_id=1078649685901856839, timeout_duration=timedelta(seconds=60)

short rivet
#

using bridge_commands cant we provide the description of an option ?

low solar
#
@bot.event
async def on_message(message):
        block_words = ["fuck", "shit", "http://", "https://"]
        for text in block_words:
            if text in message.content:
                await message.delete()
                return
            
        print('Cant Delete')

my bot has admin permissions so it should be able to delete the message but it doesn't

little cobalt
lapis dock
low solar
atomic fern
#

how to disconnect someone from vc? didn't find the attribute in docs

little cobalt
lapis dock
#

Just set the channel to none.

ivory meadow
#

When will the voice channel status change be added? d.py already has it

low solar
#

from what i read there is no such thing as "Ban duration", am i right?

short rivet
#

@lapis dock while using bridge_command can we not give the options a description?

short rivet
#

if i use discord.Option

#

then it wont work as a prefix command uk

little cobalt
#

are you sure about that?

#

at the end you still could use @discord.option() instead the the other discord.Option()

short rivet
# little cobalt are you sure about that?

ya like i had a command in which i had to have a limit of type int so if i give limit a type of option it wont work as normal prefix command since it will be unable to convert the given limit to an Option when using the command as a prefix command although i havent tried the same thing using @option decorator i guess that may work because in that i can just give the limit a type of int and then define it also as an option using the decorator

short rivet
#

it may work with the decorator i suppose

rugged lodgeBOT
#

Here's the slash options example.

little cobalt
#
@discord.option("member")
(ctx, member: discord.Member=None):
#

at the function

#

you could do it like that

short rivet
#

let me try that

lapis dock
low solar
lapis dock
#

It depends on how long the tempban is. I think asyncio sleep only support 10-15 min. Otherwise you will need to store the end date and check ever once and a while (with ext.tasks) to see if they should be unbaned.

low solar
#

i tought about making the bot save the exact time a user should be unbanned in a .json file and make it check the file every once in a while but yea ill try it

#

thanks

lapis dock
#

that is the idea. just make sure that you check if the date has passed in case you dont check at the exact time they should be unbanned. Also

#

.tag nojson

sly karmaBOT
#

JSON is a convenient and easy-to-read data storage protocol that's widely accepted by most programming languages. However, we caution against its use for storing and retrieving data in an asynchronous environment like a Discord bot. Don’t use json!

  • It's a file-based data storage, which makes it vulnerable to race conditions
  • You'll need to implement your own synchronization primitives to avoid corrupting data
  • If you're not careful, you could accidentally wipe your entire JSON file.

Solution? Use a database. Recommended schema are SQLite, PostgreSQL, and MongoDB.

  • Async libraries exist on pypi for each of these
    sqlite -- aiosqlite (or Danny's wrapper, ?tag asqlite)
    postgresql -- asyncpg
    mongodb -- motor
  • Databases organize your data into tables, and are fast at inserting, retrieving, and removing records
  • You can impose uniqueness constraints to ensure against duplication
  • The Python libraries enforce synchronization for you
  • The query language is intuitive, you can get running with simple queries in just a few hours!
short rivet
#

while using bridge_commands if i want to send a message (not reply) (ctx.send) when its a prefix command which means its context would be BrideExtContext and when its a slash command at that time i just want to respond (ctx.respond) so would i have to check each time using the isinstance method that if the command was used as a prefix command and then instead of responding just send the message
also ctx.send doesnt cache the sent message so ctx.edit wont work i have to save the sent msg in a variable and then edit it later while at the same time when the command is used as a slash command at that time since i use ctx.respond therefore i am able to use ctx.edit later to directly edit the message for some progress updates but this way i contstantly have to keep adding the check if isinstacne(ctx, BridgeExtContext) ... so is there any alternative to this or will i have to go with this only

frail basin
grizzled loom
grizzled loom
vivid zodiac
#

I have been trying to "interaction.response.edit_message" on an interaction I already responded to after a modal gets submitted, after doing a few operations on the modal's callback function and I am getting a "discord.errors.InteractionResponded: This interaction has already been responded to before" error.

Is there a way to simply edit the first response from a modal submission or the only way is by using "interaction.response.followup"?

ocean agate
#

can someone help me? its not recognizing discord_slash as a module even though i installed discord.py, discord-py-slash-command, and discord-py-interactions

ocean agate
lofty parcel
ocean agate
#

do you have a link to it

lofty parcel
#

Google does.

lapis dock
lapis dock
lapis dock
stray pasture
#

with the deleting of py-cord-dev, what version should we use in py-cord

lofty parcel
#

The github version just like it was specified in the message.

stray pasture
#

oh but that is just the master branch, it is not unstable ?

lofty parcel
#

It's not

stray pasture
#

I see thank you ! Will use that

vivid zodiac
short rivet
#
if ctx.is_app():
            await ctx.respond(embed=embed, view=view)
        else:
            await ctx.send(embed=embed, view=view)```
#

right now we will have to do this

#

also for the ctx.defer i would like it to be such that it only triggers typing if we pass that explicitly like ctx.defer(typing=True) otherwise it should just defer the normal slash command other wise again we will have to check if the command was used in an application context or ext context and respond accordingly

#

@lapis dock one more thing i would like to suggest is that when a view is orginated as a result of an interaction (not interaction.response.send_message only interaction.response.edit_message) at that time the views message is not set to the interaction.message automatically like it would have been set if the view orginated of a message command or as the reuslt of response.send_message same goes with when a view is orginated as a result of using ctx.edit in the context of Application Commands ... if the response to the command was something like ctx.defer() and later when we fetch some data and we use the ctx.edit and with this when we add a view also to the message the view.message doesnt get set and we explicilty have to set it like this .

view.message = await ctx.edit(embed=embed, view=view)```
#

one more thing while using the disable_on_timeout=True it obviously wont disbale in the cases when the view is orginated from a ctx.edit or interaction.response.edit_message since the self._message will be None as i mentioned above also if the view was a result of a message command and the view.message was set correctly even then if u delete the message and disable_on_timeout=True then the library will try to disable the view but since the message is deleted it will raise a NotFound error so i guess use a try xcept block over there

short rivet
#

one more thing in slash commands if the input type is Member for an option then if u provide a user id to it (not a Member id) (someone outside of the server) then it is not going to raise the MemberNotFound error i myself have to add that check

if isinstance(member, User):
            raise MemberNotFound(member)```
in prefix commands its does the job correctly it will raise the MemberNotFound error if the provided id was the id of user and not a member but in slash commands it doesnt raise the error
atomic fern
#

why commands.has_any_role won't work? i tried using name and id but nothing happens, like i don't have the required role (but i have it)

discord.ext.commands.errors.MissingAnyRole: You are missing at least one of the required roles: '['Gold', 1192424050857889843]'
pine yacht
#

Is there a utility function to let me quickly check if a string would violate a server's automod rules? Or, will I have to implement it myself?

obsidian stratus
#

on_error Includes what errors? normal cmds, slash & app commands & interactions too? and even python errors?

valid panther
#

Is there a way to make the buttons that don't have time, when the bot restarts still working?

rugged lodgeBOT
#

Here's the persistent example.

lofty parcel
#

@valid panther

valid panther
valid panther
#

Sad

grizzled loom
#

can someone explain what None = None line does exactly?

lofty parcel
#

It's typehinting

#

label: str | None = None

str | None typehinting. Can be a str or None.

= None default to None, the arg isn't required.

limber terrace
#

ahhh.
Yeah makes sense

I always forget that python has logical operators as symbols as well

#

Smth like Label = str or None would work as well there

little cobalt
#

I already use a lot of stuff like that

#

but I just do ```py
text: str
data: dict

#

its also helping a lot at the IDE for more autocomplete

shell radish
swift gust
#

how does one use discord.ButtonStyle.link

rugged lodgeBOT
#

Here's the link example.

lapis dock
#

Bascially have url= in your button creation

gilded crow
#

are hybrid groups supported in pycord?

shell radish
#

yes, it just goes under a different name

loud kayak
#

Is there an alternate to not having a super long on_ready with a big verified bot that has 5.7k servers to have guilds cached so I can see a user’s mutual guilds with the bot accurately?

#

Having chunk_guilds_at_startup as True just doesn’t allow on_ready to fire since it takes so long, and I need on_ready to fire.

shell radish
#

well, the bot is literally not ready

gilded crow
#

Umm in dpy we had commands.Author and we were able to use it as a default value for arguments

#

possible in pycord?

grizzled loom
# gilded crow possible in pycord?

yes, how to call it depends on what it is though. could be message.author in an on message event, would be ctx.user in a slash command, may have some other variation in other listeners.. but its there

grizzled loom
gilded crow
#

bridge command

grizzled loom
#

scratches head

gilded crow
grizzled loom
#

idk bridge command, sorry. Oh.. I missed your initial message.

gilded crow
#

oh ok

grizzled loom
#

Sorry i wasted your time 😅

gilded crow
#

it's ok no worries

little cobalt
#

its at the moment a prefix command

lapis dock
# gilded crow

ctx.author will give you the author of the command for prefix, slash, or bridge. You will have to set that manually in the callback if user is None. Also like zervy mentioned, your command is currently typehinted as a prefix command. The correct typehint for a bridge command would be BridgeContext

round heart
gilded crow
little cobalt
#

So... I have noticed that the master branch version is not adding the params to the slash commands at discord

#

its working fine if you just do pip install py-cord or a older master branch version

balmy dome
#

Is it true that the on_ready() function can be run several times? I just run tasks.loop() in my bot and later the console starts spamming with errors that tasks are already running(how to fix it?).

little cobalt
lapis dock
balmy dome
vivid zodiac
#

When sending an image file into a channel with the bot, is there a way to get the file URL from it before actually sending the image? I wanted to add a "Share on Twitter" button to that message, containing a tweet intent link with some text and adding that image to the tweet, but for that I would need an image URL

little cobalt
vivid crag
#

Is it possible to set a custom timeout date for AutoMod like you can with timing out a member through the API directly?

fleet maple
fleet maple
vivid zodiac
# little cobalt ```py (ctx, file: discord.Attachment): url: str = file.url```

Here's what I'm trying to do:

# Prepare scorecard image as a file
scorecard_file = discord.File(io.BytesIO(scorecard_bytes), filename="scorecard.png")

# Send the success message with the scorecard image
await success_channel.send(file=scorecard_file)

# Generate the tweet intent link
tweet_text = "Check out my success case on PNL Bot!"
tweet_intent_link = generate_tweet_intent_link(tweet_text, scorecard_file)

Before actually calling channel.send(), I wanted to get a real URL for the file, so that I can add a view containing a link button with the intent tweet. I was wondering if there was a way to get it before sending the message, or the only way was by sending the image on the channel, then retrieve the URL that Discord will create automatically and then edit it with the view containing the link button.

fleet maple
vivid zodiac
fleet maple
vivid zodiac
fleet maple
summer knot
#
@commands.Cog.listener()
    async def on_command_error(self, ctx, error):
        if isinstance(error, commands.MissingRequiredArgument):
            await ctx.send("Falta un argumento requerido.")
            await ctx.invoke(self.bot.get_command('help'), category=ctx.command.cog_name)
You'd have to get them from the message:

error:

Ignoring exception in on_command_error
Traceback (most recent call last):
  File "/home/container/.venv/lib/python3.11/site-packages/discord/client.py", line 378, in _run_event
    await coro(*args, **kwargs)
  File "/home/container/cogs/excepsiones.py", line 82, in on_command_error
    raise error
  File "/home/container/.venv/lib/python3.11/site-packages/discord/ext/commands/bot.py", line 347, in invoke
    await ctx.command.invoke(ctx)
  File "/home/container/.venv/lib/python3.11/site-packages/discord/ext/commands/core.py", line 942, in invoke
    await self.prepare(ctx)
  File "/home/container/.venv/lib/python3.11/site-packages/discord/ext/commands/core.py", line 872, in prepare
    await self._parse_arguments(ctx)
  File "/home/container/.venv/lib/python3.11/site-packages/discord/ext/commands/core.py", line 774, in _parse_arguments
    transformed = await self.transform(ctx, param)
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/container/.venv/lib/python3.11/site-packages/discord/ext/bridge/core.py", line 94, in transform
    return await super().transform(ctx, param)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/container/.venv/lib/python3.11/site-packages/discord/ext/commands/core.py", line 601, in transform
    raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: member is a required argument that is missing.

I was creating an exception cog but the script for some reason doesn't want to handle the error:
commands.MissingRequiredArgument
and also try with:
commands.MemberNotFound

lofty parcel
supple kiln
#

one of the bots in the server that my bot is in sent a message and when I try to get their member object they come up as a user rather than a member of the guild why is that?

#

why would a bot not show up as a member?

#

there is no issue with normal members

#
    @commands.Cog.listener()
    async def on_message(self, message):
        with Session(self.bot.DB) as session:
line 34>    statement = insert(user).values(member_id=message.author.id, guild_id=message.author.guild.id).on_conflict_do_nothing()
            session.execute(statement)
            session.commit()
            thisUser = session.query(user).filter_by(member_id=message.author.id, guild_id=message.author.guild.id).one_or_none()
            thisUser.message_count += 1
            session.commit()
#

I sent the wrong code at first whoops

little cobalt
supple kiln
#

What you suggested did fix it. I should have been using message.guild from the beginning I'm not sure why I didn't think of that before, though I'm still curious why the previous code didn't work.

loud kayak
#

Cuz then I can't access guild.members, which is preventing user.mutual_guilds from being used.

#

Would

for guild in bot.guilds:
  await bot.fetch_guild(guild.id)

cache the server members too?

solid sapphire
#

Hi! Is there a maximal number of option choices? (discord.Option().choices)

vital bramble
supple kiln
#

how would I go about making an option for a slash command that is a drop down

little cobalt
#

choices=[]

supple kiln
#

like say if for one option a user can set it to either on or off is there a way they can just click on or off rather than typing it

#

thank you

little cobalt
#

or autocomplete for other stuff

shell radish
#

pretty sure it's called choices

little cobalt
#

choices, yea

#

@supple kiln

supple kiln
#

I can't find any code examples for choices in the documentation

rugged lodgeBOT
#

Here's the slash options example.

supple kiln
#

thank you

#

you'd think the doc site would link to those examples

shell radish
#

it does

supple kiln
#

here on the options section there's like no links linking to places where you can learn more

#

it's just like "this exists"

#

oh this is the guide site

#

that's confusing

#

mb

lapis dock
#

Yeah, guide site is different. We should add More info links at the bottom tho

supple kiln
#
    @commands.slash_command(test_guild="1172086165332049980" , description="select whether you want to set the welcome dm or welcome channel message and attach your embed json")
    @option("type", description="select whether this embed will be DM'd to the user or sent in the welcome channel", choices=["DM", "WC"])
    @option("json", discord.Attachment, description="attach the embed json file you generated using the site embed.dan.onl", required=True)
    async def set_welcome_message(self, ctx, type: str, attachment: discord.Attachment):
        if attachment:
            await ctx.respond("thanks!")
        else:
            await ctx.respond("you didn't attach a file!")
little cobalt
#

you dont need the check

supple kiln
#

oh I've just realized what my issue was before I even finished typing out the question lol

supple kiln
little cobalt
#

I mean the attachment check

supple kiln
#

oh will the command fail if they don't fill it

little cobalt
#

you would only need it if required=False

supple kiln
#

I see

little cobalt
supple kiln
#

is there a way to send a custom mesage if they fail to add the attachment

#

oh I see

#

is there a way to specify a file type for attachments

shell radish
#

nope

supple kiln
#

rip

#

it's kind of unfortunate how slash commands feel less conversational than non slash commands

#

oh nevermind what am I saying you can definitely make it conversational

#

is there a way to refresh the slash commands in my client without having to close and reopen it

lapis dock
#

Ctrl+r hard refreshes discord. I have had few problems with slash commands not updating though. When developing you should add debug guilds to your bot so that it is slightly faster.

#

It is a kwarg of bot

short rivet
#

if i have made the help command using the HelpCommand class provided by the library how do we add the cooldown to that command ?

#

also i would like to make it a BridgeCommad

lapis dock
vestal folio
#

owner id

#

not owner name

lapis dock
#

Yes, read the second part

#

The user object you fetch will have the name

sly karmaBOT
lofty hedge
#

i think the only way would be if you have the guild ids stored somewhere, i may be wrong about that though. but i manually chunk my main server as i need that for some of my admin commands

vestal folio
#

i can not play a sound by my bot

#

the bot connect to lavalink but there is no sound

#

i have PyNaCl

#

lavalink and pycord

#

installed

hybrid tinsel
#

is it possible to get "segments" of the audio data that the sinks have or do i have to make the bot leave to get a workable file

fresh totem
#

Fixed it

slim scroll
#

how do I make a discord.HelpCommand recognize slash commands

vivid zodiac
#

Is there a way to let the InputText fields on a Modal only accept numeric values in a specific range? Other than validating the user input after they submit the modal, of course.

vivid zodiac
shrewd spade
#

Can we rebuild an Interaction object from it's ID? Motive is to defer the interaction, store in DB, and respond later

vital bramble
#

Also I think I read somewhere that interactions (even deferred) become invalid after about 15 mins or so.

cursive swallow
#

Correct

mighty otter
#

anyone knows how to sort to mathcing options with autocomplete context? (theres a list, when they write, only the elements that has a matching part with the input shows up)

vital bramble
#

I think that's automatically done by the discord client

mighty otter
#

hmm ty

little cobalt
mighty otter
#

autocomplete

lofty parcel
mighty otter
#

yes

lofty parcel
#

Then you have to return a parsed list by yourself

#

It's pretty much return [value for value if ctx.value.lower() in value]

rugged lodgeBOT
#

Here's the slash autocomplete example.

mighty otter
#

here's another question: how do i know if the user invoked the slash version or the prefix version of the command in bridge commands?

little cobalt
#

You can check it with is_app

deft kestrel
#

how do you add your bot to the menu when you right click a message and it shows there in Apps

rugged lodgeBOT
#

Here's the context menus example.

little cobalt
#

@deft kestrel

deft kestrel
#

thank you!

fresh totem
#

Figured it

plucky moss
deft kestrel
#

If I have a text saved in a variable, how would I go about sending that text as a file instead

#

I don't want to create a file, but I want to send it as a file on discord

lofty parcel
deft kestrel
#

can I use io

#

to just create the file in memory?

lofty parcel
#

I guess so

winged vault
#

Did discord ever add a way to check how a member joined, through the API? Or is that still something we have to find and store ourselves?

cursive swallow
#

You still need to track invites yourself

whole needle
#

how can i make modals?

glad garnet
slim scroll
#

How can I make a slash help command that recognizes slash commands?

vital bramble
#

use bot.commands

rugged lodgeBOT
shell radish
#

use that arg

whole needle
#
Ignoring exception in on_ready
Traceback (most recent call last):
  File "C:\Users\jarex\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 378, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\jarex\Downloads\TOOLS\Jarexs Tools\terracord\bot\terracord.py", line 36, in on_ready
    await connect_nodes()
  File "C:\Users\jarex\Downloads\TOOLS\Jarexs Tools\terracord\bot\terracord.py", line 14, in connect_nodes
    await wavelink.NodePool.create_node(
AttributeError: module 'wavelink' has no attribute 'NodePool'```

Following the wavelink doc and i get thsi
strong rain
#

Quick question: how can I respond to a deferred interaction with sending a modal?

shell radish
strong rain
#

What are some reasons why a bot takes so long to respond to an interaction? My hosting service provides 40 GB SSD Storage, and 3 GB RAM. Here is my code:

# main.py
@client.event
async def on_interaction(interaction):
  await client.process_application_commands(interaction)

Ready = False
async def on_ready():
  global Ready
  if not Ready:
    Ready = True
    for document in Load("Channels"):
      for messageID in document["CustomIDs"]:
        view = discord.ui.View(timeout=None)
        for button in document["CustomIDs"][messageID]:
          view.add_item(classes[button](**document["CustomIDs"][messageID][button]))
        client.add_view(view, messageid=messageID)
    print("Bot now online!")

for category in os.listdir("./commands"):
  for commandtype in os.listdir(f"./commands/{category}"):
    for command in os.listdir(f"./commands/{category}/{commandtype}"):
      if command.endswith(".py"):
        client.load_extension(f"commands.{category}.{commandtype}.{command[:-3]}")
        print(f"Loaded {category}.{commandtype}.{command[:-3]}")

print("Starting bot...")
client.run(os.getenv("token"))``````py
# commands/slash/utilities/ping.py
class Ping(commands.Cog):
  def __init__(self, client):
    self.client = client
  @slash_command(description="Provides the bot's latency")
  async def ping(self, ctx):
    await ctx.respond(embed=SetEmbed(ctx.guild,
      "Pong!",
      f"Executed in **{round(self.client.latency * 1000)}** ms!",
      discord.Color.green()))

def setup(bot):
  bot.add_cog(Ping(bot))```
When I run `/ping`, it may not always return an embed, and instead return `InteractionNotFound` Error. There is nothing in the code that I think makes the interaction response take a long time to respond, yet it still throws an error anyway.
#

When /ping does respond, the latency is 1 ms

#

In other words, what are some causes that prolong the duration an application responds to a slash command?

vital bramble
#

Network speed

valid panther
#

to get the default colour of the banner is with the colour = ctx.bot.user.colour ?

lofty parcel
#

You can't get that colour as far as I am aware.

celest atlas
valid panther
green oar
#

Hey there, I need quick help to use the ID of message / reaction because I do not understand why my code isn't working. Can I message there or should I create a thread ?

#

I also wanted to ask what's the point of using bridge command and what's the difference between these and normals command since I never used them

plucky moss
#
#main.py frfr
monitored_channels = [1185369048456904805, 1185355137187844107, 1185354638325715095, 1185355055713497249, 1185354338420400279]

@client.event
async def on_message(message):
    if message.channel.id in monitored_channels:
        try:
            await message.add_reaction('⭐')
        except discord.Forbidden:
            print("Bot doesn't have permission to add reactions in the monitored channels.")

    await client.process_commands(message)
#

Why dosent this work

#

What is wrong with it

#

No error message, it just dosent work

little cobalt
plucky moss
#

Yes it used to work. But when I switched hosting softwares it just stopped

silk spire
#

How many funcs called on_message do you got

agile oar
#

Anyone got a recommended solution for Persistent View's not always being loaded / randomly resulting in failed interactions?

This is not due to an issue in the view itself.

I initilise all persistent views via an on_ready() event listener.

Should I do this in a loop instead?

Please reply with ping. Thanks

cursive zealot
#

Hi guys I have a quick question: is it possible for a Select to keep the user's choice displayed after the callback ?
When I select something, the Select.values are correct and I can use them as expected, but at the end of the callback the Select goes back to it's label (I thought maybe by iterating through the options and setting their default attribute to True if they're selected but I wanted to know if I'm doing something wrong or if it's the normal behavior.
Thanks

little cobalt
cursive zealot
little cobalt
#

do you edit the select in any way?

cursive zealot
#
class OrganisationSelect(discord.ui.Select):
    """Allows the user to choose one or several diving organisations"""
    def __init__(self):
        self.view: Menu1

        options = [x.get_select_option()
                   for x in database.db.static_data['orgs']]
        
        super().__init__(
            placeholder='Fédérations',
            min_values=1,
            max_values=len(options),
            row=0,
            options=options
        )

    # Overriding the callback method
    async def callback(self, interaction: Interaction):
        # Selected certifications
        selected: list[CertificationOrganisation] = [
            await CertificationOrganisation(int(x)) for x in self.values
        ]

        # To only show certifications from the selected organisation(s)
        possible_certif = set([certif.id
                               for orgs in selected
                               for certif in orgs.certifications])
        
        self.view.diver.organisations = selected.copy()

        # As the certifications depend on the organisation, changing org select
        # will reset eventual certifications selected.
        if self.view.certif_select.values is not None:
            self.view.certif_select.values.clear()
            self.view.diver.certifications.clear()

        # Updating the choices offered in the certifications
        self.view.certif_select.update_certifs([await Certification(x) 
                                                for x in possible_certif])

        # Updating the view
        await interaction.response.edit_message(view=self.view)
#

When selecting

#

After the selection (PADI and SSI are not shown and I would like them to stay so the user doesn't think its actions didn't work)

#

(and the callback worked since the "Niveaux" Select is no longer disabled and offers the right choices) (sorry it's in french)

#

Added this bit to the first Select callback and it works, I was just wondering if there's another "cleaner" way

# Updating the view and keeping the user's choices selected
for opt in self.options:
    if opt.value in self.values:
        opt.default = True
little cobalt
#

and you have the newest py-cord version?

cursive zealot
#
❯ pip list | grep "py-cord"
py-cord-dev        2.5.0rc5
#

it's probably because I edit the message

#

but idk how to modify the second Select without doing it

rugged lodgeBOT
#

Here's the modal dialogs example.

cunning stirrup
#
@cog_ext.cog_slash(
        name="songrequest",
        description="Request a song and share it with others",
        options=[
            create_option(
                name="artist",
                description="The name of the artist",
                option_type=SlashCommandOptionType.STRING,
                required=True
            ),
            create_option(
                name="song",
                description="The name of the song",
                option_type=SlashCommandOptionType.STRING,
                required=True
            )
        ]
    )
      ``` how can i do that in pycord?
rugged lodgeBOT
#

Here's the slash cog example.

lofty parcel
#

@cunning stirrup

lofty hedge
#
DEBUG:asyncio:Using selector: EpollSelector
INFO:root:Starting bot
WARNING:discord.client:PyNaCl is not installed, voice will NOT be supported
INFO:root:CasinoHoldem cog initialized
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 817, in _match_option_param_names
    p_name, p_obj = next(params)
StopIteration
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.10/site-packages/discord/cog.py", line 789, in _load_from_module_spec
    setup(self)
  File "/home/container/cogs/casinoholdem.py", line 25, in setup
    bot.add_cog(CasinoHoldem(bot))
  File "/home/container/.local/lib/python3.10/site-packages/discord/cog.py", line 659, in add_cog
    cog = cog._inject(self)
  File "/home/container/.local/lib/python3.10/site-packages/discord/cog.py", line 548, in _inject
    command._set_cog(self)
  File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 609, in _set_cog
    self.cog = cog
  File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 855, in cog
    self._validate_parameters()
  File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 713, in _validate_parameters
    self.options: list[Option] = self._match_option_param_names(params, kwop)
  File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 819, in _match_option_param_names
    raise ClientException("Too many arguments passed to the options kwarg.")
discord.errors.ClientException: Too many arguments passed to the options kwarg.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "/home/container/bot.py", line 36, in <module>
    asyncio.run(main())
  File "/usr/local/lib/python3.10/asyncio/runners.py", line 44, in run
    return loop.run_until_complete(main)
  File "/usr/local/lib/python3.10/asyncio/base_events.py", line 649, in run_until_complete
    return future.result()
  File "/home/container/bot.py", line 33, in main
    bot = Bot()
  File "/home/container/bot.py", line 23, in __init__
    self.load_extension(cog_name)
  File "/home/container/.local/lib/python3.10/site-packages/discord/cog.py", line 913, in load_extension
    self._load_from_module_spec(spec, name)
  File "/home/container/.local/lib/python3.10/site-packages/discord/cog.py", line 794, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.errors.ExtensionFailed: Extension 'cogs.casinoholdem' raised an error: ClientException: Too many arguments passed to the options kwarg.``` whenever i try to add a slash command im getting this exception and not sure exactly why
#
import discord
from discord.ext import commands
from discord import ApplicationContext, Option
import logging


class CasinoHoldem(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        logging.info("CasinoHoldem cog initialized")
    @discord.slash_command()
    async def test(self, ctx):
        await ctx.respond('This is a test.')

def setup(bot):
    bot.add_cog(CasinoHoldem(bot))```
rugged lodgeBOT
#

Here's the slash cog example.

summer knot
stray sphinx
#

Hello 👋 can some one provide me a code-snipped for a /-command that provides a list of choices.
Or ist that only possible as modal?
I have tried it by my self... but with no success... :(

rugged lodgeBOT
#

Here's the slash options example.

steep cliff
#

Wrong example, my bad

rugged lodgeBOT
cursive swallow
whole needle
#
utilitys = terracord.create_group(name="utilitys", description="Utility commands!", guild_ids=[1198059337751474276])

class Verify(discord.ui.Modal):
    def __init__(self, ctx, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)
        self.ctx = ctx

        self.captcha = discord.ui.InputText(label="Captcha", placeholder="Enter Captcha")
        self.add_item(self.captcha)

    async def callback(self, interaction: discord.Interaction):
        if self.captcha.value.lower() == "TeRrAcOdE":
            role = discord.utils.get(self.ctx.guild.roles, name="Terrarian")
            await interaction.user.add_roles(role)
            await interaction.response.send_message("Verification successful! You've been granted the 'Terrarian' role.", ephemeral=True)
        else:
            await interaction.response.send_message("Incorrect captcha. Please try again.", ephemeral=True)

@utilitys.command(name="verify")
async def verify(ctx):
    if ctx.author.guild_permissions.administrator:
        embed = discord.Embed(
            title="**TerraCord Verification!**",
            description="`Please Follow The Captcha So We Can Prove That You Are Not A Robot!`",
            color=discord.Colour.green()
        )
        embed.set_image(url="https://i.imgur.com/3l2Sh41.jpg")
        embed.set_thumbnail(url="https://terracord.site/images/icon.png")

        view = discord.ui.View()
        button = discord.ui.Button(label="Verify", custom_id="verify_button")
        view.add_item(button)
        
        await ctx.send(embed=embed, view=view)
    else:
        await ctx.send("You don't have the required permissions to use this command.", ephemeral=True)

@terracord.event
async def on_button_click(interaction: discord.Interaction):
    if interaction.custom_id == "verify_button":
        verify_modal = Verify(ctx=interaction)
        await verify_modal.start(interaction.user)

I dont get any errors i just get this interaction failed

little cobalt
#

Py-cord does not have a event with on_button_click

frail basin
#

not entirely sure what terracord is 🤔

little cobalt
#

Terracord?

heavy sky
little cobalt
#

oh yea

lunar isle
#

Hey, can someone tell me how to check the ID of the message a user has replied to

lunar isle
#

(1199730370384507122)

lunar isle
lunar isle
lofty parcel