#Basic Pycord Help

1 messages · Page 59 of 1

fresh sierra
#

ok so there is not a global thing to get all the error that occurs in events, we need to do per event thing

#

(or do a custom thing)

lofty parcel
#

Check that

fresh sierra
#

else i was thinking to make a decorator that will apply to all listener to catch every error, so i can get the discord Execption and do in consequence

round heart
#

brb stealing all of Dark's code

fresh sierra
#

what do you need help sith ?

sage tendon
#

dumps his whole file and expects help

#

440 lines of code

#

bruh

fresh sierra
#

open a post

#

it will be easier because you have a LOOTTT of code here

sage tendon
#

yea that is way too much shit

#

why?
just set the permissions as you create the channel
also stops the channel from showing for members for a fraction of a second every time you create one

fresh sierra
#

also help with rate limit

lethal loom
sage tendon
#

the docs tell you

fresh sierra
#

overwrite

deft bronze
#

Now how i invite a bot to my sv? 💀

#

Like what's this

#

Like what's this

sage tendon
#

you need the bot scope

deft bronze
#

(sorry, double pic)

sage tendon
#

and yes, use the provided link

#

after adding the bot scope

deft bronze
#

Thanks

#

Basic things are getting weird in ds, idk

sage tendon
#

No, its just because there's a lot more stuff than just straight up bots you can make on discord

deft bronze
#

Too much for my brain

sage tendon
#

i mean you want a bot and application commands

#

pretty straightforward

deft bronze
#

Yeah, i know, im just kidding

#

But this is new right? i made a bot a few weeks back and this wasn't an option i think

#

Whenever you add a new command or smt like that, you need to restart discord? or is there any other way to make it appear

loud kayak
#

How can i forcefully set a cooldown for a guild (cooldowns using commands.cooldown) for a specific command?

sage tendon
#

using a dynamic cooldown already?

loud kayak
#

on the command i am using @commands.cooldown(1, 300, commands.BucketType.guild) but i want to be able to set the command's cooldown from another command overwriting it.

sage tendon
#

for a guild, without any interaction from that guild?

loud kayak
#

yes

sage tendon
#

hm

loud kayak
#

thats a decorator tho, there isnt a function that would allow me to do what im wanting to do?

sage tendon
#

yea no, no idea if this is possible with the built in cooldown system

shell radish
#

you can still use dynamic cooldown?

rigid verge
#

How can I fetch the Individual User Count? Sorry for HDR

shell radish
#

it's only on master right now

shell radish
slender lantern
#

IIRC bot emojis are supported now. When using get_emoji(), are they given priority if there's a naming collision with a server?

slender lantern
#

Ah, you're right. I was thinking of a different method. Thanks

#

Small confusion regarding the documentation:

discord.Bot.emojis: "The emojis that the connected client has."

Is that the emojis uploaded to the application, or all emojis it can see on its servers?

errant trout
slender lantern
#

Ah, thanks. I misread something late last night. So if I read this correctly, app emojis don’t need the use external emojis permission?

lofty parcel
#

They don't

oblique fern
#

If I want to restrict a command to be only able to be used when someone has the Admin permissions, this should work right?

issue = SlashCommandGroup("issue", "desc", checks=[commands.guild_only().predicate])
errant trout
#

(pass default_member_permissions=discord.Permissions(...) inside the constructor)

frail basin
#

If I don't have any interactions, nor am I listening to any events, is it safe to deploy a 2nd instance with the same token?

#

The bot will be controlled by a Flask API with the instances having different endpoints.

lofty parcel
#

Why do you need two instances

#

Make your flask server a cog

fresh sierra
sage tendon
#

Why does getting 50 messages worth of channel history take 8 seconds?

#

Is the discord API slow currently? it didnt take this long before

#

Okay.. it seems to only be like that on one server

#

Yea it seems to be happening in one server quite obviously, and not at all in another server
The chat histories aren't dissimilar, both a lot of text and some images

#

So i have no idea why its so slow?

frail basin
frail basin
sage tendon
#

i mean you can have one instance that ONLY handles incoming API requests, and the other instance that does all the actual bot stuff

#

should work

deft bronze
#

Where is the Forums / Threads documentation?

#

To fetch a thread, create one, etc

deft bronze
#

@echo wraith Thanks

echo wraith
#

:)

deft bronze
#

Why fetch_channel doesn't show ForumChannel?

errant trout
deft bronze
deft bronze
#

Why fetch guild returns no categories / channels?

echo wraith
sage tendon
#

and you have proper intents

deft bronze
#

I have all intents and bot has admin perms

sage tendon
#

did you also select the bot scope when inviting the bot?

errant trout
#

read the docs, fetch_guild doesn't include channels

#

(every time)

#

if you don't have channels cached, use guild.fetch_channels @deft bronze

sage tendon
#

better question (for me) would be why they dont have any of the guilds channels cached at all

errant trout
#

i mean they probably do

#

but they'll never show through fetch_guild lol

sage tendon
#

ah

deft bronze
errant trout
sage tendon
#

yea thatll totally not break the instant your bot is in two guilds

#

if anything you should do bot.get_guild(id)

deft bronze
#

Is for my personal sv

sage tendon
#

you think that now

deft bronze
#

I know i should do it right

#

But thats how it ends

#

I did it just to work in my sv

#

Its filled with fetch channel, categories, etc

sage tendon
#

you should also avoid fetch whenever possible

obsidian stratus
#

Hey how to make the user command which you can use without a bot being in the server

#

As in what is it called?

obsidian stratus
#

Thank you!

dense summit
#

within the on_timeout how can i send a message to the channel the interaction is in?

lofty parcel
dense summit
#

tho i dont see anything on the docs to get the client?

#

nvm i can have the guild

sage tendon
#

you dont need anything but what dark sent to send a message

dense summit
#

i needed it for other things :p

echo wraith
#

Where can I subclass ApplicationContext where self.command is set ? Because self.command is not set in the __init__...

sage tendon
#

what

#

just override whatever function does set it

echo wraith
#

I believe it is set by prepare

#

but I'm lost

#

Actually, no method of ApplicationContext is called after that ApplicationContext.command is set by ApplicationCommand.prepare, which kinda sucks because it means I need to somehow subclass ApplicationCommand and that's way harder

#

WAIT I KNOW

#

I cann override ApplicationContext.__setattr__ and do something there if it's setting command

fresh sierra
echo wraith
# fresh sierra it is

Yeah figured it, thx. In the end I went with that __setattr__ thing and it works great. But oh boi the code is hard to read...

deft bronze
#

How can i send multiple buttons inside a message?

#

with a list?

sage tendon
#

a view

stray pasture
#

I am doing a check for permission before running come commands. This is the check:

    def check_for_manage_role(self, ctx: ApplicationContext) -> bool:
        my_bot: Member = ctx.guild.get_member(self.bot.user.id)
        missing_permissions = []
        if not my_bot.guild_permissions.manage_roles:
            missing_permissions.append("manage_roles")
        if not my_bot.guild_permissions.view_audit_log:
            missing_permissions.append("view_audit_log")
        if len(missing_permissions) > 0:
            raise MissingPermissionsException(missing_permissions)

I never had a problem, but one user today complain that when running the command he is getting a error. When checking logs I see that ctx.guild is None. How can this happen ? I try to reproduce but cant get a ctx.guild that is None. Anybody got a clue ?

#

I am think of doing get_or_fetch guild with ctx.guild_id instead

stray pasture
#

This is in a slash command

errant trout
#

(which you should probably do anyway)

