#Basic Pycord Help

1 messages · Page 24 of 1

sage tendon
#

like for what purpose

vital bramble
#

To have a role that can use a command but one can change the role that can use the command during runtime.
But I just remembered: The command.checks are basically the equivalent of just checking it in the callback, right?

sage tendon
#

server settings

vital bramble
#

That's the new way?

sage tendon
#

that has always been the way

vital bramble
#

Hasn't there been a commands.check for roles?

sage tendon
# sage tendon

No idea, but i cant imagine a use case where the discord menu isn't enough

vital bramble
#

ok but is it possible by now to change those values (in the serversettings) from code?

sage tendon
#

dont think so, but why would you ever need that

vital bramble
#

Hm yeah. I guess to make it easier to set it up...

#

faster*

sage tendon
# sage tendon

if you only use that bot in your server then just limit commands to manage_server perms or use this
you only need to do it once for every command

finite plover
#

its pizdec

deft kestrel
#

How can I stop the work wait_for before the timer expires

arctic plover
#

how to fetch a message?

arctic plover
#

Thanks

deft kestrel
#

Guys, how can I stop a previously running process wait_for?

errant trout
deft kestrel
errant trout
rugged lodgeBOT
errant trout
#

Docs has a decent example of how it works

deft kestrel
arctic plover
#

How can I add a persistent view if the view class gets additional parameters? I can't just do bot.add_view(myView()) as there will be an AttributeError

deft kestrel
#

Depending on how many additional parameters you have, insert so many self

sage tendon
#

...why would they pass self for each parameter, that makes no sense

arctic plover
#

So I just pass any parameters and it will work?

sage tendon
#

pass the right parameters..

lapis dock
#

Basically you just manually create the view. You will not have some of the cached properties like View.message but it is just passing a instance of View in the end.

arctic plover
sage tendon
#

what do you mean lol

#

pass the stuff you want the view to have

#

just make the view normally

arctic plover
#

It has many instances with different attributes

#

Do I have to add them all separately?

lapis dock
#

Yes

sage tendon
#

every existing view needs to be added yes

#

if you have a lot, well, good luck

lapis dock
#

Most of the time on bot startup you will need to use a database and a for loop to add a bunch of views

arctic plover
#

So there is no easier way here?

sage tendon
#

no

#

if you want views, make them

#

you cant just magically make them think up arguments for themselves

#

well you can, but, yknow

frail ocean
#

Does someone have an example for automod rules

limber wagonBOT
#

dynoInfo There are no tags that match your search.

errant trout
#

i meannnnn

#

what are you trying to do

sage tendon
frail ocean
errant trout
#

again, example for what

#

like what's your goal

sage tendon
#

the docs have great code examples for automod iirc

frail ocean
sage tendon
errant trout
#

that's... a bit vague, there's a lot to automod

frail ocean
#

._.

frail ocean
errant trout
#

like in this case, reading the docs just makes sense

sage tendon
frail ocean
#

How many servers u have to create a rule to get the badge

errant trout
#

if you want to edit an existing rule, fetch it from the guild method and then use AutoModRule.edit

#

oh that

sage tendon
#

bruh

errant trout
#

idk i forgot the threshold but im pretty sure it's a constant check

sage tendon
#

just to farm the badge?

frail ocean
#

Na only want to know

#

No

errant trout
#

so you'll probably lose it anyway

sage tendon
#

i am quite certain its a fixed amount of rules, not servers

errant trout
#

eh... i can write one...

#

but it won't look particularly useful

sage tendon
#

just deduce it from the docs

#

its really not hard

#

fill the parameters with stuff and you're done

frail ocean
#

Hmm okay

#

and is there a way to get rules ?

sage tendon
#

of course

frail ocean
#

And how can i create slash command which look like that:
/automod blacklist add?

errant trout
# errant trout but it won't look particularly useful

like py await guild.create_auto_moderation_rule(name="Some Rule", event_type=AutoModEventType.message_send, trigger_type=AutoModTriggerType.spam, actions=[AutoModAction(action_type=AutoModActionType.block_message, metadata=AutoModActionMetadata(timeout_duration=60))], enabled=True, exempt_roles=[guild.get_role(...)], reason="example")it's so verbose that you have to read docs anyway

frail ocean
#

This 3 command names if u understand

frail ocean
#

Groups i know

#

But subgroups?

errant trout
#

subgroup is the last level, that example shows how to use create_subgroup

frail ocean
errant trout
#

yeah

frail ocean
#

Thank you 😄

#

And is there a id from automod rules or how to get them

errant trout
#

when you fetch them they'll have an ID attached

frail ocean
errant trout
#

like... any other discord id

#

snowflake format

frail ocean
#

Is there also a way to get who created the rule

#

?

errant trout
#

uhhhh

#

i don't think that's saved, only way would be through audit log

#

wait no

#

the creator attribute, completely missed it lol

frail ocean
#

Okay and last question:
Is ther a way to get if a server has premium from a bot or is there a "upgrade" event?

errant trout
#

like, server boosts?

#

or bot subscriptions

frail ocean
errant trout
#

hmmmmm im not sure if that's implemented

#

lemme see

frail ocean
#

❤️

errant trout
#

i've never used these, so you're on your own to test

frail ocean
errant trout
#

these are all user related yes, the docs tell you everything

frail ocean
#

Thanks you

#

and is there a way to get this via command?

sage tendon
#

get what

frail ocean
#

If a server has subscribed

sage tendon
#

what

errant trout
finite plover
sage tendon
#

certified read-the-docs moment

finite plover
#

sure

arctic plover
grizzled loom
errant trout
#

if your bot makes X amount of automod rules, it gets a badge for it

#

...for some reason

grizzled loom
#

definately dont want that, but i'll take a look at it. thanks for the link!

shell radish
#

nqn has it for emoji shenanigans

grizzled loom
#

jeeeesus. I'd never build a censor bot like this. possibly to help protect against raids or massive spam but other than that, no thanks.
okay, squids example may also make the list. but thats it 😄

shell radish
#

@austere loom

errant trout
#

well it's really just for creating built-in mod rules, but they also added an automod event so bots can throw in their own logic whenever a user messes up

grizzled loom
#

i once got short term banned (and quickly unbaned) when on the discord dev server someone asked why his bot would get rejected. i pointed out his f... nitro garbage in the bots discribtion, auto mod kicked in.

strongly dislike those mechanics cause they never ask for context.

#

same on a study server where literature was discussed and parts of it happened to be sexual, which is part of the main plot in some classics and was in this case essential to the book.

#

but i am going a bit of topic 🙃

deft hull
#

How do I set a local image as thumbnail of an Embed?

errant trout
sly karmaBOT
deft hull
#

my images are stored in a folder assets/portraits

#

I've tried "attachment://assets/portraits/image.png"

#

but the image does not display

errant trout
#

you're a bit off

#

as in the example above, you specify the file path and the name separately

#

the path is the actual path on your PC, while the name can be anything you want - that name is what you set in the embed.

deft hull
#

ah I see

#

let me try

#

damn

#

this is going to be a bit hard for how I store my embeds

errant trout
#

what's the issue?

deft hull
#

the thing is I store my embed in a subclass

#

and I have a lot of ui components that edit the message to update the embed

errant trout
deft hull
#

no issues, I just have to define the file in every ui component

#

and my file changes depending on some parameters lol

errant trout
#

ah i see, just make sure it's a new object every time because File isn't reusable

deft hull
#

hopefully I don't run into a lot of issue lol

