#Basic Pycord Help

1 messages · Page 6 of 1

plucky ingot
#

so I do it with icon_url = user.display_avatar.url

opal hamlet
#

What is the difference?

plucky ingot
#

its error and I don't know what it say

safe nest
plucky ingot
#

none of the problem about my code

safe nest
opal hamlet
#

Ahh yeah, that makes sense... Since there's also display-name

safe nest
#

:)

plucky ingot
#

it say missing access

#

so it is not my problem

safe nest
#

let's see the rest of the error message, I believe there should be a bit more

plucky ingot
#

its I have to turn on something in the developer portal

opal hamlet
#

Intents maybe?

plucky ingot
#

this is the back

opal hamlet
#

Maybe Member intents?

safe nest
#

it would usually give an error saying you need to enable the intent or smth like that iirc

plucky ingot
#

so how can I make it work

#

is it in the discord developer

opal hamlet
#

Under the bot tab of your application

safe nest
#

you can try that, but you're giving us no context to work with on why the error is popping up, we're just left to guess with what you've given us

#

we would need the full error to really even start, because I've never once seen an error on pycord that didn't give a line number in your code to trace the error back to

plucky ingot
#

here

#

oh wait

#
@project: b61cd8f3-b305-4e94-a2e9-481e92e4627a
@environment: 1ddf7202-ac60-42b2-bb83-8c6348836c5e
@service: 64569d90-0439-4b82-9561-aad45b100cdb
@deployment: cb246a29-8bef-49d8-9096-a5a8ffc22de2
@replica: 0511b7a7-a2e1-42c0-b293-3dd162de2283

Traceback (most recent call last):

File "/opt/venv/lib/python3.9/site-packages/discord/commands/core.py", line 110, in wrapped

ret = await coro(arg)

File "/opt/venv/lib/python3.9/site-packages/discord/commands/core.py", line 766, in _invoke

await self.callback(ctx, **kwargs)

File "/app/./bot/bot.py", line 167, in makeannouncement

await ctx.send(embed=embed)

File "/opt/venv/lib/python3.9/site-packages/discord/abc.py", line 1439, in send