stray pasture
#

I can use bot_has_guild_permissions

errant trout
#

yep quite a few on that page

stray pasture
#

But still does not explain why ctx.guild was null

errant trout
#

did you set the command to guild only

stray pasture
#

How is that possible in a s’ash command running in a guild

stray pasture
errant trout
#

then they can use it in dms

stray pasture
errant trout
#

how many guilds is the bot in

stray pasture
#
        On guild Rise of Kingdoms by user ruzxv (Ruz) 
        On command server_time_role with values [{'value': '1254719275084546091', 'type': 8, 'name': 'role'}, {'value': 30, 'type': 4, 'name': 'days'}, {'value': True, 'type': 5, 'name': 'apply_to_existing_member'}]
        Error -> Application Command raised an exception: AttributeError: 'NoneType' object has no attribute 'guild_permissions'
        Original ->   File "/usr/local/lib/python3.11/site-packages/discord/commands/core.py", line 138, in wrapped
    ret = await coro(arg)
          ^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.11/site-packages/discord/commands/core.py", line 1486, in _invoke
    await command.invoke(ctx)
  File "/usr/local/lib/python3.11/site-packages/discord/commands/core.py", line 432, in invoke
    await self.prepare(ctx)
  File "/usr/local/lib/python3.11/site-packages/discord/commands/core.py", line 364, in prepare
    await self.call_before_hooks(ctx)
  File "/usr/local/lib/python3.11/site-packages/discord/commands/core.py", line 584, in call_before_hooks
    await hook(ctx)
  File "/usr/src/app/cogs/WriteCog.py", line 14, in cog_before_invoke
    self.check_for_manage_role(ctx)
  File "/usr/src/app/cogs/WriteCog.py", line 36, in check_for_manage_role
    if not my_bot.guild_permissions.manage_roles:
errant trout
#

the guild isn't none

#

did you make this a user command?

#

(i.e. user installable)

stray pasture
errant trout
#

that's not the guild, that's your bot member

#

guild_permissions is a Member attribute

stray pasture
#

oh yeah right, sorry about that

errant trout
#

did you set your bot to user install or is it just a regular one

stray pasture
#

I guess somehow the bot is not cache in that guild

errant trout
#

mmm odd but yeah

stray pasture
#

I can just do get_or_fetch member

#

but yes it is odd that not cache

#

never happenned because in more than a year 😄

errant trout
#

it's not meant to be possible but eh the more you know

stray pasture
errant trout
#

allgood

loud kayak
#

its only doing channel.send once and i know for a fact

slender lantern
#

Isn't ctx.respond supposed to fill in the message attribute in View?

silk spire
fresh sierra
echo wraith
#

When using bridge will commands still be in bot.pending_application_commands ? Yes

echo wraith
#

How would you "disable" slash / prefix commands from a bridge bot in a reasonable amount of lines ?

sage tendon
#

disable how?

deft kestrel
#

Do you know if the Discord API is having issues right now? It seems like the slash commands aren't working as they should

sage tendon
#

looks fine

#

what doesnt work properly for you

echo wraith
sage tendon
#

you want to disable all commands?

echo wraith
sage tendon
#

actually it's a listener so it wouldn't stop the execution if you return

#

hm..

echo wraith
deft kestrel
sage tendon
#

yea just posted lol

fresh sierra
lean garnet
#

Hi, is there any way to have 2 fields per line ? TIf I set inline=True for the third one it will be on the same line than the two previous ones, if I set inline=False it will put the fourth in a new line.

#

I tried to put an empty field between them but the last one is way too espaced

sage tendon
#

cant you do inline=False for the 3rd, and inline=True for the fourth field?

#

if not then i dont think you can

lean garnet
#

UPDATE : the empty field that I added was inline with the previous one, I put it on inline=False and now it works.

round heart
#

Wish it was easier to make blank lines. Didn't you have to do a special utf character instead of an actual blank string?

round heart
errant trout
#

otherwise i'd have liked to make name/value optional

#

(e.g, you can send a completely blank embed, and thus a message with zero content, using discord.Embed().add_field(name="", value=""))

round heart
errant trout
#

that's the more "recommended" way because empty string is supposed to be patched, but it's worked fine for ages so might as well until they break it lol

deft bronze
#

How can i get the userID of people who reacted to a message?

#

Idk what to do with message.reaction bc i dont know how to get a user from there

deft bronze
#

nvm

dense summit
#

to stop listening on a view so avoid the on_timeout event to be called i need to do #.stop()?

sage tendon
#

p sure yes

#

but you should usually just disable all items to convey that to the user

dense summit
#

so i dont think i really need to disable all items

acoustic path
#

hi is there an integrated thing to make a time input in a Modal dialogs ?

sage tendon
#

no

#

modals only support string input

acoustic path
round heart
#

You can get a small text box or a big text box. That's the extent of Modals.

vivid crag
#

I am trying to make member optional, however when I attempt to do so it doesn't support autofill like it does when I typehint it normally (member: discord.Member). Am I doing something dumb?

async def profile(self, ctx, member: Option(description="The member to display the profile of.", input_type=discord.Member, required=False, default=None))
#

Tried it both inline and with the decorator, same result

sage tendon
#

it might be because of the default, try to remove that

vivid crag
sage tendon
#

did you restart discord

vivid crag
#

yeah

sage tendon
#

can you try use the decorator method instead to make the option? it shouldn't change it but you are passing everything correctly

vivid crag
#

already tried that, didn't change anything

sage tendon
#

and it works if you remove the required=False but leave the rest?

vivid crag
sage tendon
#

can you try just send the command with any input

#

if it somehow hasn't, it should update then

vivid crag
sage tendon
#

yea ok

#

try rename the command
worked for another person a few hours ago for some unknown reason

sage tendon
#

can you try pass the input type positionally then

#

it somehow seems to just ignore that

vivid crag
#

thanks

sage tendon
#

np

twilit socket
#

I'm trying to use discord.ext.commands.Bot beucase I need my current bot to work only on the old prefix commands.

The issue I'm encountering is: it looks like all events related to commands are not being triggered. I tried using on_application_command_error, on_command_error and on_error and nothing is triggering when I use a command that does not exist. I just get an exception on stdout instead of it going through the code inside the event first.

Is there a fix?

#

Nevermind, on_command_error actually is the only one that works but I got confused because of mylogger.warn CirnoSociety anyways thanks.

fresh sierra
#

on_command_error = prefix
on_application_command_error = app commands
on_error = event

fresh sierra
#

how should i do for the view of my paginator appear only if the number of pages is greater than 0 ?. Should i edit the send/edit function or another one ?

round heart
fresh sierra
#

For exemplenhere

#

Since there is only 1 page remove the view

#