#

(oops I forgot to specify the filename)

#

damn nice it worked thank you

errant trout
#

allgood

deft hull
#

this is my view object and the output

#

how do I rearrange it to become
[OutfitSelect]
[ShinyButton] [ChangeLevel]

lofty parcel
#

Cute bot lmao

#

What does it do?

deft hull
#

it just displays info from the game lol

lofty parcel
#

Give your select row 0 and your buttons row 1

deft hull
#

ah ok

lofty parcel
#

Edit. Its zero indexed

deft hull
#

thank you

ivory beacon
#

How many seconds do I have to wait before changing the bot's activity?
to avoid rate limit

edgy girder
#

Im currently using requests for a small task that runs once weekly and uses a get and a post request, is it worth it to re write it in a non blocking library?

Its for a small 3 server project

edgy girder
edgy girder
ivory beacon
fresh totem
#

Hey

I'm trying to delete all the messages froma channel using

    await channel.delete_messages()

what should I set the messsages parameter as? there are < 100 messages in these

edgy girder
#

sorry for the phantom had to make sure i wasen't just making shit tf up

fresh totem
granite pier
#

thats what .flatten() does

#
async def flatten(self) -> list[T]:
    return [element async for element in self]
#

just fyi ;p

fathom cedar
#

What does that mean

errant trout
errant trout
#

If it's still broken, show the whole command definition/class

fathom cedar
rugged lodgeBOT
errant trout
#

Yeah just remove the Context typehint

#