data = await state.http.send_message(

File "/opt/venv/lib/python3.9/site-packages/discord/http.py", line 332, in request

raise Forbidden(response, data)

discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access

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

Traceback (most recent call last):

File "/opt/venv/lib/python3.9/site-packages/discord/bot.py", line 520, in process_application_commands

await ctx.command.invoke(ctx)

File "/opt/venv/lib/python3.9/site-packages/discord/commands/core.py", line 306, in invoke

await injected(ctx)

File "/opt/venv/lib/python3.9/site-packages/discord/commands/core.py", line 116, in wrapped

raise ApplicationCommandInvokeError(exc) from exc

discord.commands.errors.ApplicationCommandInvokeError: Application Command raised an exception: Forbidden: 403 Forbidden (error code: 50001): Missing Access
#

I can't find anyway to show
I know its very unclear sorry about that

safe nest
#
File "/app/./bot/bot.py", line 167, in makeannouncement

await ctx.send(embed=embed)```
#

the error originates from this line

#

are you absolutely positive the bot has permission to send messages in whatever channel you're running the command in?

plucky ingot
#

no

#

it work now

#

I am very sorry

safe nest
#

no worries, just keep in mind to send the full error log next time, it helps a ton

plucky ingot
#

actually I have one more problem

#

I already download everything from the pycord dev portal

#

but everything still error

#

is it have any different with mac and windows

#

Im on mac rn

safe nest
#

did you already run pip install python-dotenv py-cord?

#

if so, then try reopening the project

plucky ingot
safe nest
#

pycord is py-cord not pycord if I recall correctly

#

in pip anywho

#

and it's python-dotenv instead of dotenv, i noticed that one on your error list as well

heavy sky
#

And if you have installed python-dotenv and py-cord, tried reinstalling both and restarting vscode and it still doesn't work I'd recommend create a venv running it inside the venv instead. https://docs.python.org/3/library/venv.html

#

Oh, and also. I see you're trying to install pycord 2.0.0 in your code which is an old version of it. I'd strongly recommend using the newer version of it (2.4.1)

plucky ingot
#

same even I reinstalled

heavy sky
#

Try creating a venv and installing it in the venv

#

Then restart vscode

plucky ingot
heavy sky
#

Try using py instead

plucky ingot
#

ok

#

command not find:py

#

is it I have to put python3

#

many trys and still not work

rose roost
#

no

plucky ingot
fleet cedar
# opal hamlet What is the difference?

user.avatar will be None if they don't have any avatar set (the default red, green etc discord logo). But user.display_avatar will return the default avatar too

#

So display_avatar will 100% return an avatar url

fleet cedar
#

Did you create a venv?

plucky ingot
#

how can I create

#

Im noob sorry

fleet cedar
#

Google 🙃

plucky ingot
#

:<

fleet cedar
#

Pass the actual path to the venv, not the example text

rose roost
#

why it dont work

subtle juniper
#

why this event is not being triggered when I change my display name?

@bot.event
async def on_user_update(before, after):
print("triggered")
print(after.display_name)

opal hamlet
valid panther
#

I have a problem, when I make the paginator and with the Dropdown, I choose another type of data, it only maps the page in question. Then if I want to change the page, it returns to the base data.

class Dropdown_Type(discord.ui.View):

    def __init__(self, league_division: str):
        ....

    @discord.ui.select(
        placeholder="Selecciona un tipo de filtro",
        min_values=1,
        max_values=1,
    )
    async def select_type(self, select: discord.ui.Select, interaction: discord.Interaction) -> None:
        value = select.values[0]

        paginator = Paginator_Score(self.league_division, value)
        await interaction.response.edit_message(embed=paginator.pages[0])
hazy turret
#

Is there a way to receive a webhook with a Discord bot without extra webserver etc. to execute a function accordingly?

old violet
#

how to make group commands in pycord bridge

grizzled loom
#

If I upgrade to using the master branch instead of the pip version, is it fully backwards compatible?(with 2.4.1)

lofty parcel
#

Yes

grizzled loom
#

@stoic patio was your earlier question answerd? If so, what storage solution did you go for? and is it a one server bot or for many servers

dense veldt
#

how can i make a optional option in a slash command?

grizzled loom
dense veldt
#

so i do Optional() instead of Option()?

grizzled loom
#

or i show you one of mine, hang on:

dense veldt
#

i want to make the text option optional, so you dont need to put something in there

grizzled loom
#
@booty.slash_command(name="kick_status", description="Displays how many members and who exactly would get booted")
@commands.cooldown(1, 20, commands.BucketType.member)
@booty_needs_to_be_ready
async def emb(
        ctx: discord.ApplicationContext,
        days: discord.Option(
            int,
            "enter max days of being inactive, 90 if none are given",
            min_value=2, max_value=999, default=90
        )
):
#

Here you can see the integer has a default value of 90, thus it can be left empty.

to post code here use
```py
# code
```

so it becomes

# code
dense veldt
#

py

#

wait

#
async def dice(ctx, text: Option(int, description = "Höchste Zahl")):
heavy sky
#

Or you can just pass required=False

#

If you don't want a default value

dense veldt
#

ohh thats what i was looking for

#

thank you

heavy sky
#

No problems 🙂

opal hamlet
#

can i send a message with multiple embeds at once? f.e. embeds = {embed1, embed2} and then ...send(embed=embeds)

opal hamlet
#

ah yeah

#

but can i?

little cobalt
opal hamlet
#

would it work like that?

#

yeah should have done that

little cobalt
opal hamlet
#

thanks, want to somewhat foolproof my embed against character limit

little cobalt
#

So description have a limit of 4k and fields have a limit of 1024

opal hamlet
#

surprises me that the description is so large tho

little cobalt
#

I dont know the other ones

hardy drum
#

quick question - whats the difference between Application Command and Slash Command?

heavy sky
hardy drum
heavy sky
#

No, discord only has User and Message context menus as of right now

hardy drum
#

i mean not global facepalm, my bad

#

i mean like this

#

slash command can be global or guild

#

like that

heavy sky
hardy drum
#

can i create a slash command inside a function?

#

like command = Discord.SlashCommand(...)

little cobalt
#

it should work

#

you also could create a slash command class

hardy drum
#

okay thanks

#

i am trying to create a command that can load or unload a guild command

subtle juniper
#

why this event is not being triggered when I change my display name?

@bot.event
async def on_user_update(before, after):
print("triggered")
print(after.display_name)

heavy sky
#

so not when the display name is updated

subtle juniper
#

kinda need to switch to discord py sadly

heavy sky
#

hmm, do you have member intents enabled then?

subtle juniper
#

yea

little cobalt
#

did you also add member intents to the bot?

subtle juniper
#

every intent

little cobalt
#

which py-cord version do you use?

upper hearth
#

if i have a command that sends 2 msgs, how do i pick which one it edits

heavy sky
subtle juniper
little cobalt
#

2.4.1 or master branch?

opal hamlet
little cobalt
opal hamlet
#

oh it doesnt?

#

my bad

little cobalt
#

nope

opal hamlet
#

thats good to know

little cobalt
#

slash commands return an interaction object

stoic patio
upper hearth
stoic patio
grizzled loom
opal hamlet
#

btw how easy is it to get verification?

little cobalt
grizzled loom
grizzled loom
little cobalt
#

76?

#

wtf is that number

grizzled loom
#

yes, "over 75" is the offical limit to start verification. so you can begin the process when its 76.

little cobalt
#

oh

grizzled loom
#

just dont bullshit around with it, when discord assums "unorganic growth" ( meaning you just push it on 20 of your own or friends servers to hit 76) it wont start.

#

*in

#

anyways, i am curious about your storage thing 😄

#

you'll need to apply for message intend seperately with verification anyways, cause that's priviliged intent. they don't allow all usecases. especially when user data and/or message content is stored.

#

not saying you cant do or get it, but you need to explain and state your usecase.

opal hamlet
#

i assume automod functionality would be a valid usecase for msg intent?

grizzled loom
#

could be

grizzled loom
grizzled loom
#

usually you cant start official verification before 76 servers

stoic patio
#

i lost a few servers

#

lmfao

grizzled loom
#

Ahhh!

#

Okay makes sense

#

Did you also apply for priviliged intents?

stoic patio
#

yes

#

also, my storage as of rn is a dictionary with guild ids as keys and lists of recent messages as values

#

(recent means, every message that's added gets deleted afterwards)

#

after about ~20 seconds

grizzled loom
#

okay, now I am really curious

stoic patio
#

whenever someone sends a msg, i check the corresponding guild id

stoic patio
#

and the thing i'm using this for is anti fast messages spam

grizzled loom
#

soo.. what happens with the stored messages and how do people know who wrote what if its all deleted after 20 seconds?

stoic patio
#

so there is a rate limit (messages per unit time) set by the admins

#

suppose it's x messages per y seconds

#

we find the messages in the array sent within y seconds

#

and use listcomp to determine which were sent by the user

grizzled loom
#

I fail to see how this helps

#

I must be missing something.

stoic patio
#

what do you need clarification on

grizzled loom
#

how do you "sell" your bot when you advertise it on botlists or such? maybe it'll help if i read through his description

stoic patio
#

i don't think that's relevant to the antispam thing rn

#

it's an automoderation dc bot

grizzled loom
#

hmm

#

sounds like the stored data can become a lot pretty fast.

stoic patio
#

which is why i delete the msgs

grizzled loom
#

Ahhh! So it checks if the same message was posted before withing a given timeframe and prevents dublicates.

#

Reading through it made it make much more sense

stoic patio
#

i see

arctic plover
#

Hey guys, i wanna get item of view:

button = super().get_item(name)

But i get this error:

TypeError: super(type, obj): obj must be an instance or subtype of type

Why?

stoic patio
#

no idea

stoic patio
#

because guilds means less keys but each key contains a large array

#

and channels means a lot more keys but each key contains a small array

arctic plover
# lofty parcel Full code?
class test(discord.ui.View):
    def __init__(self, name):
        super().__init__(timeout = None)
        button = discord.ui.Button(label = 'Test', style = discord.ButtonStyle.grey, custom_id = name)
        async def test(interaction):
            button = super().get_item(name)
            super().remove_item(button)
            button.label = 'Hi!'
            super().add_item(button)
            await interaction.response.edit_message(content = 'Hi, {name}', view = super().__init__())
        button.callback = test
        super().add_item(button)


@bot.slash_command(name = 'testing')
async def testing(ctx, name:discord.Option(str, required = True)):
    view = test(name)
    await ctx.respond('Test', view = view)
lofty parcel
#

Just use self

#

And whats the point of subclassing a view if you're going to manually assign callbacks and buttons

arctic plover
lofty parcel
#

Then subclass the button

#

And add it to the view

arctic plover
grizzled loom
stoic patio
#

i just experimented with huge python dicts

lofty parcel
stoic patio
#

like it only took 2.5e-5 seconds to fetch smth from {i: [i**2]*2000 for i in range(100000)}

arctic plover
#

ty

shell radish
stoic patio
#

i can't

grizzled loom
stoic patio
#

well i'm using this for antispam

#

and i use databse queries to retrieve automod settings

#

which is already enoguh

grizzled loom
#

hmn. well, as long as all the comperrison work with strings can hold up. why not.

shell radish
#

what you're describing sounds like a cache, so I'll recommend redis if you ever have scaling issues.

grim estuary
#

Hello! How can I edit an already created field? Or is it only possible by deleting it and re-creating it?

shell radish
#

what field are you referring to?

grim estuary
#

Field in Embed

shell radish
#

you can replace the embed with a new embed

shell radish
grim estuary
#

Thank you!

arctic plover
#

I tried to use super().callback = callback

#

But here error that super() doesnt have attribute 'callback'

shell radish
#

items have callbacks, not views

arctic plover
shell radish
#

Do you know how OOP works?

arctic plover
#

It is written there:

In other words, the class that subclasses another class can inherit all the methods and attributes of that class.

#

all attributes

shell radish
#

ok, how do you override a method?

arctic plover
#

Like callback this is an attribute of discord.ui.Button

arctic plover
# shell radish ok, how do you override a method?

Here is my code:

class view_button(discord.ui.Button):
    def __init__(self, title, q_embed, link):
        async def view(interaction):
            link_button = discord.ui.Button(label = 'Go to question', style = discord.ButtonStyle.url, url = link)
            view = discord.ui.View(link_button, hide_button(title, q_embed, link), timeout = None)
            await interaction.response.edit_message(content = '(Viewed)', embed = q_embed, view = view)
        super().__init__(label = 'View', style = discord.ButtonStyle.grey, custom_id = f'view_{title}')
        super().callback = view
#

Maybe I'm dumb, but I don't understand

shell radish
#

this is an example of button subclassing

rugged lodgeBOT
#

Here's the button roles example.

arctic plover
shell radish
arctic plover
upper hearth
#

if i have a command that sends 2 msgs, how do i pick which one it edits

shell radish
#

specify the message to edit

upper hearth
#

one of the msgs is send by a button but i can't figure out how to make it edit the 2nd msg instead of original one

opal hamlet
upper hearth
#

i would do that but if two people do it at the same time it will mess up so im just gonna not do it

opal hamlet
#

can i see the code? mainly out of curiosity what you want to do

slow dock
#

can anyone help with this? All works correct but i get this warning

safe nest
#

At least that's the only way I've ever seen it used

slow dock
safe nest
#

Oh, nvm, forgot about decorators

#

Not sure why pylint is doing that lmfao

slow dock
safe nest
#

That's goofy

hasty cosmos
#

If I'm doing bot development testing locally, and run my main.py with updated code, is it necessary for bot users to reset their discord for updates to reflect?

lofty parcel
#

For callbacks, no

#

For visual stuff like commands names, options names etc, could be

hasty cosmos
#

Ahh okay yeah I changed a command name, also some method for how the command's calling a backend database. It updated once I reset, just curious 🙂

Is there a delete_category() command, similar to create_category?

#

I couldn't find one in the docs

lofty parcel
#

delete a channel category?

hasty cosmos
#

Yeah

lofty parcel
#

I think categories are treated as channels

#

So if you get the category, there should be a delete() method iirc

#

.rtfm Category

hasty cosmos
#
    async def create_category(
        self,
        name: str,
        *,
        overwrites: dict[Role | Member, PermissionOverwrite] = MISSING,
        reason: str | None = None,
        position: int = MISSING,
    ) -> CategoryChannel:
        """|coro|```

Like the opposite to this
hasty cosmos
lofty parcel
#

.rtfm delete_category

sly karmaBOT
#

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

lofty parcel
#

Looks like there's not

hasty cosmos
#

ahh so I can't use something like, discord.CategoryChannel.delete(category_id)?

#

oh I see

#

class discord.CategoryChannel(*, state, guild, data)

lofty parcel
#

delete() doesn't take any arguments

#

Just an optional reason

hasty cosmos
#

Nah but CategoryChannel does, I could do something like this?

class CategoryChannel(discord.abc.GuildChannel, Hashable):
    def __init__(
        self, *, state: ConnectionState, guild: Guild, data: CategoryChannelPayload
    ):
        self._state: ConnectionState = state
        self.id: int = int(data["id"])
        self._update(guild, data)

Obviously I'd need to update how I'm getting guild and data payload im not exactly sure how to yet, but I'm also clueless if this is proper 🤣
await discord.CategoryChannel(guild=ctx.guild, data=category_id).delete()

#

it worked pogthumbsup

category_channel = ctx.guild.get_channel(category_id)
if isinstance(category_channel, discord.CategoryChannel):
      await category_channel.delete()```
lofty parcel
#

You're editing the library code?

hasty cosmos
#

No

lofty parcel
#

Oh lol

hasty cosmos
#

just using delete() by grabbing the payload category channel 🙂

#

Although it would be nice to have a delete_category to complement create_category

#

I wouldn't mind working on adding that to lib it wouldn't be that difficult

lofty parcel
#

I'm sure there's no such method because of the way I said

#

Just like how delete_channel doesn't exist (I think)

hasty cosmos
#

It doesn't, I'm saying adding it to guild.py would make sense though

#

I don't know how to contribute to the lib though

#
    def _add_channel(self, channel: GuildChannel, /) -> None:
        self._channels[channel.id] = channel

    def _remove_channel(self, channel: Snowflake, /) -> None:
        self._channels.pop(channel.id, None)```
It'd be like this, excelt create_category, and delete_category
lofty parcel
hasty cosmos
#

Sounds good thanks

slender lantern
#

Is there a way to see if a user has permission to run a specific slash command in a given channel?

daring grove
#

essentially, after a few minutes or so my buttons stop working and say 'interaction failed' - i want to keep them working

lofty parcel
#

If you don't want a timeout, pass timeout=None to the class

daring grove
#

oh so is timeout by default 3 minutes?

lofty parcel
#

Buttons will still stop working after restarts.

lofty parcel
daring grove
#

also one more thing

#

after a condition, i want to bot the run a command

lofty parcel
#

What

daring grove
#

i do a command and it sends this
as expected

#

however after the queue is full, i want the bot to automatically send another one

#

i dont want to have to run the command again

lofty parcel
#

Once there are 14 users?

daring grove
lofty parcel
#

Then you'd need to run a condition on your button callback

#

And send a new queue message

daring grove
#

is there any way to just send a message in an interaction

#

without it being the response?

lofty parcel
#

interaction.channel.send?..

daring grove
#

right well im a bit silly

#

thank you for your wisdom

brave ore
#

is this a embed edited by markdown format? by flow official docs markdown 101 I cant create a embed like this, such as the image.

brave ore
#

I tried, but the code block created by me has no color like this.

lofty parcel
#

It's some syntax highlighting

#

Dunno what language it is

brave ore
#

OK, I'll try again, thx.

hasty cosmos
#

.rtfm admin

old violet
#

how to edit bridge help command
any reference for that?

fleet cedar
#

Bridge help command?

devout glacier
#

how to use the voice recorder

rugged lodgeBOT
#

Here's the audio recording example.

heavy sky
#

@devout glacier ^

devout glacier
#

thans

vague notch
#

quick question, how do i remove the reply part of the message

#

context.send() works but it never finishes the command and it sends an error to the user

#

context.send_response() and .respond() both reply like that

vague notch
#

well i found a hack, it's sending a response with delete_after=0

#

it's not the best but it works

plucky ingot
#

shit Im stuck up

@bot.command(description = "get members avatar")
async def avatar(ctx, user:str):
    user = ctx.user
    embed = discord.Embed(
        title = "here is the avatar",
        color = discord.Color.dark_purple(),
    )
    embed.set_image(url = f"{user.dislay_avatar}")
    await ctx.respond(embed=embed)

how to let members to mention a person to get their avatar

plucky ingot
vague notch
#

but then the command hangs forever executing

plucky ingot
#

await ctx.send("hello")

vague notch
#

it sends the message but the command execution is stuck

#

and then sends an error

#

but yeah sending a response which disappears immediately fixed it

plucky ingot
#

but the reply and the command is separate

plucky ingot
plucky ingot
#

I still can't input a value

daring valve
plucky ingot
daring valve
plucky ingot
daring valve
lofty parcel
#

Lmao

opal hamlet
#

i saw that

lofty parcel
#

Random sticker discords fault 😭

opal hamlet
#

what was that lol

#

sure sure

lofty parcel
plucky ingot
#

the bug fix already

#

and right now

#

it append another problem

lofty parcel
#

I wouldn't consider it a bug but ok

plucky ingot
#

It say 'NoneType' object has no attribute 'dislay_avatar'

#

ah wrong speeling

#

:>

opal hamlet
#

how would yall trigger a func or whatever from one bot in another bot? (main bot that triggers audio bots in different channels) WEbSockets or?

lofty parcel
#

That depends on the other bot

#

Not your bot

opal hamlet
#

nah they all are my bot

#

they play alarm sounds in VC channels(Star Citizen Org/Fleet events)

#

currently using !1 / !joib/leave etc. since they can all listen to that, but i want my main bot to have buttons to trigger em

#

only way i'd know wold be Sockets, but maybe someone has a better idea

plucky ingot
#

ahhhhh
File "/app/./bot/bot.py", line 186, in avatar

embed.set_image(url = f"{user.display_avatar}")

AttributeError: 'NoneType' object has no attribute 'display_avatar'

#

why Not work

#

Im mad

opal hamlet
#

user.display_avatar.url maybe?

plucky ingot
#

actually It have another thing

opal hamlet
#

since you aren 't passing the URL I guess

plucky ingot
#

I can't let member input a member to get their avatar

opal hamlet
#

what are you trying to do?

plucky ingot
#

a member choose the command call avatar
they mention a user and the bot will send out that member's avatar

opal hamlet
#

well i can send you my func that does that if you want

#
                       description='Fetches a users avatar.'
                       )
    async def get_avatar(self, ctx, 
                         member: Option(discord.Member)
                         ):
        """
        Retrieves a user's Avatar.
        """   
        asset = member.avatar.url
        await ctx.respond(asset)```
#

replace utility tho, thats just a command group

plucky ingot
#

oklet me try

opal hamlet
#

member: Option(discord.Member) this is neat tho because it only lets users pick members/users

heavy sky
plucky ingot
# heavy sky Show the code
@bot.command(name='useravatar',description='Fetches a users avatar.')
async def get_avatar(self, ctx, member: discord.Option(discord.Member)):
    user = ctx.user.id
    embed = discord.Embed(
        title = f"here is <@{user}> avatar",
        color = discord.Color.dark_purple(),
    )
    asset = member.avatar.url
    await ctx.respond(asset,embed=embed)
heavy sky
#

Are you getting any errors?

#

when you're trying to execute the command?

plucky ingot
#

TypeError: get_avatar() missing 1 required positional argument: 'ctx'

heavy sky
#

Do you have this code in a cog or in the main file?

#

If it is in the main file, remove self

plucky ingot
#

same

#

even I remove self

heavy sky
#

Try this

@bot.command(name='useravatar',description='Fetches a users avatar.')
async def get_avatar(ctx, member:discord.Member):
    user = member.id
    embed = discord.Embed(
        title = f"here is <@{user}> avatar",
        color = discord.Color.dark_purple(),
    )
    asset = member.avatar.url
    await ctx.respond(asset,embed=embed)```