(I will edit the class of the paginator for that h

round heart
#

Ah. I mean… couldn’t you just not send the Paginator in that case? You would know whether you have multiple pages or not

I also think there’s a kwarg for the view, you should be able to pass None nm that’s for custom view and it’s already default None (but you could make an empty view and pass it 🤷‍♂️)

round heart
lofty parcel
#

Yeah just check before

fresh sierra
#

But what part to edit in the subclass, the edit and sent it or innit for exemple

sage tendon
#

Okay I just noticed something odd and I'm not sure if it's a feature or not
When I reply to an interaction with an empty message, the API returns an error, logically
However, my error handler then catches that error, and upon trying to call ctx.respond to the ctx in question, it gives me an unknown interaction error
How does this happen? Does the "cant send empty message error" somehow consume and completely get rid of that interaction?

sage tendon
#

How long can a discord option input be

fresh sierra
sage tendon
#

i tested it afterwards and the limit is the fact that discord freezes and starts eating hundreds of megabytes of RAM even on relatively small inputs

echo wraith
#

lol

echo wraith
#

How many slash command options ?

sage tendon
#

not sure there's a (restrictive) limit

#

if i had to guess, 25

#

same as choices

echo wraith
#

Let's hope it's more than 16

sage tendon
#

tf you need that many options for

echo wraith
#

a bad design decision

little cobalt
echo wraith
#

thx

vivid crag
#

Is there a more efficient way to add users to a thread, perhaps by role, than add_user? Unless I'm blind I'm not seeing anything in the documentation aside from that and when I tried it my bot's hitting ratelimits adding maybe ~10 people.

#

If not I could add a delay, but that would kind of suck if there's a better method

sage tendon
#

you can just mention them in a message

#

(roles too)

vivid crag
# sage tendon (roles too)

I remember that being a thing at one point, but I think they changed it. It's not mentioning the role in the thread via .mention (it does in a regular channel, tested it) and it's not adding my alt which has the role

sage tendon
#

allowed mentions

vivid crag
#

Also, there's two group of people that I need added, one that should be pinged and another that should have access but shouldn't be pinged, so I'd rather avoid using that method even if it does still work

sage tendon
#

hm

#

all ticket bots i know use pings, not sure if there's a way to avoid the seemingly strict limit

#

you can do silent pings

vivid crag
# sage tendon allowed mentions

my bot's allowed mentions are on, it's only in threads that it doesn't actually ping the role members. Also I forgot to mention that this is a private thread, so sorry for accidentally leaving that out

#

That's probably why that doesn't work

sage tendon
#

weird since discord itself does convey that as "main" way

#

i just tried and it even works if you edit in the mention afterwards so it's not tied to ping itself

vivid crag
#

perhaps mentioning them individually works but not mentioning by role?

sage tendon
#

both worked when i just tested it

vivid crag
#

hmm that's odd

sage tendon
#

is your bot creating the thread?

vivid crag
#

yes

#

I'm trying to:
create thread -> send an embed -> add members

sage tendon
#

hm but it does add the users if you use add_user?

vivid crag
#

it does, but I get angry messages in my console saying I'm being ratelimited

sage tendon
#

can you show that message

vivid crag
#

one sec

sage tendon
#

also doesnt every add_user cause a message about user x being added to the thread?

vivid crag
# sage tendon can you show that message
[2024-10-18 19:17:46,535] [WARNING - discord.http] We are being rate limited. Retrying in 3.89 seconds. Handled under the bucket "1296975537540960316:None:/channels/{channel_id}/thread-members/{user_id}"
vivid crag
sage tendon
#

no but it gets messy if you add more than like 2 people

vivid crag
#

true

sage tendon
#

but it really should work if you @ mention them in any way, its weird that it doesnt

#

and i dont see another way to do it

vivid crag
#

Just realized I'm dumb, I was testing it in a channel that the role doesn't have access to. It works now, thanks for your help lol

sage tendon
#

lol

#

np

echo wraith
#

Is there a way for autocomplete options to have a name, value thing ?

round heart
sage tendon
#

correct

echo wraith
sage tendon
#

thats also the only way to do a "limited" role select

#

the value will be the actual role object, and the string shown to the user is just @Rolename

#

(if i highlight the rest it looks ugly)

cerulean laurel
#

is it possible to transver values from one class to another

sage tendon
#

As in?

cerulean laurel
#

in one class i have a command with input and i want the input in another class

sage tendon
#

then just use a setter for that attribute

cerulean laurel
#

?

sage tendon
#

otherclass.set_input(user_input)

cerulean laurel
#

and how do i use it

sage tendon
#

use what?

cerulean laurel
#

where do i put it and how

sage tendon
#

in your command, and exactly how i wrote it
just make a setter in the class you wanna give the input to, and then call that function on the class object
no idea how your structure is and what that class is but either you make a new class object just for that, then you could give the input to the constructor directly, or you already have an existing instance of that class, then it's a bit more complicated and i'd need to know how your program is structured and all

cerulean laurel
#

from the red to the red

sage tendon
#

ah

cerulean laurel
sage tendon
#

well just pass it to the view when you create it and then save it in an attribute, and then access it with self.attribute when you need it

cerulean laurel
#

?
im not so good at code

sage tendon
#

do you know how to use views?

cerulean laurel
#

kind of

sage tendon
sage tendon
cerulean laurel
#

huh im just putting one class under another

sage tendon
# cerulean laurel kind of

yea so you're creating an instance of the view somewhere
just pass the user input as an extra argument to the constructor, and ofc change the constructor in the view class to take that argument and save it to a self. attribute

sage tendon
#

it gets very messy

#

your cog doesnt even have a setup function from what i can see so it doesnt even work lol

cerulean laurel
#

?

sage tendon
#

your cog. has no setup function.

#

so it cannot work

cerulean laurel
#

i have that at the end

sage tendon
#

well if it works i dont even wanna know how lol

sage tendon
#

how what?

cerulean laurel
#

how do i pass the input to the constructor

sage tendon
#

... = Aufgabe_Button(your_input)
and then you just change the constructor in the view to actually take and save that argument

sage tendon
#

put what

cerulean laurel
#

where do i put ... = aufgabe button

sage tendon
#

wherever you need to create the view
if you dont know how to use views, please check the guide

cerulean laurel
#

so here?

sage tendon
#

remove the aufgabe_button =

#

but yea

cerulean laurel
sage tendon
#

in the constructor of the view

#

just add another argument after self and then save that with self.whatever = argumentname

#

i gotta go now tho, but i'm sure there's someone else who can help
And I recommend you look into basic OOP in python

#

and split your files so that you generally dont have more than one class per file especially not in a cog file

cerulean laurel
#

so like this?

sage tendon
#

yea

cerulean laurel
#

"discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction"

#

didnt work

sage tendon
#

I mean that error isn't about creating the channel or anything you just changed

#

that's just some response somewhere not working, and the error tells you where

cerulean laurel
#

i now put the class in another cog but a get another error, it says there is no module named aufgabe_button but that is my class that im importing

#

nothing works

echo wraith
sage tendon
cerulean laurel
#

got it

#

i accsidentaly had an older version running on a server

#

ok i got the button and the channel but when i try to place it in a category i get the error:
AttributeError: 'str' object has no attribute 'id'

sage tendon
#

are you passing the category name?

cerulean laurel
#

await interaction.guild.create_text_channel(self.aufgabe_grob, category="aufgaben")

sage tendon
#

thats not how it works

#

please check the docs

#

you need to pass either the actual channel object of the category, or discord.Object(id of the category) should work too

cerulean laurel
#

oh ok

#

it worked thx

sage tendon
#

np

cerulean laurel
#

im trying for at least 2 hours

sage tendon
#

always have the docs open

#

(and use them lol)

#

also you might wanna run checks on the name the user passes for the channel, i think you'll just get an error if it's too long or uses forbidden characters

#

or depending on what you wanna do you could also have a channel named aufgaben, and the individual things the users create are threads
threads also have more lax naming restrictions and also capitalisation

cerulean laurel
#

ok

dense summit
#

with paginator is possible to allow the user interact with the buttons only if they have x role?

round heart
#

You'd have to put the logic in the button callbacks. For permissioned stuff like that, it can often be more beneficial to just make it an ephemeral, so you can control who can even start the interaction.

dense summit
round heart
# dense summit well what i want to achieve is that everyone can click the button to get the pag...

Your options are:

  1. Make the reply ephemeral
  2. Don't send the Paginator controls if a non-permissioned user presses whatever initiates the display
  3. Keep it as it is, but just return False (or optionally some feedback) in the Paginator callback buttons if a non-perm'd user interacts with it. (You'll have to create your own View for this)