(More specifically it should be ApplicationContext, but really you don't need to specify at all)

fathom cedar
#

okkk

#

worked ty

hushed pebble
#

Guys, is it possible to have already something in modal?

like i want to make one modal, and i need that it will ask if you can edit like you wrote something in modal and it saying:

publishing modal?
YES|NO|EDIT

and when im clicking on edit it will send to me to modal with the text that i already wrote there so i can edit it

#

sorry for grammar mistakes if i have any, im not english speaker

fathom cedar
#

yes i already saw a modal like that

hushed pebble
fathom cedar
#

how to fix this error: "Call expression not allowed in type expression"

errant trout
#

The code should still run fine unless your IDE's explicitly blocking it

#

(In which case there should be some "ignore" button, but it varies)

fathom cedar
#

oh okay

hushed pebble
hushed pebble
errant trout
#

That's me

hushed pebble
# errant trout That's me

`Ignoring exception in command kodartupdatescom:
Traceback (most recent call last):
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\core.py", line 180, in wrapped
ret = await coro(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Lenovo\Downloads\KodArt\main.py", line 165, in kodartupdatescom
view = UpdatesView()
^^^^^^^^^^^^^
File "C:\Users\Lenovo\Downloads\KodArt\main.py", line 113, in init
self.add_item(Update())
^^^^^^^^
File "C:\Users\Lenovo\Downloads\KodArt\main.py", line 88, in init
super().init(
TypeError: Modal.init() missing 1 required keyword-only argument: 'title'

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

Traceback (most recent call last):
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\bot.py", line 349, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\core.py", line 959, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Lenovo\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\core.py", line 189, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: Modal.init() missing 1 required keyword-only argument: 'title'
`

#

where do i put title in modals

errant trout
#

Inside super init

hushed pebble
#

but now i need to do prefix command so idk where to put

errant trout
#

In prefix commands, you have to create a button and use that button press to send the modal

#

Or select, basically it has to be from an interaction

hushed pebble
#

maybe i can put it in View?

class UpdatesView(discord.ui.View):
    def __init__(self):
        super().__init__()

        self.add_item(Update())
errant trout
#

No, modals can't be added to views

#

They are separate

hushed pebble
errant trout
#

Because they're different concepts

hushed pebble
#

i tried with dropdown menu and it worked

#

i guess they are also different concepts

errant trout
#

Dropdown can be added to a view, yes

#

But modals and views exist separately

#

Views are a Pycord concept, on discord everything is a "Component" - Modals are outside of this

hushed pebble
#

oh well it is harder that i guessed

little cobalt
#

its not hard

#

its really easy

hushed pebble
#

dont thing so

#

after i will create button it will show me thousands more errors

errant trout
#

There's also the examples on the repo if you wanna see how it comes together

rugged lodgeBOT
#

Here's the modal dialogs example.

little cobalt
main carbon
#

quick question, is this not how i use once parameter?

    @discord.Cog.listener(once=True)
    async def on_ready(self):
hushed pebble
#

how can i code no button so when you will click it it will delete message

errant trout
hushed pebble
errant trout
#

(You might need to defer first)

hushed pebble
#

thanks it worked!

errant trout
#

Allgood

main carbon
# errant trout It should be

i got
discord.errors.ExtensionFailed: Extension 'modules.parent' raised an error: TypeError: Cog.listener() got an unexpected keyword argument 'once'
though i'm using py-cord==2.5.0

errant trout
#

Uhhh hold on

errant trout
main carbon
#

lmao

errant trout
#

There's still @bot.listen... but jeez insane we didn't notice that

main carbon
#

i'll wait for the update then, thanks

errant trout
#

If you want you could probably just implement it yourself by editing cog.py

#

Should be a 2 line edit

main carbon
#

i’ll try tmr cuz i’m going to sleep soon, thanks!

noble flax
#

Does "app_commands" not exist in py-cord?

errant trout
#

No, we have our own slash command structure

noble flax
#

Trying to create my own autocomplete from an example as I've failed horriblity at trying to implement one myself

errant trout
#

Oh autocomplete should be easy

noble flax
#

Need to create a fuzzy autocomplete and failing horribly lol

errant trout
#

Maybe use regex?

noble flax
#

I've used "basic" autocomplete and got that working but really need a fuzzy one, which I'm struggling to create

errant trout
#

Or some fuzzy search library

sage tendon
#

magic weapon .startswith()

rugged lodgeBOT
#

Here's the slash autocomplete example.

noble flax
#

I've used fuzzywuzzy but I can't get the function to work

errant trout
#

This shows how to implement your own function

noble flax
#

Much appreciated sir/madam

grizzled loom
# fathom cedar worked ty

i dont think this failed because you were typehinting, but because you were typehinting incorrect.
try "ctx: discord.ApplicationContext" instead.

fathom cedar
#

okkk

hushed pebble
#

@errant trout
can u help me with edit button?

#

idk how to do it

errant trout
#

If you're on 2.5, use interaction.edit

hushed pebble
# errant trout Do what
class UpdatesSubmitView(discord.ui.View):
    def __init__(self):
        super().__init__()
        self.value = None

    @discord.ui.button(label='Yes', style=discord.ButtonStyle.success)
    async def yes_button(self, button: discord.ui.Button, interaction: discord.Interaction):
        if interaction.guild.id == 1214612682951491645 and not interaction.user.bot:
            await interaction.followup.send("hello world")

    @discord.ui.button(label='Edit', style=discord.ButtonStyle.grey)
    async def no_button(self, button: discord.ui.Button, interaction: discord.Interaction):
        #what to write there?
        ...

    @discord.ui.button(label='No', style=discord.ButtonStyle.danger)
    async def no_button(self, button: discord.ui.Button, interaction: discord.Interaction):
        await interaction.response.defer()
        await interaction.delete_original_response()


class Update(Modal):
    def __init__(self, *args, **kwargs) -> None:
        super().__init__(
            discord.ui.InputText(
                style=discord.InputTextStyle.long,
                label="Обновление",
                required=True,
                placeholder="Введите новое обновление..",
            ),
            *args,
            **kwargs,
        )
    
    async def callback(self, interaction: discord.Interaction):
        embed = discord.Embed(title="Ваше обновление было написанно! Опубликовать?", description=
f"""
**Вот так выглядит ваш текст:**
{self.children[0].value}
""", color=discord.Colour.blurple(), timestamp=interaction.message.created_at)
        embed.set_footer(text="Kodart")
        view = UpdatesSubmitView()
        await interaction.response.send_message(embed=embed, view=view)
#

i need that when i will click on edit button it will give me back the inputtext

errant trout
#

Like, the modal?

#

You're looking for interaction.response.send_modal

sage tendon
#

Anything I need to change when I convert a bridge bot to a slash bot? I know the bot definition has to change (to what?), but anything else?

errant trout
#

Uhh just check through what decorators you're using for commands

#

If you still want prefix commands, use ext.commands.Bot

sage tendon
#

no, only slash

errant trout
#

Then discord.Bot is fine

sage tendon
#

I'm using BridgeBot right now I think

errant trout
#

Yeah, BridgeBot supports all commands and is an extension of ext.commands.Bot

sage tendon
#

and for decorators I think I only have bridge_command (obvious change) and @option so that's not much to change

errant trout
#

Yeah that's all really

#

Basically just give it a go and debug any straggling errors

hushed pebble
# errant trout Like, the modal?

yes, i want that you can write firstly in modal then it will ask
do you want to send it
YES|EDIT|NO
if you will click on edit it will bring back you to modal

errant trout
#

Right, so your edit button can send the same modal with their old input already set

#

Looking at your Update code, you actually support this already - just pass value as their old input

#

Oh actually not quite

#

I'd recommend adding a new argument to update, then setting value in InputText

hushed pebble
#

i didnt really understood what you said

errant trout
#

I'll break it down a bit more

#

To pre-fill an InputText box, you need to set the value attribute (like you already have placeholder etc)

#

To do this in your Modal subclass, I would recommend adding a new argument to init where you can specify the user's previous input

#

(I'm going on the assumption that you want to use the same Update modal)

errant trout
#

Where you have *args, **kwargs, before that you can just add another parameter

hushed pebble
#

?

errant trout
#

You can just default previous_input to None

#

Won't have to use that if/else

hushed pebble
# errant trout You can just default previous_input to None

and in edit i will put this?

@discord.ui.button(label='Edit', style=discord.ButtonStyle.grey)
    async def edit_button(self, button: discord.ui.Button, interaction: discord.Interaction):
        await interaction.response.edit_message(view=None)
        view = Update(previous_input=self.previous_input)
        await view.edit_callback(interaction, self.previous_input)
errant trout
#

Uhhhhh

#

If you want to send a modal, you have to use response.send_modal and no other responses

#

I'd recommend removing the view after the modal is submitted with some other method

hushed pebble
#

like this?

errant trout
#

interaction.response

#

send_modal only takes the modal object

hushed pebble
#

but i need modal

rugged lodgeBOT
errant trout
#

What else are you trying to do

hushed pebble
#

i guess i understood

#
@discord.ui.button(label='Edit', style=discord.ButtonStyle.grey)
    async def edit_button(self, button: discord.ui.Button, interaction: discord.Interaction):
        view = Update(interaction, previous_input=self.previous_input)
        await interaction.response.send_modal(view)
errant trout
#

Yep you got it, probably

hushed pebble
#

how do i get previous_input??

errant trout
#

Ah, from the old modal?

hushed pebble
errant trout
#

You're gonna have to chain it - repeat the argument part for UpdatesSubmitView to pass it through

#

(To access it in modal, something like self.children[0].value)

errant trout
#

it should be the same logic, in theory

hushed pebble
#

maybe json file?

errant trout
#

What did you try

hushed pebble
errant trout
#

Did you actually make the param

hushed pebble
#

ye

sage tendon
#

whats the equivalent of this well, without bridge?

#

@commands.has_permissions(ban_members=True) right?

#

and whats the difference to this?

shell radish
sage tendon
#

thx

#

ahw cmon surely there is a way

#

(it cant resolve ctx)

shell radish
#

None and handle it internally

sage tendon
#

yea thats how i do it rn

sage tendon
#

okay i might be dumb but i have taken a brief= kwarg into my bot from an old codebase and i just learnt that SlashCommand doesnt even have that kwarg???

#

am i dumb lol

shell radish
#

never heard of it

sage tendon
#

yea its description=

errant trout
#

oh channel didn't scroll oops

errant trout
sage tendon
#

ahh, thats probably where it stems from

granite pier
edgy nest
#

just user = user or ctx.author

sage tendon
#

wont that make it a bool?

granite pier
sage tendon
#

thats new

granite pier
# granite pier nah
user = user or user2 # if user is None then user2, if both are None then None
username  = user and user.name # if user is None then None else user.name
errant trout
#

the second would be a bool

#

oh wait wrong syntax fair enough

sage tendon
#

that is just awful

granite pier
#

but idk

#

it's useful sometimes

deft kestrel
#

discord api down?

sage tendon
#

no

lapis dock
hushed pebble
crystal patrol
#

guys how can i using decision if the arg1 is empty in the bot command?

lofty parcel
crystal patrol
#

okay

lofty parcel
#

Ask again.

crystal patrol
#

that was my ask

#

ty

lofty parcel
#

What?

#

Mk...

trail tiger
#

Hey, looking to have the bot send a message to a user when joining a server, but after they have completed onboarding/accepted rules. I don't see an obvious way to do that, is there an existing event like "completed_onboarding" or will I need to make my own way detect that?

lofty parcel
#

This is discord.Member.pending on the docs.

trail tiger
#

nice! thanks so much!

#

knew I had to be missing something

hushed pebble
#

guys is there any way so bot will message everyone who is on the same guild as bot?

#

i want to create news command, and it will work like this:
im sending message to bot and this bot will send to all people that are in same guild about those news

lofty parcel
hushed pebble
median gorge
#

How to put descriptions on the place that written "No description provided"? I want to describe each arguments.

sage tendon
#

description= in each option

little cobalt
rugged lodgeBOT
#

Here's the slash options example.

sage tendon
median gorge
fervent surge
#

Why is it semingly impossible to manually invoke the function for a bridge command?

sage tendon
#

like?

fervent surge
#

I finally got it to work after mutiple trial and error attempts, digging through multiple source code files, etc.

sage tendon
#

what do you even want to do lol

fervent surge
#

I have to type out this long thing for it to actually work

await self.userinfo_cmd.slash_variant.callback(self, ctx, user=str(member.id))
fervent surge
sage tendon
fervent surge
#

yes

#

basically bridging it

sage tendon
#

man no idea

#

but that seems wrong

fervent surge
#

but when I went to convert my old function to a bridge command it fucked it up

#

when you try to execute the actual function

#

its not the function, but a BridgeCommand object instead

#

which has an invoke function, but wont allow you to pass arguments

fervent surge
fickle salmon
errant trout
#

I personally abuse process_commands by editing an existing message's data

lofty hedge
#

I got a lot of data I am trying to display and im not quite sure how i want to do this. So, its a command called gamestats which users gamestats for specific game. I don't know if i should use autocomplete, or what anyone got ideas?

It returns wins, losses, ties, tie amount, amoutn won, amount loss, current win streak, highest win streak. so just not sure what would make the most sense when displaying the data.

sage tendon
#

autocomplete for which part

lofty hedge
#

so /gamestats is the command. I want this as easy for the user as possible. So, maybe I could do /gamestats commandname and have that autocomplete? Im assuming teh way autocomplete works is by typing in a few characters it would help fill the rest for user for convenience.

Making it with buttons i dont think would make sense even if done with left and right arrow cause there's like 9 or so games, which im looking to expand on.

sage tendon
#

again, what do you even want to autocomplete

lofty hedge
#

the game name

sage tendon
#

make choices

lofty hedge
#

is the limit of choices still 25?

sage tendon
#

if not, yes, best way is autocomplete

#

if you have more than 25 i mean

round heart
#

Any definitive examples of translations? I didn't see any in the examples folder (at least by name)

shell radish
#

it’s called localization

round heart
#

Ah, I used 'translation'. I should have recalled localization (I did it for 10 effing years)

#

tyty, btw

rugged lodgeBOT
#

Here's the slash cog groups example.

errant trout
errant trout
#

well

#

good on you ig

sage tendon
#

why i18n?

#

i remember

errant trout
#

Internationalization, 18 letters between

swift egret
#

why am I spammed with those?
haven't updated pycord since

sage tendon
#

vsc thinks its smarter than you

#

it isnt

#

or rather, pylance does

round heart
shell radish
# sage tendon why i18n?

Sometimes some words like "localization" or "internationalization" are so long that writing them many times in one text is quite tiresome.

Let's consider a word too long, if its length is strictly more than 10 characters. All too long words should be replaced with a special abbreviation.

This abbreviation is made like this: we write down the first and the last letter of a word and between them we write the number of letters between the first and the last letters. That number is in decimal system and doesn't contain any leading zeroes.

Thus, "localization" will be spelt as "l10n", and "internationalization" will be spelt as "i18n".
Source: "Way Too Long Words" (codeforces.com)

swift egret
#

how can I get the version of the already installed pycord on my system? using linux

fervent surge
swift egret
#

thanks!

trail tiger
#

I'm trying to make a bot that does player counter for a game, that will periodically check how many players are online and update an embed in discord.
Where would be the best place for this loop? right now I have it in on_ready with a while True: ... await asyncio.sleep(600) does that seem like the right place?

lofty parcel
#

Use tasks.

rugged lodgeBOT
#

Here's the background task example.

trail tiger
#

noice, I'm just re-writing a bot in pychord from discord.py cause me and another guy could not get slash commands to work in it

versed root
#

have any way to reload the command from cogs? i need to cycle the guild and reload, because when i restart the slash command did not reload

versed root
#

btw when i use reload_extension, the slash command also not reload on some server

high pilot
#

how do i make a dynamic arguement like i have an arguement which has select option. if the user lets say selects select 1 then the command must be required else no

sage tendon
#

thats not a thing, yet at least

#

if i understand you correctly

high pilot
#

yes okay thanks

#

one more thing , is it possible to add like 2 fields in a modal but atleast one is required

#

both cant be empty

high pilot
#

or a modal check

high pilot
#

like view.interaction_check

little cobalt
#

but you can add a default value at it with something like "None"

high pilot
#

this also not yet?

errant trout
high pilot
#

yes i understand that can i have it like if both fields empty i dont let the modal be submitted?

#

after clicking on submit

errant trout
#

it's not possible, no

#

i'd recommend check -> if they are both empty, display a button to resend the modal

high pilot
#

okay will do

rare marlin
#

Hello dear community, I need your help. How can I have the database retrieve the name and then insert it here?

options = [
     discord.SelectOption(label="test", emoji=":ticket:"),
]```  ```py
class TicketDB(ezcord.DBHandler):
    def __init__(self):
        super().__init__("db/ticket.db")

    async def setup(self):
        await self.execute(
            """CREATE TABLE IF NOT EXISTS ticket(
            server_id INTEGER PRIMARY KEY,
            category_id INTEGER DEFAULT 0,
            teamrole_id INTEGER DEFAULT 0,
            logs_channel_id INTEGER DEFAULT 0,
            ticket_channel_id INTEGER DEFAULT 0,
            set_name_count INTEGER DEFAULT 0,
            panel_name TEXT DEFAULT NULL
            )"""
        )

    async def set_category(self, server_id, category_id):
        await self.execute(
            "INSERT INTO ticket (server_id, category_id) VALUES (?, ?) ON CONFLICT(server_id) DO UPDATE SET category_id = ?",
            (server_id, category_id, category_id)
        )

    async def get_category(self, server_id):
        return await self.one("SELECT category_id FROM ticket WHERE server_id = ?", (server_id,))

    async def set_teamrole(self, server_id, teamrole_id):
        await self.execute(
            "INSERT INTO ticket (server_id, teamrole_id) VALUES (?, ?) ON CONFLICT(server_id) DO UPDATE SET teamrole_id = ?",
            (server_id, teamrole_id, teamrole_id)
        )

    async def get_teamrole(self, server_id):
        return await self.one("SELECT teamrole_id FROM ticket WHERE server_id = ?", (server_id,))

    async def set_logs_channel(self, server_id, logs_channel_id):
        await self.execute(
            "INSERT INTO ticket (server_id, logs_channel_id) VALUES (?, ?) ON CONFLICT(server_id) DO UPDATE SET logs_channel_id = ?",
            (server_id, logs_channel_id, logs_channel_id)
        )

    async def get_logs_channel(self, server_id):
        return await self.one("SELECT logs_channel_id FROM ticket WHERE server_id = ?", (server_id,))

    async def set_ticket_channel(self, server_id, ticket_channel_id):
        await self.execute(
            "INSERT INTO ticket (server_id, ticket_channel_id) VALUES (?, ?) ON CONFLICT(server_id) DO UPDATE SET ticket_channel_id = ?",
            (server_id, ticket_channel_id, ticket_channel_id)
        )

    async def get_ticket_channel(self, server_id):
        return await self.one("SELECT ticket_channel_id FROM ticket WHERE server_id = ?", (server_id,))

    async def get_press_count(self, server_id):
        result = await self.one("SELECT set_name_count FROM ticket WHERE server_id = ?", (server_id,))
        return result if result is not None else 0

    async def increment_press_count(self, server_id):
        current_count = await self.get_press_count(server_id)
        new_count = current_count + 1
        await self.execute("UPDATE ticket SET set_name_count = ? WHERE server_id = ?", (new_count, server_id))

    async def set_panel_name(self, server_id, panel_name):
        await self.execute(
            "UPDATE ticket SET panel_name = ? WHERE server_id = ?",
            (panel_name, server_id)
        )

    async def get_panel_name(self, server_id):
        return await self.one("SELECT panel_name FROM ticket WHERE server_id = ?", (server_id,))


db = TicketDB()``` I have everything in the database but I don't know how to transfer the names into the option
lofty parcel
little cobalt
rare marlin
rare marlin
little cobalt
#

stay in one channel pls

rare marlin
sage tendon
#

stay here or in your ticket

#

/ post

lone hound
#

Does asyncio.sleep() pauses my code just liketime.sleep()?

lone hound
#

ok, thanks!

finite plover
#

how to send the message after async for?

lofty parcel
#

add it below?

finite plover
#

uh

#

youre right

lofty parcel
#

kek?

finite plover
lofty parcel
#

dunno what you were expecting lol

finite plover
#

idk

finite plover
steep cliff
#

Grammar's so bad I don't even know what you're asking for

finite plover
steep cliff
#

well then I don't know what to answer

finite plover
#

And i dont know how to describe lol

arctic plover
#

Almost all of my commands have a description added normally, but two of them do not have it, although it is written in the code. Why?

steep cliff
#

it's spelled description, but in the code you missed the r

arctic plover
#

oops

#

😅

#

thanks you

finite plover
edgy nest
#

if i were you i would just listen for audit log events instead of the actual delete event

#

or somehow pair them together

high pilot
#

never did anything to italicize that for fulfilling line

shell radish
rugged lodgeBOT
shell radish
#

you can use that on the username part

high pilot
#

oh my god

#

sillyme

#

thank you

shell radish
#

np

glad totem
#

can i restrict a bot to only work in a channel list?

versed root
#

actually have any way to reload cogs at all server?

when i use reload_extension, some server have not reload. btw i have wait a daynotlikethis

versed root
little cobalt
#

no

#

at your bot..

versed root
#

and other

#

i have update the command to repair bug

#

sorry my broken english

versed root
little cobalt
versed root
boreal sky
#

How do I get the slash command associated with a message?

#

I basically just want to see what command led to a message being created

rugged lodgeBOT
shell radish
#

@boreal sky ^

boreal sky
#

That's the first thing I had tried

#

I also tried Message.application but that wasn't it either it seems lol

shell radish
#

maybe you’re looking at the wrong message?

boreal sky
#

Uh... There's no other message to look at

shell radish
boreal sky
#

I do

#

Well, considering I use it in other places

shell radish
#

are you sure you the message you are checking for is the correct message

boreal sky
#

and the only message that ever gets sent is one spawned from a command

#

during testing, I mean

#

but even if it did error, I'd be able to see the message that succeeded if such a message existed

#

uh... never mind, I guess... I tried again and now it's working, I wonder what I did wrong beforehand...

#

very weird

shell radish
#

🪄

boreal sky
#

I hate when that happens lol

boreal sky
#

Uh... How is it possible for this to result in a timedelta of about -2 days?

discord.Object(message.interaction.id).created_at - message.created_at
#

Latest resulted in -1 day, 23:59:59.270000

sage tendon
#

do it the other way around

boreal sky
#

you'd have thought it'd be like negative some amount of time less than a second

#

very strange

sage tendon
#

it literally is

boreal sky
boreal sky
sage tendon
#

less than a second

boreal sky
#

that's -2 days

#

no?

sage tendon
#

no

#

it's 630ms

boreal sky
#

\🤔

#

say again

sage tendon
#

it's 630ms

#

It's because of how datetime works, simply said

boreal sky
#

I assume you mean 730

#
In [8]: timedelta(seconds=-0.730)
Out[8]: datetime.timedelta(days=-1, seconds=86399, microseconds=270000)

that is unnecessarily confusing

sage tendon
#

oh, yea

#

well it's not confusing at all

#

it's how datetime works

#

you can do the subtraction you initially had, and just display the milliseconds component from it

#

you are just printing it as a datetime which causes that

#

Though, your initial subtraction is still wrong because it has the values backwards, so, yea

#

the real difference on that one would be 270ms

boreal sky
#

like is days the only thing that can be negative?

#

like what you add -1 days to 86399 seconds and 270000 ms?

#

I think that's what it is

#

so weird

sage tendon
#

see it like day 1, day -1

boreal sky
sage tendon
#

datetime is the achiless heel of every dev

subtle moth
#

Can someone tell me the ratelimit on how many slash commands can be registered in an interval

sage tendon
#

how many can a bot have registered max?

little cobalt
shell radish
#

?tag cmd-limits

limber wagonBOT
#

You can have 100 commands, and each command can have up to 25 sub-command groups. Each sub-command group can have up to 25 sub-commands.

100 x 25 x 25 = 62.5k

Of course, "slash commands can have a maximum of 4000 characters for combined name, description, and value properties for each command and its subcommands and groups", so you're not likely to hit that 62.5k command limit

This can be doubled again with guild commands

sage tendon
#

damn okay

subtle moth
lone hound
#

Hi! To edit a guild channel's name i need to do:

channel = ctx.guild.get_channel(<channel id>)

await channel.edit(name='New channel name')

or something like that?

sage tendon
#

Are you doing that in a command?

#

and yes, that would work, but if you are doing it in a command, you dont need the channel = part because you can do that with an option

little cobalt
sage tendon
#

oh really?

little cobalt
#

ye

sage tendon
#

how much

little cobalt
#

The last time I checked it was 2 times every 10 Minutes

sage tendon
#

oh wow, thats shit

errant trout
#

discord got tired of people using them for live stats

daring grove
#

Ive put two commands on my bot, one of them appears and one of them doesnt and I cant see the problem - is discord taking a long to update it?

daring grove
sage tendon
#

restart your discord when making a new command

daring grove
quick knot
#

anyone else with this issue, all i see when i look it up is 4 yr old posts about the windows certif experation in 2020
aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to host discord.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1000)')]

quick knot
#

win 11

shell radish
#

I don't use windows, can't help you

quick knot
#

ubuntu?

quick knot
#

alright, go to dicord.com and donwload and install the certificate

#

for anyone else

edgy nest
sullen mauve
#

How to make a ban command?

little cobalt
sullen mauve
arctic plover
#

How can I disable all the buttons of this message knowing the message id?

errant trout
plucky palm
#

Looks like I forgot to update pycord to 2.5.0 and when I did every single bridge command was broken

It seems to be because now bridge commands use BridgeOption instead of usual Option, so @option decorator now just doesn't work

Is there a decorator for BridgeOption or do I need to make a decorator myself now?

#

Nvm, figured out it's not BridgeOption's fault but something else, though still not sure what it is

#

Throws Converting to "Option" failed for parameter "..."

errant trout
#

(when you import bridge, the default option objects redirect to their bridge variants)

plucky palm
# errant trout is there a full traceback
Ignoring exception in command random:
Traceback (most recent call last):
  File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/discord/ext/commands/converter.py", line 1154, in _actual_conversion
    return converter(argument)
           ^^^^^^^^^^^^^^^^^^^
TypeError: 'Option' object is not callable

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

Traceback (most recent call last):
  File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/discord/ext/bridge/bot.py", line 144, in invoke
    await ctx.command.invoke(ctx)
  File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/discord/ext/commands/core.py", line 951, in invoke
    await self.prepare(ctx)
  File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/discord/ext/commands/core.py", line 881, in prepare
    await self._parse_arguments(ctx)
  File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/discord/ext/commands/core.py", line 792, in _parse_arguments
    kwargs[name] = await self.transform(ctx, param)
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/discord/ext/bridge/core.py", line 107, in transform
    return await super().transform(ctx, param)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/discord/ext/commands/core.py", line 627, in transform
    return await run_converters(ctx, converter, argument, param)  # type: ignore
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#
File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/discord/ext/commands/converter.py", line 1255, in run_converters
    return await _actual_conversion(ctx, converter, argument, param)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/data/data/com.termux/files/usr/lib/python3.11/site-packages/discord/ext/commands/converter.py", line 1163, in _actual_conversion
    raise BadArgument(
discord.ext.commands.errors.BadArgument: Converting to "Option" failed for parameter "data".
errant trout
#

oh

errant trout
#

which is a major breaking change so it's rather concerning that this wasn't talked about more...

plucky palm
#

so do I need to make a workaround now?

errant trout
# plucky palm so do I need to make a workaround now?

sorry, this entire thing was very poorly planned out
if you want you can reimplement the old logic - at the bottom of discord/ext/bridge/core.py, add these two lines py discord.commands.options.Option = BridgeOption discord.Option = BridgeOption

raven moth
#

how do i add 2 buttons to an embed to function as like yes/no buttons? Sounds pretty simple to me but i cant seem to figure it out w the documentation rn

sage tendon
#

views

#

one view, to be precise

raven moth
#

that only confused me more 😅

sage tendon
#

look up views in the guides

raven moth
#

the only thing i can seem to find with that is how to create a button? I have got that figured out i just dont rlly know how to send it in the channel

sage tendon
#

send it with your ctx.respond

#

view=view

#

should all be in the guide

raven moth
#

i found it, got buttons appearing now, now i cant seem to figure out how to await the button click? I would have assumed this would use but.wait_for or ctx.wait for but i cant find anything regarding buttons or views on those docs?

sage tendon
#

the callback of the button contains the function called when pressing it

#

example of my yes/no view

raven moth
#

idk if im just stupid or i need sleep or both but i dont understand any docs rn

sage tendon
#

i literally sent you the code how you can do it

raven moth
#

im just very confused how i should implement this code into my codebase. ill be honest i dont have a ton of experience with classes but should i put this in a seperate file and import it? I already have the commands in a class inside a cog, can i just add this code as functions in my existing class?

#

i think i just need sleep mabye but idk

#

im just very confused rn

shell radish
#

you don't need to use classes if you don't want to

raven moth
#

i currently have this weird cluster of code but it works apart from listening for the buttonpress

@commands.slash_command(name='changeorigin',
                            description='Change your origin in the server')
    async def change_origin(self, ctx):
        embed = discord.Embed(title="Are you sure?", color=0xF66946)
        embed.add_field(name='Are you sure you want to do this? The action CANNOT be reversed however you can choose the same origin again', value='')
        yes_button = discord.ui.Button(label="Continue", style=discord.ButtonStyle.danger)
        no_button = discord.ui.Button(label="Cancel", style=discord.ButtonStyle.green)
        view = discord.ui.View()
        view.add_item(yes_button)
        view.add_item(no_button)
        message = await ctx.respond(embed=embed, view=view)
        interaction = await discord.Interaction()
        print(interaction)
        # Wait for the user to click one of the buttons
        if interaction == "Continue":
            await interaction.respond(content="You clicked 'Continue'!")
            # Perform your action here
        elif interaction == "Cancel":
            await interaction.respond(content="You clicked 'Cancel'!")
        else:
            print(F"Interaction output: {interaction}")
raven moth
#

i just dont rlly know where to look

sage tendon
#

the button callback gets called when a button is pressed

#

i have no idea how to "assign" it a callback without just subclassing the view tho
its just the easiest and cleanest imo

raven moth
#

idk its just what im used to with the old commands and bot.wait_for('message') but it doesnt seem to work the same way i guess

sage tendon
#

w..what

raven moth
#

thats me trying to figure it out but that code doesnt even make sense to me

sage tendon
#

just use mine

raven moth
#

i have this now

await ctx.respond(embed=embed, view=view)
        yes = await yes_button.callback(ctx.author)
        print(yes)
        no = await no_button.callback(ctx.author)
        print(no)
        print("callback was called")

but it just gets ran instantly, prints None twice

sage tendon
#

that makes zero sense

#

are you new to python by any chance

raven moth
#

no. I just dont understand this documentation. I would not call myself an expert and i am kinda feeling in the dark when it comes to awaiting stuff and threading. Also its just a side hobby for me and i dont spend much time on it

But rn i just dont even know what im supposed to do so im just trying whatever i guess

#

idk tempted to just give up and use text promts again

#

cause i understand those

sage tendon
#

just copy my code lol

#

its right there

lofty parcel
#

You don't understsnd Object Orientated Programming.

#

It's not the documentation.

raven moth
#

i guess? Idk

Almost all my knowledge in python is data handling/SQL

lofty parcel
#

You must learn OOP before handling pycord.

#

The whole library is OOP based.

#

I understand this isn't the field you're used to, but you must learn it before using pycord to avoid frustration and not understanding the docs.

sage tendon
#

(views as they are now are still not the most intuitive thing in the world tho let that be said)

raven moth
#

i am one to more wing it and just figure it out tbh. Like i understand that i dont fully grasp how OOP works but its not like this is my first time working with pycord. Most stuff i understand how it works but some stuff i just dont grasp i guess

lofty parcel
#

The repo is full of examples.

#

If you want that and makes it easier for you to understand.

rugged lodgeBOT
#

Here's the confirm example.

raven moth
#

okay so i copied the example code without changing anything but if i do this

view = Confirm()
        await ctx.respond(embed=embed, view=view)
        output = await view.wait()
        print(output)

i get false regardless of the input? Even though i copied the entire class just like in the example

sage tendon
#

what even is view.wait

#

why do you have stuff after ctx.respond

raven moth
sage tendon
#

hm

#

are you even pressing the button

raven moth
#

yes ofc, if i dont press the button the code doesnt even run

shell radish
raven moth
#

oh yeh

#

i see

#

i also see it in the example now, my bad

rugged lodgeBOT
#
Represents a UI view.

This object must be inherited to create a UI within Discord.

.. versionadded:: 2.0

Parameters
----------
*items: :class:`Item`
    The initial items attached to this view.
timeout: Optional[:class:`float`]
    Timeout in seconds from last interaction with the UI before no longer accepting input.
    If ``None`` then there is no timeout.

Attributes
----------
timeout: Optional[:class:`float`]
    Timeout from last interaction with the UI before no longer accepting input.
    If ``None`` then there is no timeout.
children: List[:class:`Item`]
    The list of children attached to this view.
disable_on_timeout: :class:`bool`
    Whether to disable the view when the timeout is reached. Defaults to ``False``.
message: Optional[:class:`.Message`]
    The message that this view is attached to.
    If ``None`` then the view has not been sent with a message.
parent: Optional[:class:`.Interaction`]
    The parent interaction which this view was sent from.
    If ``None`` then the view was not sent using :meth:`InteractionResponse.send_message`.```
stray pasture
#

is there a way to recover from this error (reconnect ?): ```discord.errors.DiscordServerError: 503 Service Unavailable (error code: 0): upstream connect error or disconnect/reset before headers. reset reason: connection termination

The current behavior the bot just crashes and closes
red mist
#

I'm guessing you're having a very unstable connection; you might wanna checkout resuming a session.

#

503 indicates a server is / was not able to handle a request or that it's temporary down.

glad totem
#

using a slash command can i set the arguments to be a list of an object? specifically it would be /command <int> <string> <string>, <int> <string> <string>, ...

round heart
#

Not really. Best you could do would be to make optional args for those extra ones, but the UX won’t be super great (especially if users forget them)

deft kestrel
#

@bot.slash_command(description="Set Reminder channel") async def setreminder(ctx, channel: discord.TextChannel, date, text):
how to put a server restriction to use this command? like: just server ID: 1111 can see this command

shell radish
#

add the guilds_id kwarg to the decorator:

@bot.slash_command(…, guilds_id=[1234567890])```
glad totem
deft kestrel
#

how to get user avatar in interaction?

glad totem
#

if i want my bot to handle slash commands do i need to enable any permissions besides sending messages?

stray pasture
#

But how can I recover from DiscordServerError: 503 ?

#

I can always run the bot in endless loop (if it crashes) I do bot.stop() and after bot.start(), but not sure this is the ideal solution

#

The error 503 is not happening often, maybe once each fiew weeks. But each time the bot goes down

glad totem
#

@shell radish hallo PB_wave

shell radish
glad totem
glad totem
#

groovy its working now

#

tyvm!

glad totem
# shell radish yup

btw the main goal of this bot is to handle some slash commands and then send messages, if possible slightly stylized ones in response. do i need to add any other perms?

shell radish
glad totem
shell radish
glad totem
#

ah it does not deal with letting the bot read messages? xd ok ty ill give that a try

shell radish
glad totem
#

lol thats fine

glad totem
#

do i have to reinvite the bot everytime i change the code? i got the first command to work, i added a second, stopped and started the bot but the second command isnt showing up

lofty parcel
#

No

glad totem
#

ah it just takes time, weird that i can run a command and it cna reconigze its changed but doesnt update with the change right away xd

glad totem
#

can i restrict a command to a category rather than just one channel? i tried copying the id of the category and putting it in guild_ids property but i got an error that discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access

lofty parcel
#

You either implement an internal check or edit the command permissions on the integration settings of your server

glad totem
#

no idea how id do either of those. the issue is that we use a ticket system so channels would be created as the bot is running

glad totem
#

i see that theres a discord.CategoryChannel that seems like it might be able to help but im not sure how to utilze/call on it

lofty parcel
crystal patrol
#

hey guys how can i use if isinstance when arguments is missing or arguments not included?

lofty parcel
crystal patrol
lofty parcel
crystal patrol
lofty parcel
crystal patrol
# lofty parcel Showing your code would be helpful

Aight

@bot.command()
async def webscrapp(ctx, website):
    """Scrapping Usage : ht!webscrapp [url link]"""
    if isinstance(website, commands.MissingRequiredArgument):
        await ctx.reply("Usage ht!webscrapp [url link]")

    await ctx.send("Processing")
    req = requests.get(website)
    with open("scrapped.txt", "w") as files:
        files.write(req.text)
    await ctx.send(file=discord.File("scrapped.txt"))
lofty parcel
#

commands.MissingRequiredArgument is an error

#

It's raised when an arg is missing

#

You're supposed to create an on_command_error listener and catch it and reply accordingly there

crystal patrol
#

on_command_error is callback?

lofty parcel
#

No, an event

#

You listen to that event

#

Assuming you'd do this in a cog:


@commands.Cog.listener()
async def on_command_error(self, ctx, error):
    if isinstance(error, commands.MissingRequiredArgument):
    await ctx.send("You are missing a required argument")
crystal patrol
#

But thanks for the example

lofty parcel
#

I think you can?

#

Try

@webscrapp.error
async def webscrapp_error(self, ctx, error):
    if isinstance(...):
          ....
#

Below your command.

crystal patrol
#

Im confusing

lofty parcel
crystal patrol
red mist
deft hull
#

How do you guys host your bots?

little cobalt
deft hull
#

damn

#

What if I don't have one

round heart
#

.tag hosting

sly karmaBOT
#

Tag not found.

Did you mean...
closing

deft hull
round heart
deft hull
#

How do you add a slash command group in a cog?

#

I could just import bot from the main file but I don't think that'll be very practical

lofty parcel
rugged lodgeBOT
#

Here's the slash cog groups example.

little cobalt
#

@deft hull

deft hull
#

thank you 👍

grizzled loom
#

never mind, saw it by clicking on it

#

wasnt aware an example existed for this case

chilly crow
#

Hey, I'm trying since like the last hour to figure out how to make a url button work, but also with a view class I can't get it to work. Im very new to python still

@discord.slash_command(name='userinfo', description='Provides information about a Discord Member')
    async def get_user_info_cmd(self, ctx, member: discord.Option(discord.Member) = None):
        target = member if member else ctx.author
        view = discord.ui.View
        btn = discord.ui.Button(label='View', style=discord.ButtonStyle.link, url="https://cdn.discordapp.com")
        view.add_item(self, item=btn)
        await ctx.respond(embed=get_user_info_embed(target), view=view, ephemeral=True)```

**Edit: got it!**
chilly crow
#

Why is embed.set_image(url=member.banner.url) not working?

little cobalt
#

Read the error ;3

chilly crow
#

what that mean?

#

Idk why it says my banner is none

#

it's clearly not

little cobalt
#

You have to fetch the user to get the Banner

edgy nest
little cobalt
#

^

chilly crow
edgy nest
chilly crow
#

I'm trying my best to figure it out but I'm always getting some error like this

#

Please give me a code example on how to fetch a user from their id

#

user = await discord.Client.get_or_fetch_user(self.bot, member.id)
I tested so many things

errant trout
chilly crow
#

but what do I need to put there

#

what does it want from me

errant trout
#

you've set a bot variable in your code, right...

chilly crow
#

yes

errant trout
#

then just use that

chilly crow
#

it's in a different file tho

errant trout
#

this is a cog, right?

chilly crow
#

correct

#

so main.bot.get... works?

errant trout
#

and what's the first thing you set in your cog's __init__

chilly crow
#

self.bot = bot

errant trout
#

right

#

so now access that from the command

chilly crow
errant trout
#

then pass it through

#

if it's outside, you create a new parameter to send it in

chilly crow
#

Or no wait, I actually added it to the class as async function

#

async def get_user_info_embed(self, member: discord.Member):

#

I tried to pass it through but it always just gives me none

#
import discord
from discord.ext import commands
import views.lookupUser


class UserInfo(commands.Cog):

    # this is a special method that is called when the cog is loaded
    def __init__(self, bot):
        self.bot = bot

    @discord.slash_command(name='userinfo', description='Provides information about a Discord Member')
    async def get_user_info_cmd(self, ctx, member: discord.Option(discord.Member) = None):
        target = member if member else ctx.author
        view = views.lookupUser.lookupUserBTN()
        view.add_item(await views.lookupUser.lookupUserBTN().button(url=f'https://discordlookup.com/user/{target.id}'))
        await ctx.respond(embed=get_user_info_embed(bots=self.bot, member=target), view=view, ephemeral=True)


def get_user_info_embed(bots: discord.Bot, member: discord.Member):
    embed = discord.Embed(
        title='User Information:',
        color=discord.Color.from_rgb(100, 255, 100)
    )


    embed.set_thumbnail(url=member.avatar.url)

    user = bots.get_user(member.id)
    print(user.banner)
    return embed


def setup(bot):
    bot.add_cog(UserInfo(bot))```
errant trout
chilly crow
#

in the guild

errant trout
#

then don't use get_member

#

you already have the member object

chilly crow
#

I want a userinfo command that sends me info about my member on my server

errant trout
#

basically just remove the user = ... line (unless you really need their banner for some reason, then you'd have to fetch)

chilly crow
#

I want their banner ye

#

I want to use it as image of the embed

errant trout
#

then you have to change it to an async function and use await bot.fetch_user

chilly crow
#

It worksss

#

thank youu

deft kestrel
#

can someone please help

#

how to add fields to a paginators embed

#

send an example code or anything

sage tendon
#

the repo is full of examples

deft kestrel
sage tendon
#

just.. add them to the embed like normal lol

lapis dock
#

Embed takes a fields kwarg.

deft kestrel
sage tendon
#

docs, as always

deft kestrel
#

ye ty 😭

deft kestrel
#

how to create that?

little cobalt
serene goblet
#

Am I able to nest groups like this?

parentgroup = bot.create_group("parent", "parent group commands.")

childgroup = parentgroup.create_group("child", "child group commands.")
sage tendon
#

you can definitely have 2 subcommands yes, but im not sure if it works like that. just try it

minor crescent
#

what's the best way for handling config values across cogs? i can't figure out how to do it without dealing with desynced data

sage tendon
#

config file?
or a database if you mean that kind of config

minor crescent
sage tendon
#

if its per-server configs, database

minor crescent
sage tendon
#

then just use a config file or hardcode it lol

minor crescent
sage tendon
#

what are you even doing that needs you to change the config file lol

minor crescent
#

remaking it*

#

my original version is all in 1 main.py

#

im converting it to use cogs

#

so stuff like discounts, permissions, etc

sage tendon
#

well if you need to change it more than never, use a db

minor crescent
#

kk

#

thanks

fickle salmon
minor crescent
#

literally just a config table?

fickle salmon
minor crescent
#

lemme get what it is rn

fickle salmon
#

guild id, variable name, variable value? idk

minor crescent
# fickle salmon guild id, variable name, variable value? idk
[SETUP]
depo_world = BANNED
depo_bot = 05u1oyzyk9
pay_as_you_go_price = 30
purchase_count = 482
total_profit = 1283217
rescan_cooldown = 60
admin_checker_channel = 1206053236428247070
admin_checker_price = 0
add_your_own_world_channel = 1206105043426615367

literally just stuff like this

#

a lot of ints, some strings

#

i use config parser and .ini normally

#

but now im working with multiple cogs

fickle salmon
#

Why not keep it an ini

minor crescent
#

if i save the config in one cog it wont update on the other ones unless i reload

#

the only idea i've had is creating a configparser object in a shared.py file and importing it across all cogs

fickle salmon
#

When you read a config value, just re-read the file?

minor crescent
fickle salmon
#

How is this not efficient?

#

I create a db object and add it to my bot bot.db = DB() that I then use in any cog to query the DB, this is very similar

minor crescent
#

thanks

red mist
sage tendon
#

You know
If you somehow manage to desync your data with a config file
Just make it a class that sets its fields upon being made, and save the object as a bot variable

atomic fern
#

i have message id from db, but if i using bot.get_message() after the msg age is more than 1week, it's always return None, why?

lofty hedge
#

I think you can only get a message that’s x amount of days old correct me if I’m wrong

#

Because bots can’t delete messages that’s older than x amount of days

little cobalt
#

and do you fetch the message?

deft hull
#

I'm trying to host an application which uses a database by fetching data from the google sheets api. Thing is, I don't know how

errant trout
atomic fern
#

skull_cry ty I'll try use fetch

shell radish
rotund quarry
#

How can i make this a int

async def get(ctx, page: description="The page with the quest that you want to see.", min_value=1, max_value=6, default=1):

sage tendon
#

make what an int

lofty parcel
#

Make what an int

sage tendon
#

slow

lofty parcel
#

Shut

sage tendon
#

im just a dragon

rotund quarry
#

I menat i want to make a slash command that you can put a nuber

sage tendon
#

use the @option decorator

#

thats how i do it

#

discord.commands.option i believe, 1s

rotund quarry
#

I can't do it directly on async def?

sage tendon
#

you can but its ugly af in my personal opinion

rotund quarry
#

ok

#

thank you

sage tendon
#

example

#

from discord import option

lofty parcel
sage tendon
#

ssh

#

first let them convert it to use the decorator

lofty parcel
#

No shut

#

Die decorators

sage tendon
#

its so clean wdym

lofty parcel
#

discord.Option supremacy.

sage tendon
#

inferior

lofty parcel
#

says the dragon

sage tendon
#

exactly, the superior species

lofty parcel
#

you're fictional

rotund quarry
#

Classic

@bot.slash_command(name="test", description="test")
@option(name: "page", int, description="The page with the quest that you want to see.", min_value=1, max_value=6, default=1)
async def get(ctx, page: int):
@option(name: "page", int, description="The page with the quest that you want to see.", min_value=1, max_value=6, default=1)
                ^
SyntaxError: invalid syntax
sage tendon
#

that is.. not how you do python

#

just do it the way i did

#

pass the name and type as positional argument

rotund quarry
#

ok

sage tendon
#

did it work?

lapis dock
#

But type has to go first.

sage tendon
#

it doesnt have to

lapis dock
#

Kwargs can't be before positional args.

sage tendon
#

yea, but if they just followed the way i did it, they wouldnt have that issue

steep cliff
sage tendon
#

why?

steep cliff
#

Ugly af

sage tendon
#

literally so clean

sage tendon
steep cliff
#

Immo the latest version they added is the best

#

Crowded mess up top and doesn’t seem pythonic

sage tendon
#

the multi-line function definition is what i find absolutely disgusting and wrong looking

steep cliff
#

Typing.anotated just seems more general and closer to other libraries/code

sage tendon
#

wtf is that

steep cliff
#

I get that decorators do the best at separating the options visually, but they also make really library specific and counter intuitive

steep cliff
sage tendon
#

wtf does that do

#

that looks so garbage

steep cliff
#

It looks weird but is properly type hinted

#

Currently use option kwargs but this is better imo

chilly crow
#

So I need help with something, I have a main file where my bot is loaded. Now I have another script where I want to put my events inside to make the code more readable. Now how do I access this bot instance from my main file in my event file?

lapis dock
#

@chilly crow

chilly crow
deft hull
#

Quick question

#

can you set a command desciption like this

#
@decorator
async def something(ctx):
    '''
    Description
    '''
    pass
shell radish
#

The pycord syntax is different

deft hull
#

oh

#

thanks

shell radish
errant trout
#

(just note that user and message commands don't have descriptions, only prefix and slash do)

tranquil steeple
#

channel.overwrites_for(ctx.guild.default_role)
why does this return None

little cobalt
tranquil steeple
fresh sierra
#

Hello, i didnt really understand something about slash command, i read the limit is 100 slash command and sub command but with the tag cmd-rate im now a little lost.
If i create a /command math with 25 sub command in it and i does 5 others groups like this i will have a total of 125 commands and subcommands. Does it will work ?

#

or the limit is still 100 so i cant have a total of 125 sub commands

shell radish
#

you can have 100 top-level commands

#

this is one top-level command, "afk"

fresh sierra
shell radish
fresh sierra
#

and not 1/100 with 7/25 for the subcommands

#

oo ok

shell radish
#

you have mod and set

fresh sierra
#

because mode is like 1

#

so mode is a subcommand of a subcommand ?

shell radish
#

something like that. There's probably an official term.

fresh sierra
#

ok thanks you, im planning to put all my prefix command as slash command

#

but with more than 300 commands, i will need to do better thing

#

i was planning to do for each category the name like /moderation ban @user, /action agree, /antiraid antispam etc etc, if you have some advice or else tell me

shell radish
#

yes, that's generally how its done

fresh sierra
#

and also about /slash commands, what does it mean no rate limit ?

#

like it doesnt rate for the sending of the command and the invocation ?

shell radish
#

for text-based commands, there are rate-limits because bots can't send messages that frequently

fresh sierra
#

ok its about that

#

i have a lot of thing to learn about slash commands...

#

is there a way with bridge command to something like this :
/moderation ban
+ban

#

for when i use the slash i have the moderation has group but with the prefix i dont need to speficy the group

shell radish
#

what if you just made a regular slash command and a regular text-based command

fresh sierra
#

it also work but 2 times more works

#

cos when i will change a / i will have to change the text too

#

but if there are nothing to do it i will make both

shell radish
#

I'm not familiar with bridge