plucky ingot
#

It work thank everyone

plucky ingot
# heavy sky Try this ```py @bot.command(name='useravatar',description='Fetches a users avat...

actually I add somthing on it and here is how the code look like right now

@bot.command(name='useravatar',description='Fetches a users avatar.')
async def get_avatar(ctx, member:discord.Member):
    user = ctx.user
    embed = discord.Embed(
        color = discord.Color.dark_purple(),
    )
    asset = member.display_avatar.url
    embed.add_field(name=f"Here is the person avatar", value=f"{user.display_name}", inline=True)
    embed.set_image(url=asset)
    embed.set_footer(text="DO NOT USE THIS COMMAND TO ABUSE DISCORD TOS")
    await ctx.respond(embed=embed)
#

Im trying to let the bot printing and person mention's username and his avatar

heavy sky
#

👍

plucky ingot
#

like this the what it look like right now
but the bot is showing my name instead of its username

heavy sky
plucky ingot
#

oh

#

yea

#

Im bad at logic lol

heavy sky
#

lol

deft kestrel
#

How to use pip install Import option for slash commands?

heavy sky
deft kestrel
#

My code:

import discord
from discord.ext import commands
from typing import Union
from discord import option

class Verify(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @commands.slash_command(name='verify', description="Верификация пользователя")
    @commands.option("пользователь", description="Укажите пользователя для верификации", type=commands.User)
    async def verify(self, ctx, пользователь: discord.User):
        if пользователь == ctx.author or пользователь.bot:
            await ctx.send("Вы не можете верифицировать себя, либо бота.")
            return
        
        user_joined_at = пользователь.joined_at.strftime("%d.%m.%Y %H:%M:%S") if пользователь.joined_at else "Неизвестно"
        user_created_at = пользователь.created_at.strftime("%d.%m.%Y %H:%M:%S")
        
        device = "Неизвестно"
        if пользователь.activities:
            for activity in пользователь.activities:
                if isinstance(activity, discord.CustomActivity):
                    device = activity.name
                    break
        
        embed = discord.Embed(title="Верификация пользователя", color=discord.Color.blue())
        embed.set_thumbnail(url=пользователь.avatar_url)
        embed.add_field(name="Пользователь", value=пользователь.name, inline=False)
        embed.add_field(name="ID Пользователя", value=пользователь.id, inline=False)
        embed.add_field(name="Присоединился на сервер", value=user_joined_at, inline=False)
        embed.add_field(name="Создан аккаунт", value=user_created_at, inline=False)
        embed.add_field(name="Устройство", value=device, inline=False)
        
        await ctx.respond(embed=embed)

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

heavy sky
#

Use @option instead of @commands.option

deft kestrel
#

Thanks

opal hamlet
sly quail
#

What do I need to do to get the bot to send reponses only a specific user can see

sly quail
shadow bear
#
    @commands.Cog.listener("on_message")
    async def on_message(self, message: discord.Message):
        log.debug("Received new message: %r", message)

Is there anything glaringly wrong I'm doing here? The event is supposedly firing however my handler isn't getting it

#
[2023-08-23 15:15:12 DEBUG] discord.gateway: For Shard ID None: WebSocket Event: {'t': 'MESSAGE_CREATE', ...}
[2023-08-23 15:15:12 DEBUG] discord.client: Dispatching event socket_event_type
[2023-08-23 15:15:12 DEBUG] discord.client: Dispatching event message
#

that's it

#

(The cog is loaded, [2023-08-23 15:14:53 INFO] cogs.counting: Counting cog loaded is further up)

#
@bot.listen("on_message")
async def foo(msg):
    logging.debug("msg: %r", msg)

This also isn't firing anything

shadow bear
#

discord.Intents.all()

#

and in dev portal

#

regardless, its still claiming to be dispatching the event

#

but no listeners are picking up on it

#

ctx.respond returns Interaction, you'll want await msg.edit_original_response

little cobalt
shell radish
#

and probably don’t name it msg

shadow bear
#

there is?

little cobalt
#

You can use ctx.edit(content="")

shadow bear
#

Oh ctx.edit does weird shit to my ide I avoid it KEKW

#

ctx.edit(embed=embed2)

#

instead of msg.edit

little cobalt
#

that would edit the message

shadow bear
#

it edits the original interaction last time I checked

shell radish
#

You sent it with ctx

shadow bear
#

it just does what i said but shorter

shell radish
shadow bear
# shell radish could you show how your `bot` object is defined
bot = commands.Bot(
    commands.when_mentioned_or("j!", "J!"),
    help_command=commands.MinimalHelpCommand(),
    case_insensitive=True,
    intents=discord.Intents.all(),
    debug_guilds=getattr(config, "DEBUG_GUILDS", None),
)
bot.loop.run_until_complete(db.registry.create_all())
bot.load_extension("cogs.counting")

@bot.event
async def on_ready():
    logging.info("Bot ready")
    print(f"Logged in as {bot.user} ({bot.user.id})")


bot.run(config.TOKEN)
#

Weirdly enough, the @bot.listen listener works when debug_guilds is None

#

but the cog listener is still doing nothing

shell radish
#

I think you’re supposed to use “message” instead of ”on_message”

shadow bear
#

That seems like a drastic change, its always been on_message afaik

#

I'm on 2.4.1

#

two seconds

#

Nope, still nadda with just message

shell radish
#

What type of cog are you using?

shadow bear
#

commands.Cog

little cobalt
shell radish
#

did you super().__init__() it?

shadow bear
#
class CountingCog(commands.Cog):
    def __init__(self, bot):
        self.bot: commands.Bot = bot
        ...
        log.info("Counting cog loaded")

    @commands.Cog.listener("message")
    async def message(self, message: discord.Message):
        log.debug("Received new message: %r", message)
        ...


def setup(bot):
    return CountingCog(bot)
#

no i did not

#

I forgot about that

#

I feel dumb now, thanks KEKW

shadow bear
#

tbf most of the text commands will be admin related stuff so the slash commands don't get cluttered up, its not a big deal

#

weird, even with super().__init__(), its not doing anything

#

also according to the doc, super() isn't needed

little cobalt
#

so change it both to on_message or change message at the () to "on_message"

shadow bear
#

I've tried both combos

#
    @commands.Cog.listener("on_message")
    async def on_message(self, message: discord.Message):

this is it now

#
[2023-08-23 15:37:25 DEBUG] discord.client: Dispatching event socket_event_type
[2023-08-23 15:37:25 DEBUG] discord.client: Dispatching event message

this is all im getting

#

I'll re-add the @bot.listen two secs

#

I'm not even getting the message

#
[2023-08-23 15:39:05 DEBUG] discord.client: Dispatching event message
[2023-08-23 15:39:05 INFO] root: Root got message: <Message id=... >

This is what I get if I use @bot.listen

#
@bot.listen("on_message")
async def on_message_2(msg: discord.Message):
    logging.info("Root got message: %r", msg)

So this gets it

#

but not @commands.Cog.listener

little cobalt
#

Do you have more than one on_messageevent?

shadow bear
#

nope

#

that's it

#

Hold on

#

the cog isn't in bot.cogs?

#

OH

#

HOLD ON

#

IM NOT DOING bot.add_cog IN SETUP

#

I'm returning it instead

#

god my knowledge of this library is dusty

#

omg it works now

#

Honest to god im a moron sometimes

#

thanks all KEKW

shell radish
#

well try using

    @commands.Cog.listener()
    async def on_message(self, message: discord.Message):

edit: ignore

#

oops messages didn't load

#

not sure what you're using, but setup_hook doesn't exist

little cobalt
#

isnt it one of the dpy or other ones?

#

Its from dpy

shell radish
#

what does your code look like?

#

Do you know OOP?

#

yeah you should learn that before pycord

#

object-oriented programming

opal hamlet
#

thats something ive been wondering about with selectmenus, probably gotta call self.remove_item(button_func_name) or smth in the View Class

ancient cosmos
#

Listener methods defined in cogs get name-mangled or otherwise abstracted, right? That way, they run in parallel with other listeners from another cog, or at the bot level, with the same method name (i.e. listening for the same event), instead of overriding one another?

lofty parcel
#

self.remove_item(button)?..

lofty parcel
#

I can't read your mind or your pc. Just saying "doesn't work" doesn't help anyone

#

Nor yourself

#

You send the traceback and relevant code

#

You have to edit the message with the new view

#

Otherwise you're not reflecting changes

#

Try it and see

#

New code?

#

self.stop() must be in the bottom

#

Is that your whole code?...

#

Sounds like you're trying to respond twice

#

How do you expect me to help without relevant code

#

Please show the full traceback

#

You're doing send_message and edit_message

#

Either send a follow up

#

Or interaction.edit_original_message

#

Error is self explanatory

#

That means most of the time you took to long to respond

little cobalt
#

you could defer it and see if its happening again

fleet cedar
#

Are you trying to remove all buttons?

#

Just pass None to the view parameter

opal hamlet
#

lets say i have a list with names(of .mp3 files that can be played) how would i create a selectoption for each entry in that list and append it to a view?

#

worst case i'll have to hardcode it

fleet cedar
#

you could iterate over the files and add those to the options

opal hamlet
#

i tried somethign similar a bit ago but i failed miserably at appending shit

#

or rather what exactly would i append? would i just do

    def __init__(self,bot):
      self.bot = bot

    def other_def(self):
      self.add_item(discord.SelectOption(placeholder='name')```
daring grove
#

How would I do ctx.invoke in a callback for a button?

fleet cedar
opal hamlet
#

So just basically have placeholder option(s) in the select that'll be overriden? Thanks!

fleet cedar
#

yep

opal hamlet
upper hearth
#

@discord.ext.commands.cooldown(1, 15, discord.ext.commands.BucketType.user)
i put this on a slash command but it does not do anything

#

you can spam it and it works

fleet cedar
upper hearth
#
    @discord.slash_command(name="vote", description="Vote for rewards!")
    async def vote(self, ctx):```
#

oh does it need to go after

fleet cedar
upper hearth
#

yea works now thanks

daring grove
#

i got pinged?

daring grove
lapis dock
#

It would be easier to have a function that has all the code for the command and then call the function in both the command callback and button callback

opal hamlet
# fleet cedar you would rather do smth like ```py class MySelect(discord.ui.View): def __i...
  File "C:\Users\Daniel\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\bot.py", line 1114, in invoke_application_command   
    await ctx.command.invoke(ctx)
  File "C:\Users\Daniel\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\commands\core.py", line 375, in invoke
    await injected(ctx)
  File "C:\Users\Daniel\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\commands\core.py", line 132, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'method' object has no attribute 'options'```
```class MySelect(discord.ui.View):
    def __init__(self):
        self.options = []
        for i, sound in enumerate(audio.audiooptions):
            self.options.append(discord.SelectOption(label=sound, value=audio.audiooptions[i]))
        self.audioselect.options = self.options

    @discord.ui.select(placeholder='Select an option', options=[discord.SelectOption(label='Select an option', value='Placeholder')])
    async def audioselect(self, select, interaction):
        select.disabled=True
        selval = select.values[0]
        await interaction.response.send_message(f'Selected: {selval}')```okay so i cant get it to work :/ no matter what i've tried
lofty parcel
opal hamlet
#

so instead of discord.ui.View just use discord.ui.Select or wdym?

lofty parcel
#

Yes.

#

So you can dynamically set options

opal hamlet
#

that honestly sounds like a tomorrow-me problem 🤷 thanks ill try that tomorrow

daring grove
shell radish
daring grove
shell radish
#

I don't know your exact implementation or implementation you have in mind

daring grove
shell radish
#

I don't know how you plan to implement what wolfy said

daring grove
shell radish
#

so is it like

async def command(ctx):
  await func(ctx)

async def callback(...):
  await func(interaction)

or

async def command(ctx):
  foo

async def callback(...):
  foo
fleet cedar
deft kestrel
#

Hi, I'm having a really dumb issue where the command shows but not the options. I know that the command is updating every time I restart the bot (the description changes when I change it), but no matter what I write, the zone option never shows up.

async def timezone_autocomplete(ctx: discord.AutocompleteContext):
    user_input = ctx.options.get("zone", "").lower()

    matching_timezones = [tz for tz in pytz.all_timezones if user_input in tz.lower()]
    return matching_timezones[:25]

timezone_option = discord.Option(description="Pick an optional me.", autocomplete=timezone_autocomplete)

@time_group.command(name="set", description="Set your timezone for us to show your current time.")
    async def time_set_slash(self, zone: timezone_option):
        pass

I've also tried making it a string option only (no type) but it still doesn't show up. I've tried changing the command name and making it a single command instead of a subcommand but it doesn't work. I'm on 2.3.2.

deft kestrel
#

the option doesn't matter, I removed the option and it still didn't show up

#

like the discord.Option type

safe nest
#

you'll want to use discord.Option instead of directly saying the autocomplete

rugged lodgeBOT
#

Here's the slash options example.

safe nest
#

there's an example on the github :)

deft kestrel
#

alright I'll try it catthumbsup

safe nest
#

if you still can't get it working after looking through those feel free to come back o/

deft kestrel
#

catthumbsup it's okay i just realised why it didn't show up, I didn't have ctx inside the arguments fh_pepesmh

safe nest
#

it still wouldn't show up, even if you add ctx afaik

junior spire
#

so I am trying to create my own context in this example, I can get the paginator to send, but it will not respond let you move pages, interaction failed.

any ideas or suggestions?

I am fairly new to paginators and I am creating my own context so I can send an automatic paginator from a function that is timed.

fleet cedar
#

Why not use ctx.respond btw?

#

That works for slash cmds

junior spire
# fleet cedar Disable author check

I wont have ctx.respond available. This is just an example. When it actually works, I would have a function (non slash command) that auto sends a paginator to a specific channel.

How do i disable author check?

#

Dude that worked. You are amazing, thank you !

fleet cedar
#

But yea the author check thing works

hasty cosmos
#

.rtfm get_channel

hasty cosmos
#

Is it possible that if an option uses autocomplete=, the input MUST be something from the autocomplete?

For example, I have an 'emoji' input that uses a library to import a bunch of emojis. However, in the command the user can still input any string and have it run which isn't correct for my use.

    @option(
        name="emoji",
        parameter_name="emoji",
        autocomplete=emoji_autocomplete,
        description="default=👍",
        required=False
    )```
brave ore
#

Why custom emojis can't use :<CUSTOM EMOJI NAME>: format to send from Bot?

hasty cosmos
hasty cosmos
#

.rtfm autocomplete

hasty cosmos
#

How do I validate the input value against the autocomplete result before the user invokes a command? I don't want them to be able to invoke it unless if the option is from the autocomplete results.

fleet cedar
hasty cosmos
solemn ice
#

how do i send a message in a specific channel with slash commands and not on_message?

heavy sky
#

.rtfm discord.Bot.get_channel

solemn ice
#

channel.send or channel.respond dosent work

heavy sky
#

Are you doing something like:

channel = bot.get_channel(...)
channel.send("Test")```
solemn ice
heavy sky
#

Can you show the code for how you're getting/fetching the channel as well?

solemn ice
#

i loop through the channels

#

and see if rules is in channel.name.lower()

heavy sky
#

And are you getting any errors when the bot tries to send the message to the channel?

solemn ice
#

yes

#

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

heavy sky
#

Ah, that means that the bot found a category called "rules" (and the bot can't send messages to a category)

solemn ice
#

ohh i see the issue

#

i needed to loop through guild.text_channels

heavy sky
#

yep

solemn ice
#

thanks for the help 😄

heavy sky
#

No problems 😄

fleet cedar
solemn ice
sly pebble
#

hey all, is there way to make it so discord.Bot responds to all mentions (e.g. @sly pebble and replies)?

just found self.bot.user.mentioned_in(message), but curious of any other possibly more efficient ways

old violet
#

this is my one of the cog file
but slash commands not showing in bot
I checked everything

heavy sky
sly karmaBOT
# old violet this is my one of the cog file but slash commands not showing in bot I checked ...

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.
old violet
heavy sky
# old violet yes

And you don't have discord.py or another library installed?
The bot is invited with the applications.commands scope, the cog is loading before bot.run() and you're not using legacy chat input?

old violet
#

Iam loading cogs in on_read

#

I changed it now

#

yes that is the problem

#

now working

heavy sky
#

Nice 😄

daring grove
#

let's say my command beans sends a message with 2 buttons, when someone presses a button i want it to run beans again in the callback

shell radish
#

ctx.interaction returns an Interaction object

ancient cosmos
#

If I set up a slash command option with input_type = discord.SlashCommandOptionType.attachment, what will the callback function actually get for that argument? A discord.Attachment?

ancient cosmos
little cobalt
ancient cosmos
little cobalt
#

that is weird

#

If you want you can open a new thread

ancient cosmos
shadow bear
#

Is there an ApplicationCommand equivelant of discord.ext.commands.Command.can_run?

#

there is not

little cobalt
shadow bear
#

Did a cursory look through docs

#

but

#

nothing really

elfin quarry
#

bans = await guild.bans(limit=1) is returning BanIterator can't be used in 'await' expression, am i missing something?

elfin quarry
#

oh

#

thank you!

gusty rover
#

I'm not getting any intellisense in vscode for anything related to ctx. anyone got any ideas?

lofty parcel
#

What

shadow bear
#

Did you type it?

gusty rover
#

yeah I'll write for example @bot.command() async def record(ctx): voice =ctx.author.voice and when I type "ctx.a" nothing pops up

lofty parcel
#

ctx: discord.ApplicationContext

#

You typehint to let the ide know what it is

gusty rover
#

cheers

harsh gust
#

so if i create a group using bot.create_group do i create it in main file or the cog file that i need it in if i use cogs and use separate files for them

heavy sky
fleet cedar
rugged lodgeBOT
#

Here's the slash cog groups example.

harsh gust
#

that sucks

harsh gust
little cobalt
#

Do you want to sync the commands after a restart of the bot?

little cobalt
#

Errors?

#

K

hasty cosmos
#

I see I think I figured it out, nevermind. It has to do with something irrelevant to the channel creation

lapis dock
#

Pycord automatically sync commands when the code is restarted. You don't need to override on_connect your self.

little cobalt
#

.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.
lapis dock
#

Do you load the cog properly with no errors?

deft kestrel
#

I'm trying to get users from a database. How can I skip the user's selection if he is logged out of the server?

ancient cosmos
ancient cosmos
#

The code you posted says:

try:
  member = await ctx.guild.fetch_member(int(data[0]))
except discord.errors.NotFound:

And then it stops there. That's not valid Python code just like that, because there needs to be an indented block after the except statement, even if it's just a pass statement that doesn't do anything (it's a statement that exists to tell Python that "there's intentionally nothing here").

So I'm asking - what do you have after that except statement? Or is that not code that actually runs, and you're trying to write that section now?

scenic crescent
#

Is it possible to get the component that is used in the interaction_check function of a view? If i´m correct I can´t because I only get the Interaction

opal hamlet
#
    def __init__(self, bot):
        self.bot = bot
        asyncio.run(self.voice_selection_msg())

    async def voice_selection_msg(self):
        chan = self.bot.get_channel(1144369985305726977)
        print(chan)
        try:
            ms = await chan.fetch_message(settings.voice_message_id)
            await ms.delete()
        except discord.NotFound:
            pass
        except Exception as e:
            print(e)
        msg = await chan.send(view=MySelect())
        settings.update_settings(value=msg.id, setting='Voice_message_id')
        while True:
            try:
                await msg.edit(view=MySelect())  
            except discord.NotFound:
                msg = await chan.send(view=MySelect())
                settings.update_settings(value=msg.id, setting='voice_message_id')
            except Exception as e:
                print(e)     
            await asyncio.sleep(60)``` chan remains None and i have 0 clue why
shell radish
#

If get returns None, that means it isn't cached

opal hamlet
#

fetch_channel then?

shell radish
#

try

chan = self.bot.get_channel(1144369985305726977) or await self.bot.fetch_channel(1144369985305726977)
#

Basically, this checks if it's None. If so, then fetch it

#

If not, don't fetch it

#

I would probably wrap a try-except around it to handle Discord server errors

foggy gull
#
async def verified():
  discordid = request.args.get('discordid')
  robloxuser = request.args.get('robloxusername')
  robloxid = request.args.get('robloxid')
  apiauth = request.args.get('apiauth')
  
  user = await bot.fetch_user('discordid')
  await user.send("Hello there!")```

Im making a discord bot for a commission and im using this code for a flask api to send a message to a discord id and do some other stuff that i will add later but when i run the url to the api command i get a 500 error and in the console in the console it says `Timeout context manager should be used inside a task, can anyone help!
limber wagonBOT
#

Use aiohttp.
requests and urllib are blocking. Do not use these libraries within your asynchronous code as they're not asynchronous.
(https://docs.pycord.dev/en/stable/faq.html#what-does-blocking-mean)

Py-cord uses aiohttp, so it should already be installed. An example of code using aiohttp and Py-cord:

async with aiohttp.ClientSession() as cs:
    async with cs.get('https://httpbin.org/json%27') as r:
        res = await r.json()  # returns dict
        await ctx.send(res['slideshow']['author']) 

For more help, see aiohttp's documentation: https://docs.aiohttp.org/en/stable/

foggy gull
#

What should i use other than ‘requests’

little cobalt
#

aiohttp

foggy gull
#

Ok

foggy gull
#

I still get the same error

#

Its the awaits in the getting the user and then sending the user a message

little cobalt
#

The aiohttp was at least for using async

foggy gull
#

I was using both

#

Its async and await??

foggy gull
little cobalt
#

Not with request x3

foggy gull
foggy gull
little cobalt
#

which request do you use?

meager iron
#

Any simple way to search for messages containing certain phrases through all channels, all time?

foggy gull
grim estuary
#

Hello! How often can the guild banner be updated?

#

There was such an error and loop stopped updating

little cobalt
grim estuary
#

I want to know the exact limit

little cobalt
#

I know that the channel name change limit 10 minutes is

grim estuary
#

About banners I heard that 3 minutes

lapis dock
#

iirc discord does not document specific ratelimits due to them being changed often. Pycord is supposed to handel that for you

edgy nest
#

a ratelimit would have status 429

little cobalt
#

oh ok

grim estuary
dusk flume
#

How can i use the command context to output the required permissions needed to run a slash command. I used command.checks to output all the checks however it outputs something like this:

<function has_permissions.<locals>.predicate at 0x1062eb4c0> (this is for a kick command)

What can i do to get the required permissions in words. (kick_members)

torpid cosmos
#

Quick python question

#

i have some info that i want to display in one variable, in a dict or list
the info I need is a user ID, thread ID, and webhook ID
The problem is I want both a user and thread to be able to refer to each other, both being able to have the webhook also attached
Something like
Thread(ID, Webhook) -> User(ID)
I was thinking of something like a list of tuples maybe, but that wouldn't be very performant and itd also be ugly
any ideas?

ancient cosmos
#

Frankly, gin up a class for it

#

Especially if you care about cleanliness, and especially since you're probably going to want to set up @property stuff for it, from the use-cases you're saying

grim estuary
#

Hello. How to use await ctx.defer()? This option doesn't work:

await ctx.defer()
await ctx.respond(...)```
And this
```py
await ctx.defer()
await ctx.followup.send(...)
dusk flume
grim estuary
heavy sky
dusk flume
#

Yeah. I don’t exactly know what your trying to defer

grim estuary
heavy sky
dusk flume
#

Send the relevant part

heavy sky
#

No problems 😄

grim estuary
#

One more small question. How to get member status? Not online / Do not disturb status, text under a username in a profile

heavy sky
#

Are you loading the cog?

grim estuary
#

Have you used setup() in cog? load_extension() in main file?

#

In your main file you should have an entry like this:

bot = commands.Bot(...)
bot.load_extension("Cogs.Cogname")

In cog:

def setup(bot):
    bot.add_cog(Cogname(bot))```
heavy sky
#

.tag 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.
grim estuary
summer scroll
#

Hi, can someone explain me how to get all users that have a certain role, and all users that have the roles above pls

fleet cedar
#

overriding on_connect?

#

or specified a guild id?

dusk flume
grim estuary
#

Use a cycle if you need to list the members of multiple roles. Don't forget to exclude copies of members

opal hamlet
#

how can i "ignore" the interaction of a button? or rather prevent discord from complaining about app not responding

upper hearth
#

await interaction.response.defer() i think

fleet cedar
opal hamlet
#

yeah, thanks!

#

dont need my bot to tell me if sound x is playing when i can hear it lol

little cobalt
shadow bear
#

If I reply to the interaction from discord.ui.Button, how do I edit the message that the button is attached to?

#

e.g.

@discord.ui.button(...)
async def foo(...)
    await interaction.response.send_message("Hello")
    btn.disalbed = True
    await interaction.edit_original_response(content="Done")
    # ^ This edits the `interaction.response.send_message`, not the message the button is attached to
little cobalt
#

?

shadow bear
#

my scenario here is I'm replying to the user who pressed the button with an ephemeral message.
I then want to update the original message, however, after responding to the interaction, edit_original_response edits the ephemeral message, not the original message

fleet cedar
#

Not for slash cmds tho

little cobalt
#

oh, did they changed it? or was it always like that?

fleet cedar
#

it was always like that

sharp zealot
#

what was the time thing to do this

#

dose anyone know

rugged lodgeBOT
sharp zealot
opal hamlet
#

is it possible to attach an image to a slash command? it's supposed to be for bouny hunting in a game and to provide proof

opal hamlet
#

oh wow, that easy? i feel stupid for asking O.o i knew it worked with channels etc but

little cobalt
opal hamlet
#

fair

dusk flume
#

Pls help

lofty parcel
dusk flume
lofty parcel
#

.rtfm command.permissions

sly karmaBOT
#

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

dusk flume
#

It wasn’t in docs

lofty parcel
#

No it doesn't

dusk flume
lofty parcel
#

Doesn't look like you can

#

SlashCommand has default_member_permissions

dusk flume
# lofty parcel Doesn't look like you can

When I run command.checks for a kick command, it outputs this:

<function has_permissions.<locals>.predicate at 0x1062eb4c0> (this is for a kick command)

What does this mean? In the docs the command.checks said it will output all the checks the command does. One such check is that the user has kick perms

#

So what does that mean

#

Idk lol

lofty parcel
#

Checks are functions

#

It's returning a list of predicates

dusk flume
lofty parcel
#

Which is essentially what checks are

dusk flume
#

So there is no way I can return the perms of a command

lofty parcel
#

Ig you'd just need to store them by yourself

dusk flume
#

Kinda sad lol. I thought I made an automated help command in like 10 lines of code 💀💀

#

Maybe dictionary for storing

rare condor
#

I'm trying to figure out how to use the before parameter from purge, is there any example that works besides my attempt?

lofty parcel
#

.rtfm purge

rare condor
#

I tried to make my own

#

but i think Im making it wrong

lofty parcel
#

It's either a snowflake or a datetime

rare condor
#

tysm

hallow blade
#

Tried to follow the grouped commands in cogs to have grouped bridge commands in a cog, but not getting exaxtly what I expected. Is there specific examples of this?

slender cloak
#

im trying to make a custom command check, is it possible for me to refernce self.client or just client in it?

#
def is_mod():
  async def check_roles(self, ctx):
     db = self.client.check_db()
     
     if role in ctx.author.roles or ctx.author.guild_permissions.administrator or ctx.author.id == ctx.guild.owner:
               return True
     else:
               return False
  return commands.check(check_roles)
#

db = self.client.check_db()

#

basically im wondering if i can do the above and if so how

torpid cosmos
#

can i ask where this function is located

#

@slender cloak do you have any code implemented at the moment?

slender cloak
#
class Mod(commands.Cog):

    def __init__(self, client):
        self.client = client

    def is_mod():
      async def check_roles(self, ctx):
         db = self.client.check_db()
     
         if role in ctx.author.roles or ctx.author.guild_permissions.administrator or ctx.author.id == ctx.guild.owner:
               return True
          else:
               return False
       return commands.check(check_roles)
torpid cosmos
#

so first of all your is_mod function would have the self argument, check_roles wouldn't have that

#

and thats about it

slender cloak
#

ah ok

torpid cosmos
#

remember that any function in a class would have self as its first argument, unless it's a static method

slender cloak
#

ok gotcha

torpid cosmos
#

staticmethods dont have any class-related arguments

shell radish
#

static = class methods?

#

or am I java-pilled

torpid cosmos
#

you're java-pilled

#

class methods are used to create an instance of that class

#

a static method can be used regardless of whether you are using it with an instance of that class or not

shell radish
#

example?

torpid cosmos
# shell radish example?
class Animal:
    def __init__(self, animal_type):
        self.animal_type = animal_type

    def print_type(self):
        print(f"The type of this animal is {self.animal_type}.")
    
    @classmethod
    def construct_animal(cls, animal_type):
        return cls(animal_type)

    @staticmethod
    def suggest_animal():
        print(f"Here is a random animal: {random.random_animal()}")

my_animal = Animal.construct_animal("Bear")
my_animal.print_type()
>> "The type of this animal is Bear."
my_animal.suggest_animal()
>> "Here is a random animal: Rabbit"

Animal.print_type()
>> Error
Animal.suggest_animal()
>> "Here is a random animal: Cat"
kind olive
#

the docs are confusing me. How do I make a slash command that has a bool choice?

slender cloak
# torpid cosmos and thats about it
class Mod(commands.Cog):

    def __init__(self, client):
        self.client = client

    def is_mod(self):
      async def check_roles(ctx):
         db = self.client.check_db()
     
         if role in ctx.author.roles or ctx.author.guild_permissions.administrator or ctx.author.id == ctx.guild.owner:
               return True
          else:
               return False
       return commands.check(check_roles)

so like this?

torpid cosmos
#

yeah looks like it

slender cloak
#

and then further down i could say do

@slash_command()
@is_mod()
kind olive
#

also for a slash command to work right away, do I need to set a guild or specifically not set one

shell radish
#

btoh work

torpid cosmos
#

for it to register immediately you'd need to set a debug guild

slender cloak
torpid cosmos
shell radish
torpid cosmos
#

oh what

kind olive
#

lmao

torpid cosmos
#

really?

#

ive been living under a rock i guess

kind olive
#

so can anyone answer my first question?

kind olive
shell radish
#

#general message this?

kind olive
#

How do I make my slash command have a second input with a boolean choice

austere loomBOT
#
Found message through link:

is discord.py being discontinued?

Guild

Pycord

Channel

#general

Message

#general message

torpid cosmos
kind olive
kind olive
torpid cosmos
#

yeah it'll just show them both

torpid cosmos
slender cloak
#

yeah its when i am trying to reload the cog via Jishku

kind olive
torpid cosmos
# kind olive ?

more like

custom: discord.Option(discord.SlashCommandOptionType.boolean)``` i think
#

i think you can also just use bool

#

instead of the whole enum

kind olive
#

sweet thanks

torpid cosmos
#

wait

#

what

#

i dont remember typing half of that

#

im going nuts

#

anyway

slender cloak
#

lmao

torpid cosmos
slender cloak
#

sure

#

but somethings wrong with my command check tho right

torpid cosmos
#

maybe

#

i dont know what you mean

slender cloak
#

well im getting that error

torpid cosmos
#

im trying to figure it out but the puzzle pieces aren't fitting together for some reason in my head

#

the hamster is very much alive hes just not spinning the wheel

torpid cosmos
# slender cloak ```py class Mod(commands.Cog): def __init__(self, client): self.cli...
class Mod(commands.Cog):

    def __init__(self, client):
        self.client = client

    def is_mod(self):
      async def check_roles(ctx):
         db = self.client.check_db()
     
         if role in ctx.author.roles or ctx.author.guild_permissions.administrator or ctx.author.id == ctx.guild.owner:
               return True
          else:
               return False
       return commands.check(check_roles)
    
    @slash_command()
    @is_mod()
    async def my_command(self, ...):
        ...
#

something like that is what you have rn?

slender cloak
#

yes

torpid cosmos
#

okay yeah that makes sense

#

so that decorator is basically just not getting a reference to the class

slender cloak
#

wdym?

torpid cosmos
#

uh like
you know how when you use a method of a function its usually

self.func()
#

well when using a decorator it isnt getting that class instance passed anywhere

#

it isnt getting its self

#

like a baby boy without a blankie

slender cloak
#

ohh ok

#

so is it possible to use self or even just client/bot?

torpid cosmos
#

im going to say yes

#

it has to be

#

it must

#

im just thinking of how

#

@shell radish help

#

i know ive faced this same problem before
and i thought i solved it somehow

#

goose theres a reason i dont have that shiny pink helper role

slender cloak
#

lmao but ur staff so that says something

torpid cosmos
#

exactly

#

oh wait

#

@slender cloak can you try removing the parenthesis

#

though i think that might not work

slender cloak
#

in what spot?

torpid cosmos
#

the decorator

#

@is_mod

slender cloak
#

ok

torpid cosmos
#

no that wont work as far as i know

slender cloak
#

now im getting

method(extension)
discord.errors.ExtensionFailed: Extension 'cogs.mod' raised an error: TypeError: Callback must be a coroutine.
torpid cosmos
#

yeah lol

#

nope

#

oh wait a minute

#

thats a check

#
@slash_command(checks=[is_mod])```
#

add that to your slash command decorator and remove the is_mod decorator

torpid cosmos
#

id say you cant edit ephemeral messages but i dont think thats true

#

can you show me a little more of your code

slender cloak
#

so the command worked but the check either returned True falsely or it didnt run the check im not sure

torpid cosmos
#

Throw some prints in that bad boy

#

Print inside of the function

#

Print inside of the check

#

Print inside of the conditionals

#

Print the conditions

slender cloak
#

alr lol

#

nah nothing printed so i dont think its running the check

torpid cosmos
#

not even the top level one in is_mod?

#

try making it not a list

#

though im pretty sure it expects a list

slender cloak
#
class Mod(commands.Cog):

    def __init__(self, client):
        self.client = client

    def is_mod(self):
      async def check_roles(ctx):
         print("test")
         db = self.client.check_db()
     
         if role in ctx.author.roles or ctx.author.guild_permissions.administrator or ctx.author.id == ctx.guild.owner:
               return True
          else:
               return False
       return commands.check(check_roles)

i did this and nothing printed

#

i feel like there has to be a way to use self or client in a command check

torpid cosmos
slender cloak
#

ok

#

still nothing

torpid cosmos
#

oh oms here to save the day

#

Lets tri

#

Make check_roles its own function and remove the overhead from is_mod

slender cloak
#

ok

torpid cosmos
#

so then itd be like

class Mod(commands.Cog):

    def __init__(self, client):
        self.client = client

  async def is_mod(self, ctx):
     print("test")
     db = self.client.check_db()
     
     if role in ctx.author.roles or ctx.author.guild_permissions.administrator or ctx.author.id == ctx.guild.owner:
           return True
      else:
           return False
#

possibly

#

maybe

#

uh

#

hm

#

i dont think thats enough context for us unfortunately

#

wheres callback at

shell radish
#

you need the original interaction object that sent the ephemeral message to edit the message

torpid cosmos
#

thats enough context for squid though

#

squids a g

shell radish
# torpid cosmos so then itd be like ```py class Mod(commands.Cog): def __init__(self, clien...

slight nitpick

class Mod(commands.Cog):

    def __init__(self, client):
        self.client = client

  async def is_mod(self, ctx):
     print("test")
     db = self.client.check_db()
     
-    if role in ctx.author.roles or ctx.author.guild_permissions.administrator or ctx.author.id == ctx.guild.owner:
-          return True
-     else:
-          return False
+     return role in ctx.author.roles or ctx.author.guild_permissions.administrator or ctx.author.id == ctx.guild.owner
``` but nothing to do with the actual cause of error
shell radish
torpid cosmos
#

behave yourself

torpid cosmos
shell radish
torpid cosmos
#

well no baloney but how

#

did you make it colored

shell radish
#

diff

#

does

#

diff

torpid cosmos
#

oh shit thats rad

shell radish
#

should be blue and red because color blind

#

so you can either pass the interaction/context object to the view class or do a view.stop() and await view.wait()

torpid cosmos
#

i used to do something like

class mything:
    message: discord.Message
    ...

view = mything()
message = interaction.respond(view=view, ...)
view.message = message
shell radish
torpid cosmos
#

You dont need it, you just need the message to be able to edit the message

shell radish
#

no, you need the interaction object to edit the ephemeral message

torpid cosmos
#

Though I believe I actually made a pr to add an edit_message function to the view

shell radish
#

or else view.message.edit would work

torpid cosmos
shell radish
#

The error isn't message is None, it's that the message "doesn't exist"

#

how did you send the view?

#

ApplicationContext wraps an Interaction object

#

so, you would need that interaction or ApplicationContext object to edit the message

torpid cosmos
slender cloak
#

im just updating the code now

shell radish
#

You can get it by passing it into the view or waiting for the button to be pressed in the original command

slender cloak
#
TypeError: Mod.is_mod() missing 2 required positional arguments: 'self' and 'ctx'
#

now im getting this

torpid cosmos
#

Okay well I'm just retarded

shell radish
#

Put it outside of the cog?

#

and remove the self?

torpid cosmos
#

he needs the reference to the cog

shell radish
#

why?

torpid cosmos
#

he needs to access the bot object