Public interactions are public; it won't change output from one user to another.

dense summit
floral ice
#

basically i defined slash command in cog like this async def cmd(self, ctx: discord.Interaction, img, link, dms):

#

what i get is discord.errors.ExtensionFailed: Extension 'commands.memes' raised an error: TypeError: Invalid class <class 'discord.interactions.Interaction'> used as an input type for an Option

sage tendon
#

ctx is not discord.Interaction

#

and show your code, the entire command with decorators

floral ice
#

really?

sage tendon
floral ice
#

oh

#

was it always like that?

#

oops

sage tendon
#

for slash commands, in pycord, yes

floral ice
#

its fine now

sage tendon
#

ah that was the issue? lol

floral ice
#

idk why im using interaction

floral ice
sage tendon
#

or taking a view function or whatever

floral ice
#

maybe because i moved from dpy

#

not the code, but i was rewriting smth

#

and never noticed, until cogs xd

#

tysm

summer knot
#

How can I see the boost amount of a member?

little cobalt
#

or everywhere?

sage tendon
summer knot
summer knot
#

because what I want is the amount of boost that a person gave

sage tendon
#

i know, thats why i said what i said

#

check if it returns members who boosted twice, twice

#

if not then i dont think you can, as you cant in the normal UI either

summer knot
# sage tendon check if it returns members who boosted twice, twice

nope It returned this:
[<Member id=814345765119590401 name='seba.nose' global_name='N' bot=False nick='N🍀(Future Assistant)' guild=<Guild id=1030567179726360657 name='ElServidorDelYonny [🎃]' shard_id =0 chunked=True member_count=2245>>, <Member id=1145046847317082192 name='ping1292z' global_name='PinG' bot=False nick='PinGas' guild=<Guild id=1030567179726360657 name='ElServidorDelYonny [🎃]' shard_id =0 chunked=True member_count=2245>>, <Member id=1161614399497310279 name='hijodedios_7' global_name='★' bot=False nick='Jasuas' guild=<Guild id=1030567179726360657 name='ElServidorDelYonny [🎃]' shard_id =0 chunked=True member_count=2245>>, <Member id=1281398673548251188 name='pepe_supremo123' global_name='Pepe the Magician' bot=False nick='Hearo remaster' guild=<Guild id=1030567179726360657 name='ElServidorDelYonny [ 🎃 ]' shard_id=0 chunked=True member_count=2245>>, <Member id=1017684724329746492 name='.itzjoel.' global_name='«†Joel♣»' bot=False nick='«†Joel♣»' guild=<Guild id=1030567179726360657 name='ElServidorDelYonny [🎃]' shard_id=0 chunked=True member_count=2245>>, <Member id=1029908521086627930 name='elyonnymasna' global_name='ElYonnyMasNa' bot=False nick=None guild=<Guild id=1030567179726360657 name='ElServidorDelYonny [🎃]' shard_id=0 chunked=True member_count=2245>>]

#

it does not return the number

sage tendon
#

but it returns them multiple times.

#

oh wait

#

no thats the guild lol

#

mb

summer knot
summer knot
sage tendon
#

yea then i think you cant

dense summit
#

hey there i have some code that should create a view depending on the options passed on the command although i have some problems making the view created from it remain persistent.

the current issue is that after restart, every view sends the pages of the default one instead of the one they should. how can i make them persistents while making them send the right pages?

code:
https://mystb.in/5aa5db1ccf078250a9

summer knot
sage tendon
#

dont ping people for help please

summer knot
summer knot
sage tendon
dense summit
sage tendon
#

message id | page that should currently be displayed

proven valley
#

I want to write a ingame bot that invites users to a match, and it keeps track of the stats and such, but I want it to do it automatically based on the state of the queue that users can enter through the discord bot, anyone know any thing I can look into it to make it possible?

safe iris
#

Why is it that this doesn't work:

debt = discord.SlashCommandGroup("debt", "Manage your debt")

@debt.command(name="add")
async def debt_add(ctx: ApplicationContext, ...)

but then i change
@group_name.command(name="add") => @bot.slash_command(name="add")
and it immediately works?

rugged lodgeBOT
echo wraith
#

so it's bot.slash_group

dense summit
safe iris
# echo wraith so it's bot.slash_group
@bot.group()
async def debt():
    pass


@debt.command(name="check")
async def debt_check(ctx: ApplicationContext):

i do this and then
TypeError: debt() got an unexpected keyword argument 'guild_ids'

dense summit
sage tendon
#

@safe iris do you use cogs? if yes, the way you did it first is right

sage tendon
sage tendon
#

hm, yea no clue how to do it without cogs

safe iris
sage tendon
#

but paillat said slash_group and you did group

safe iris
#

is this the part where i learn cogs

safe iris
sage tendon
#

you really should if you have more than like 3 commands

safe iris
echo wraith
safe iris
dense summit
sage tendon
#

yes, that's how I'd do it

safe iris
#

and still doesn't

#

lol

echo wraith
#

just

#

debt = bot.slash_group(...)

sage tendon
#

it is a decorator tho, say the docs

safe iris
sage tendon
#

but I also don't know what it means with "initialises the given subclass of slashcommandgroup"

#

I'll be honest just do it with cogs, idk why slash groups are apparently so hard without cogs lol

safe iris
sage tendon
#

that's prefix groups

rugged lodgeBOT
echo wraith
#

mb

safe iris
echo wraith
#

it's
debt = bot.create_group(...)

sage tendon
#

I think I know how the decorator version is supposed to work but it's kinda meh

safe iris
cerulean laurel
#

how can you add a linebrak between varible inputs?

sage tendon
#

just put a line break lol

echo wraith
cerulean laurel
#

and how

sage tendon
#

press enter?

cerulean laurel
#

and the thing with \n

sage tendon
#

I love how your code is just no typehints and nothing, it just instantly returns the inputs back to the user lol

sage tendon
#

that's for strings

#

also I have no idea how you're passing all that to ctx.respond

#

are you trying to concatenate it all into one big string?

cerulean laurel
#

and the python code for a new line

sage tendon
#

ah

#

yea use an f String thrn

cerulean laurel
#

?

sage tendon
#

currently you're passing everything as a seperate positional argument

#

which doesn't work

cerulean laurel
#

ok and how do i fix it

sage tendon
#

f"{variable}\n{variable2}"

#

this is what you want I think

cerulean laurel
#

oh ok

safe iris
safe iris
echo wraith
sage tendon
#

guide is low-key outdated

safe iris
sage tendon
#

or well, not outdated but not well maintained IMO
so it can happen that some stuff doesn't work

safe iris
cerulean laurel
sage tendon
#

show your code

#

you probably didn't make it an f String

cerulean laurel
#

its f

sage tendon
sage tendon
cerulean laurel
#

oh my bad

sage tendon
#

are you trying to build an embed btw?

cerulean laurel
#

no just a message

sage tendon
#

hm ok

#

also btw instead of the Option with just required=False you can also do footer=None

cerulean laurel
#

i have to make the footer required beacause right now it just sais "None"

sage tendon
#

hm

#

could do footer='' then or just do {footer if footer else ''}

cerulean laurel
#

in the input?

sage tendon
#

the first goes in the function header

cerulean laurel
#

?

sage tendon
#

what

safe iris
#

well thank you so much and have a great rest of ur day ShibaHeart

sage tendon
#

np

cerulean laurel
#

{footer if footer else ''} that in the fstring

sage tendon
#

yea

cerulean laurel
#

worked, thx

dense summit
sage tendon
#

because you never set it lol

#

you just create a button and thats it

#

I'd recommend just using the decorator method to define buttons tho ngl

#

like here

dense summit
#

ty let me try

dense summit
# sage tendon like here

tbh im just having issues with using the decorator as i cant use the self variables how can i just set the callback with my current code?

sage tendon
#

i think button.callback = ..

dense summit
#

yeah got it, button.callback = func

#

and the func should only take an interaction object

safe iris
#
if message.content == "react me aaa":
    await message.add_reaction(":white_check_mark:")
    return

then
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body

how am i doing this wrong 💀

#
await message.add_reaction("✅")

this works for some reason?

sage tendon
#

Because you cant add reactions with the shortform like that

dense summit
#

last question, now i want that everyone can click the button to send the pages but i want to limit people without a role on the first page and people that have x role can use the buttons to navigate. how can i achieve that?

sage tendon
#

just build that into the button logic

dense summit
sage tendon
#

ah you're using the built in paginator as well?

dense summit
#

yes

def create_paginator(self, slide_data):
    """Create and return a paginator for the slides."""
    # Define buttons for pagination
    buttons = [
        PaginatorButton("prev", label="<", style=discord.ButtonStyle.green),
        PaginatorButton("page_indicator", style=discord.ButtonStyle.gray, disabled=True),
        PaginatorButton("next", label=">", style=discord.ButtonStyle.green),
    ]

    # Create a list of pages from the YAML data
    pages = self.create_pages(slide_data)

    # Create and return the paginator
    return Paginator(pages=pages, show_indicator=True, use_default_buttons=False, custom_buttons=buttons)

sage tendon
#

ah, then i have no idea, never worked with the paginator

fresh sierra
#

And you will be able to change the button

dense summit
fresh sierra
#

And then you edit the button part

#

(Look on GitHub how the thing is so you just have to change the button)

#

Should be really easy

dense summit
#

uhm i'll try

#

ohh i got it

#

it was more easy than i thought

#

how do i defer a paginator?

sage tendon
#

interaction.defer()

#

same as with normal views

dense summit
#

ah ok thanks

#

thought it was different

sage tendon
#

interaction.response.defer()* mb

echo wraith
fresh sierra
#

how can i check if the bot can use the custom emoji ?

#

because in some dropdown i got some error invalid emoji

echo wraith
#

Try except trollcube

fresh sierra
#

there is no way to know ?

#

i mean its a good way

#

i can still just replace my fonction by the creation of a dropdown and then see if its works or not

sage tendon
#

no permission needed for those, I've been told

fresh sierra
sage tendon
#

gonna need more context here then

#

are you trying to use user supplied custom emojis?

fresh sierra
sage tendon
errant trout
#

if it has to be guild emojis, just do a permission check

civic moon
#

I keep getting "interaction failed" and "discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction" at the defer() line in this callback. Only the first time I click.

Any idea why?

    
    async def callback(interaction):
        bi = int(interaction.custom_id)
        if bi != 3:
            await interaction.response.defer()
        else:
            modal = ManualModal(title="Enter Member Name", custom_id="ManualModal")
            await interaction.response.send_modal(modal)
            await modal.wait()
            #do stuff
        #do stuff

    matches = ["Test1", "Test2", "Test3", "Manual"]
    v = [discord.ui.View(timeout=None)]
    b = []
    for i, m in enumerate(matches):
        b.append(discord.ui.Button(label=m, custom_id=str(i)))
        b[i].callback = callback
        v[0].add_item(b[i])
    await msg.channel.send("Test", view=v[0], delete_after=900)```
sage tendon
#

why do you have an async def inside an async def

#

ah
you cant defer modal responses

civic moon
#

I'm not defering the modal. Just a button click callback

sage tendon
#

i mean you are deferring the interaction, and then send a modal

#

cant do that

edgy nest
#

they're not

#

indentation is broken

sage tendon
#

ah

edgy nest
#

copy pasting is hard

civic moon
sage tendon
#

oh yea ic i think

civic moon
#

I only defer if it's not for the button to send the modal.

#

Basically I'm almost immediately defering but it's like the button times out and isn't defered.

sage tendon
#

are you sure you aren't somehow taking 3 seconds to reach the defer? like idk what the rest of your code looks like

civic moon
#

Only the first time I click it though.

#

The callback I imagine is immediately called when the button is clicked. The call back only does this before the defer line:

    async def callback(interaction):
        bi = int(interaction.custom_id)
        if bi != 3:
            await interaction.response.defer()
civic moon
# edgy nest copy pasting is hard

I simplified the code in a text editor real quick to make it more readable. And that editor broke the indentation. It's fixed now. If only it was as simple as copy paste your code but it would take up the entire screen unfortunately and no one wants to read pointless code in between.

loud kayak
#
class AdvertisementButtons(discord.ui.View):
  def __init__(self, bot):
    self.bot = bot
    super().__init__(timeout=None)
  
  @discord.ui.button(label="Report", style=discord.ButtonStyle.red, custom_id="REPORTSERVERBUTTON")
  async def report_server_button_callback(self, button, interaction):
    await interaction.response.defer(ephemeral=True, invisible=False)
    await interaction.followup.send("Coming soon.", ephemeral=True)

# Somewhere else

view = AdvertisementButtons(bot=self.bot)
view.children = [view.children[0], discord.ui.Button(label="Invite PartnerPal", style=discord.ButtonStyle.link, url="https://partnerpal.nziie.xyz/invite")]

This persistent view will occasionally have the Report button which is the original button in the view. I've tried different ways to get a link button in there with a persistent view but its definitely random of when the Report button actually shows up.

#

exact same function

harsh crane
#

I'm creating a basic ticket bot and everything seems to work, but after a while the main interaction with buttons just keeps failing? No error in terminal or anything, it's still running.

sly karmaBOT
#

Tag not found.

Did you mean...
persistant-view
persistent

fresh sierra
#

.tag persistent

sly karmaBOT
#

The Issue

When you send a message with a view, button for example
if your bot restarts, you will lose the ability to use this button.

How To Fix This

  1. Set your view timeout to None
  • By default, the view timeout value is set to 300 seconds
  1. Pass a custom_id value to the view
  • Custom ids must be unique
  • Chose a custom id that has a meaning in relation to your view
  1. Add the view to the bot
  • You can use the method Bot.add_view(YourViewClass())
  • Make sure to add the view when the bot begin ready
harsh crane
#

Thank you!!!

jaunty blaze
#

I have a channel with up to 100 messages (created automatically).
Each message has a button.
Clicking that button does something destructive.
So I'd like the user to confirm the action.

How would you approach that?
I've considered an ephemeral message with another button. But the message one will appear at the bottom of the channel. So if you click the button on a message higher up you'd have to scroll down first :/
I've also considered an empty modal, but those aren't possible it seems.

Any other ideas?

lapis dock
#

Adding an item has a few more things done internally

self.__weights.add_item(item)
item._view = self
self.children.append(item)
lapis dock
# jaunty blaze I have a channel with up to 100 messages (created automatically). Each message h...

You could edit the message with new buttons but this might raise problems if they never select it, and the fact that it is not ephemeral may raise issues in your case. I think your model idea is great. You would just have to compromise and have one input text that you just ignore the contents of. You could but some placeholder text "You will be doing this destructive action. Are you sure you want to continue? If so press submit. If you want to cancel Press Cancel or The X"

jaunty blaze
#

Ah that's a nice idea!
I'll try that, thanks!

safe iris
#

Hey, I don't know if I am going insane but do on_message (A) and on_message_edit (B) use different caches somehow?
When executing the same things,
for A, message.guild.get_member(user_id).display_name
for B, after.guild.get_member(user_id).display_name

A produces an error saying AttributeError: 'NoneType' object has no attribute 'display_name', whereas B is able to get that display name

errant trout
safe iris
errant trout
#

just make sure user_id is always an int

safe iris
#

JUST now

#

😭

errant trout
#

rip

safe iris
#

i forgot to

#

yeah

#

thanks

#

:D

#

(and my ide says nothing about it)

sage tendon
#

which IDE

#

and remember python is all but typesafe, so IDEs sometimes can't detect that something is wrong

loud kayak
lapis dock
#

So the issue is that sometimes the Report button will not be included in the message?

flat wind
#

Hello
How can I differenciate the Apps and Server webhooks ?

errant trout
#

mmmm i guess it's a bit more complex

sage tendon
#

i didnt even know there was a difference.. what is the difference?

#

like i've never seen the top one

errant trout
#

server webhooks come from another server

#

(i think)

lapis dock
#

And that is different from an announcement channel post/publish?

sage tendon
#

yup you're right

#

the top one is a published announcement message

#

just checked

errant trout
# errant trout mmmm i guess it's a bit more complex
  • Message.webhook_id to see if it's a webhook (but this includes interactions)
    • Message.author.discriminator == "0000" to ensure it's a webhook
  • Server webhooks will have a message_reference that has a different guild_id to the current guild
#

so you need to combine all that

lapis dock
#

I thought the username would be the server name/channel and server pfp

sage tendon
#

oh

errant trout
#

i guess but you can't guarantee that's another server

#

(from an api perspective)

sage tendon
#

yea but it is ig? the channel is called #a ?

lapis dock
#

So the API allows you to just send a webhook as a server?

sage tendon
#

either that or there's another way of sending a "SERVER" message like that

errant trout
#

all webhooks can break the username rules so it wouldn't matter unless you only want to guess from that pattern

errant trout
cerulean laurel
#

how can i transform an in put into an str object

lofty parcel
#
@discord.slash_command()
@discord.option(str, name="my_option", description="My option")
async def my_command(self, ctx, my_option: str)
     ...
fresh sierra
#

if you put nothing it will also be by default str right

#

how to use the channel.can_send() ?

#

i dont understand what are the valid type

cerulean laurel
#

is there a way to get all categorys and display them as options to create a chat in

little cobalt
flat wind
cerulean laurel
#

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

#

?

#

what do i have to do?

sage tendon
#

No..

#

what are you trying to do

#

you are just calling the create stage channel method on the categorychannel class itself, that makes no sense

#

you need an actual channel object of a category channel to use that method, or use the create_stage_channel method of ctx.guild and pass the category channel as discord.Object(categorychannelID)

#

you could also just let the user select one of the guild's category channels instead of passing it by name, that just asks for errors

cerulean laurel
#

i just wanna create a stage

#

discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: Guild.create_stage_channel() takes 2 positional arguments but 3 were given

sage tendon
#

why are you passing self?

errant trout
cerulean laurel
#

discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: Guild.create_stage_channel() takes 2 positional arguments but 3 were given

sage tendon
#

again, why are you passing self?

cerulean laurel
sage tendon
#

ah

errant trout
#

you have to pass kwargs

sage tendon
#

yea, it doesnt take more than 1 positional argument

errant trout
#

i.e. name=name and so on

sage tendon
#

check the documentation for the method

#

name is positional tho

cerulean laurel
sage tendon
#

by using the option decorator to properly set up the option, and passing channel_types=[discord.CategoryChannel] in it

cerulean laurel
#

ok thx

sage tendon
fresh sierra
lofty parcel
#

Doesn't the docs say

nimble matrixBOT
fresh sierra
#

Apprently not content or embed

lofty parcel
#

Messages, embeds, files, emojis and stickers

fresh sierra
#

Or a content basic one but same

lofty parcel
#

I think message is just not passing anything

#

I tested with an embed and it worked too

#

Doesn't work if you pass a str

sage tendon
#

can_send is kinda weird

lofty parcel
#

Yeah lolz

jolly tundra
#

Idk if this is a discord bug or pycord, I didn't find much about it.
When you try to use this function message.channel.is_nsfw() but the channel there is a Thread... Shouldn't it act as the parent channel? So if the parent is NSFW, the thread is automatically NSFW

#

It's a User Install command btw

#

What I'm getting is that it always comes as false

jolly tundra
sage tendon
#

yea, user apps are extremely restricted

#

you cant access most of the guild related stuff

errant trout
jolly tundra
#

I don't want to restrict the command. I want the command to have a nsfw behavior, only if the channel is NSFW

errant trout
#

out of luck then apensive

jolly tundra
#

Btw about this... I tried out a couple of things, its so annoying to reproduce, every time I try recording it works.
One thing I noticed is that it seems to happen more often in group chats, and when I haven't been in the chat for a while XD

jolly tundra
#

I wonder if Discord doesn't provide the correct indicator if the channel is nsfw or not. Idk how pycord gets that value tho

sage tendon
#

its because its a user apps

#

user apps get absolutely nothing compared to a guild-installed bot

jolly tundra
#

I bet

echo wraith
sage tendon
#

its dumb

jolly tundra
#

Its very specific to the threads, its kinda dumb

#

xD

echo wraith
#

Imo

jaunty blaze
#

Is there a way to have a function get called for every application command, before the actual application command gets executed?
I tried listening to on_application_command, but it always gets executed after the actual command.

I want my bot to always defer on any slash command before executing the actual command handler.

fresh sierra
#

I want my bot to always defer on any slash command before executing the actual command handler.
sooo i did that using a bot check

jaunty blaze
fresh sierra
jaunty blaze
#

I see

#

So they actually get executed somewhat in parallel?

fresh sierra
#

but if you use a bot check, it will first do what there is inside ur check fonction before actually lunching the command

jaunty blaze
#

what's a bot check?

fresh sierra
#

.rtfm bot check

jaunty blaze
#

oooh, thanks!

#

Sounds good.

#

Hmm. I'm getting

discord.errors.CheckFailure: The global check functions for command settings failed.

my code is:

@bot.check
async def always_defer(ctx: ApplicationContext):
    await ctx.defer()

I guess it's because check is expecting a non-async function?

little cobalt
#

I just added defer to all my commands

jaunty blaze
#

guess I'll do that as well. Also tried making the check function sync and using asyncio to defer, but to no avail.

sage tendon
#

what code are you running in the event?

jaunty blaze
#

Just await ctx.defer().

sage tendon
#

ah

#

well, why do you want to defer every command

little cobalt
jaunty blaze
#

because they all request one or more external APIs, which don't always respond in time

little cobalt
sage tendon
#

ah

sage tendon
jaunty blaze
#

Well... another solution would be to subclass ApplicationCommand and implement my own @SlashCommandGroup.command() & @application_command() decorators ig?

#

Not sure if I'd wanna go that route tho

sage tendon
#

You could, but I genuinely think that's more effort than just to defer

little cobalt
#

Its actually pretty easy to do it

#

Just add defer to all the commands xd

jaunty blaze
#

I might go that route, if I need more custom command behaviour than just that

sage tendon
#

what is your bot that you need APIs in every command tho

jaunty blaze
#

It's getting info from a game's API (Pixel Starships) to display on Discord.

#

Stuff like item info, player info, clan info etc.

sage tendon
#

ah nice

fresh sierra
#
@bot.check
async def always_defer(ctx: ApplicationContext):
    if not ctx.response.is_done():
        await ctx.defer()
    return True
jaunty blaze
# lapis dock You could edit the message with new buttons but this might raise problems if the...

This works really nice! My code:

class ConfirmationModal(ModalBase):
  def __init__(
    self,
    action_name: str,
    action_description: str,
    callback: Callable[[Interaction], Coroutine[None, None, Any]],
    *,
    custom_id: Optional[str] = None,
    timeout: Optional[float] = 15.0,
  ):
    children = [InputText(label="Confirm action", placeholder=f"Submit this form to confirm {action_description}", required=False)]
    super().__init__(*children, title=action_name, custom_id=custom_id, timeout=timeout)

    self.callback_func = callback

  async def callback(self, interaction: Interaction) -> None:
    await interaction.response.defer()
    // Have to defer() here or the callback would be executed, but the modal would error and not close. Alternatively send a confirmation message to the user. If the callback takes very long, still defer() before calling it.
    await self.callback_func(interaction)

async def confirm_button_action(interaction: Interaction):
  await interaction.response.send_modal(
    ConfirmationModal("Action name", "doing this and that", button_action)
  )

async def button_action(interaction: Interaction):
  await service_layer.do_stuff()
#

Thanks again!

sage tendon
#

i may be stupid but doesn't your callback infinitely loop calling itself?

jaunty blaze
#

mmh doesn't seem so

#

the attribute added in __init__ is called callback**_func**

sage tendon
#

callback_func points at callback

#

so you are calling callback within callback

jaunty blaze
sage tendon
#

oh, you're right

#

mb

jaunty blaze
#

dw ^^

sage tendon
#

i forgor that in python you'd need to use self.callback anyway

#

sometimes i hate this language a little

jaunty blaze
# fresh sierra return true after

Aww man, I feel stupid now.
It works now. I even implemented it in a way that lets me specify the cogs whose commands should get auto-deferred. Don't need it for things like bot settings after all.

Thanks a lot.

short linden
#

I'm having a problem with autocomplete, my function that returns the list of options is working, I used print to debug, but for some reason it doesn't appear in the discord list if it doesn't follow the same order of letters as the words in the list, if the list has ['orange juice', 'apple juice'] and I write 'juice' in the parameter in discord, these two options don't appear even if the verification function returns this list.

echo wraith
lapis dock
#

My guess is you are using basic autocomplete and your own function. You should only be using one

sage tendon
#

im p sure the guide suggests using both at once at one point

#

or the docs, not sure

lofty parcel
#

Does it

#

That should be changed

sage tendon
#

the "inner" function, IIRC, just returns a list of all options, and the basic autocomplete fuzzy matches it

#

smth like that

#

ill google it in a min

echo wraith
short linden
#
@bot.command(description = '/register _type: "Type name" item: "item name" obs: "..." (obs= observation)')
async def register(
   ctx: discord.ApplicationContext,
   _type: discord.Option(discord.SlashCommandOptionType.string, min_length = 1, max_length = 25,
                         autocomplete = discord.utils.basic_autocomplete(funcoes.get_types)), # type: ignore 
   item: discord.Option(discord.SlashCommandOptionType.string, min_length = 1, max_length = 25, 
                        autocomplete = discord.utils.basic_autocomplete(funcoes.get_item_oftypes)),  # type: ignore
   obs: discord.Option(discord.SlashCommandOptionType.string, max_length = 30) = '' # type: ignore
      ):
   
   if (_type not in await funcoes.get_types(ctx)) | (item not in await funcoes.get_item_oftypes(ctx, _type)):
      await ctx.respond("Tipo de item ou item inválido.", ephemeral=True)
      return
   
   params = {
      'guild_id': ctx.guild_id,
      'user': ctx.author.id,
      'type': _type.strip(),
      'item': item.strip(),
      'gameid': await funcoes.get_game_id(ctx),
      'obs': obs.strip()
   }
   query = """
      INSERT INTO panel (server_id, user_id, game_id, item_id, obs)
      VALUES (:guild_id, :user, :gameid,(SELECT item_id FROM itens 
                                         WHERE type_id = (SELECT type_id 
                                                          FROM types 
                                                          WHERE type = :type 
                                                          AND game_id = :gameid) 
                                         AND item_name = :item), :obs)"""
   result = await funcoes.registrar(ctx, query, params)
   if result:
        await ctx.respond("item registrado com sucesso!", ephemeral=True)
   else:
      await ctx.respond("Isso já existe ou não está conforme!", ephemeral=True)

lapis dock
short linden
#
async def get_item_oftypes(ctx: discord.AutocompleteContext, _type: str = None):
    """Autocomplete para listar itens."""
    game_id = await get_game_id(ctx.interaction)
    _type = (ctx.options.get('_type', False) if ctx.options else _type)
    item = (ctx.options.get('item', False)) if ctx.options else None  # Usa `ctx.value` para capturar o que está sendo digitado
    params = {
        'guild_id': ctx.interaction.guild_id,
        'gameid': game_id,
        'type': _type,
        'item': f"%{item}%" if item else None
    }
    print(params)
    async with aiosqlite.connect('src/data/_test/data.db') as db:
        query = f"""
                SELECT item_name FROM itens
                WHERE (personalized_server = :guild_id OR personalized_server = 0)
                {"AND item_name LIKE :item" if item else ''}
                {"""AND type_id = (SELECT type_id 
                                 FROM types 
                                 WHERE game_id = :gameid
                                 AND type = :type)""" if _type else ''}
                ORDER BY item_name ASC
                LIMIT 25
                """
        print(query)
        async with db.execute(query, params) as cursor:
            data = await cursor.fetchall()
            result = [row[0] for row in data]
            print(result)
            return result

command used in discord: /register _type: Equipament item: Laby (i dont send, just test autocomplete to wait a list do "laby" itens)

echo wraith
#

.tag paste

sly karmaBOT
#

Please copy and paste your code here. This makes it easier for everyone helping you.

sage tendon
#

and also the code of the command where you use the autocomplete (at least the option you put autocomplete into)

#

but im p sure this is correct behavior

lofty parcel
#

Instead of return result do

return [result for result in result if ctx.content.lower() in result]
sage tendon
# short linden

can you do this again but add an a after the L? which options show up then

#

yea
basic autocomplete checks for startswith i think

short linden
sage tendon
#

yea, that's correct behavior then

short linden
sage tendon
#

no

short linden
#

how i can pass this

errant trout
#

basicautocomplete using startswith is criminal

sage tendon
#

you are using the function that does excatly that behavior

short linden
sage tendon
#

if you want some other behavior, try what dark said, and just dont do the basic autocomplete part

errant trout
#

just write your own autocomplete function

sage tendon
#

well they did, but they also pass it to basicautocomplete

short linden
lofty parcel
errant trout
#

i mean just skip it entirely

errant trout
sage tendon
short linden
sage tendon
#

that is the source code of the basic autocomplete

lapis dock
# short linden inherit it?

No, you just have to make a few switches. Currently you are retuning a list of all of the options to basic autocomplete. Instead you should make your autocomplete fucntion return the list of options that match your criteria, and not use basic_autocomplete

sage tendon
#

well, part of it

errant trout
#

i'd just glance through the example

rugged lodgeBOT
#

Here's the slash autocomplete example.

errant trout
#

it makes it pretty straightforward

sage tendon
#

the examples also use startswith lmfao

lapis dock
errant trout
#

well more importantly it shows how to implement without basic

short linden
#

in typing

shell radish
#

personally, use fuzzy search

short linden
sage tendon
#

you aren't passing a class there lol

#

what basic autocomplete does is to return a list of matching values

#

thats why it works like that

#

in the end if you write your own function it'll just be autocomplete = yourfunction

short linden
#

then, even if my options of "get_item_oftypes" return a list, if the start of the string not match the autocomplete ignore it?

sage tendon
#

no

#

YOU decide the list to return, so you handle all the filtering

#

basic_autocomplete just does it in a dumb way, thats why we're telling you to not use it

short linden
#

aaaaaaaaa, i change the basic_autocomplete for your check func then?

sage tendon
#

bro

#

😂

short linden
sage tendon
#

just make YOUR autocomplete function return the right values, and then do autocomplete = yourfunction
ALL values you return from that function will then show up in the UI

sage tendon
lapis dock
#

* You need to limit that to 25 results though, otherwise you will get an error

sage tendon
#

doesn't discord just cut the list short?

short linden
short linden
shell radish
#

i have an autocomplete returning 1400 items it’s fine

sage tendon
short linden
#

aaaaa

#

oke, i will try

#

ty

lapis dock
#

Also, I had no idea this worked choices = [1,2,3,4][:25] I thought that would give an index error. I feel like I have done that before and gotten an index error.

clear lark
#

is it possible to catch event based (particularly on_message) from the cog errors, tried cog_command_error but it doesn't catch anything event related

sage tendon
#

not sure if you'd get an error, no idea

shell radish
sage tendon
#

you can also do ...[:-1]

lapis dock
sage tendon
#

brother this is not C or rust

lapis dock
#

idk where I got that idea, but I have done that before

slender lantern
#

I remember being excited when I found out it works, too

shell radish
sage tendon
#

or printing

short linden
# sage tendon yip

Now that I looked for the definition of basic auto complete, I understand FalseFacePalmLaugh

slender lantern
sage tendon
#

felt

slender lantern
#

There was a proposal for it, but it never went anywhere

shell radish
#

ctx.author?.id

sage tendon
#

but the ? looks kinda out of place, i find it meh

slender lantern
#

It’s concise, at least

#

I also wish lambdas were better aka could be multiline

lapis dock
slender lantern
#

Yes

#

Wait

#

If author was none

sage tendon
#

imagine

if ctx.author then ctx.author.id and if ctx.author.id then <idk>
#

wait..

#

hm no this is cursed enough

shell radish
sage tendon
#

in java it works

#

by just doing {}

short linden
#

@errant trout @sage tendon !!!!!

sage tendon
#

nice

#

btw you can get rid of that underscore of your first option if you want, you dont have to change the actual parameter name even

slender lantern
#

Parameters can have different labels than the var name?

sage tendon
#

yes

#

depends on if you use the decorator or the typehint tho

#

for the typehint you can pass name=, for the decorator you change the name to whatever you want and then link it to the parameter via parameter_name=

short linden
sage tendon
#

yea but you can use what i said to still make it have the right name in the UI, I have the exact same problem for one of my commands

short linden
#

i configure the param with @option ?

sage tendon
#

both ways work

slender lantern
#

Nice. I assume they can’t have spaces still

sage tendon
#

never tried, don't see why not

short linden
#

like that?

sage tendon
#

you are still using basic auto complete lol wut

#

and no, for the typehint method you pass name="type"

echo wraith
short linden
#

aaaaaaaaaaa

#

true

sage tendon
#

also you don't need that whole slash command option type stuff
just passing str works too, or you can omit it altogether, it's str by default

short linden
#

but this param doesnt have some problems, is more the 'item', the type have less options

sage tendon
#

also idk what you're doing with that min and max length

short linden
#

but i can remove

sage tendon
short linden
#

a gigant name item

sage tendon
short linden
#

i have a command to add personalized itens

#

for the server

short linden
#

well the user doesnt need to "search" a type

sage tendon
#

you can make it optional then

#

if it's not needed for the command

short linden
#

but it's more because I didn't know I could implement my own autocomplete

short linden
lapis dock
sage tendon
#

not really sure rn

short linden
#

well i can set default fot item None and all of param are optional, i check it in the function

#

in cases of pp using only item param directly

#

but I appreciate it, it saved me hours of headache ❤️

sage tendon
#

np, if you need help just ask again

slender lantern
#

Is there an official release cadence? (I really want app emojis, which I know are in master)

sage tendon
#

not that I know of

errant trout
#

unofficially around christmas

slender lantern
# sage tendon never tried, don't see why not

Sadly they can't have spaces:
ERROR | COGS | Failed to load cog interface.cofd.basic: Extension 'interface.cofd.basic' raised an error: ValidationError: Command names and options must follow the regex \"^[-_\w\d\u0901-\u097D\u0E00-\u0E7F]{1,32}$\". For more information, see https://discord.com/developers/docs/interactions/application-commands#application-command-object-application-command-naming. Received "amazing option"

#

How can I send a multiline ``` ``` block? Here's my var:
'`d` is amgiguous. Did you mean: ```Dexterity\nDrive```'

#

The embed, however, drops the Dexterity part:

#

(that typo is fixed on another branch, lol)

errant trout
#

i doubt the library or discord would selectively ignore the Dexterity text

slender lantern
#

Yeah, it's odd. I'm on 2.6.1, and that's the value I pulled straight from the debugger. The method is simple:

#

(you can see my breakpoint there)

errant trout
#

what happens if you print embed.description

#

(through whatever method, e.g. before sending it or also fetching the message and checking it after)

slender lantern
errant trout
#

oh wait lol

#

you need a \n before dexterity

#

because it's reading the first line as a language code instead

slender lantern
#

Ah!

#

Good catch. I often do one-line code fences, but they're just one line. Thanks!

#

success!

errant trout
#

nice

slender lantern
#

So, I have multiple subscription tiers in Patreon (since they aren't supported in Discord yet). I'm currently checking to see if a user has one by checking if they have a role in my bot's server. Is that the standard way of doing it?

slender lantern
#

Also, is there a way to mark an entire cog as only being available to guilds, not in DMs?

slender lantern
#

Hmm. Looks like I can set contexts for a SlashCommandGroup. If I understand correctly, I can use that to ensure the entire group can only run in a guild?

sage tendon
#

yes

slender lantern
#

Okay, that works 👌

#

Looks like a better system than the old guild_only() check

sage tendon
#

yea, that's why its deprecated

errant trout
slender lantern
#

I mean that my Patreon supporters have a special role on my server that indicates they are paid supporters. My bot checks for this role to determine command eligibility. Is this the normal way of doing things?

#

(Yes, that role is managed by the Patreon bot)

sage tendon
#

you should just use the discord permission system if its slash commands

#

server settings > integrations > your bot > click any command and see

slender lantern
#

This is a bot on over 4k servers

sage tendon
#

so is it your bot?

slender lantern
#

Yes

sage tendon
#

so every guild can set patreo nroles

slender lantern
#

No, I have a "patreon" server. Supporters join that server and get the role, and they can use the premium commands wherever

sage tendon
#

ahh

#

i'd make a custom decorator for that