#Basic Pycord Help (Quick Questions Only)

1 messages · Page 58 of 1

proud mason
#

Yea

#

.tias

winter condorBOT
proud mason
#

I think you can pass an alias kwarg that will the picked up by the prefix version

#

?

#

.idw

winter condorBOT
#

Saying it doesn't work or asking what's wrong with this code is not helpful for yourself or others.
Describe what you expect and/or tried (with your code), and what isn't going right.
Please provide any errors you get for optimal assistance.

limber urchin
#

If you're going to ask a question in this channel, at the very least ask a question. Just posting random JSON data is absolutely useless.

feral lintel
# proud mason Yea

Thank you for the feedback, so quickly.
So if I have an issue with it, then I have to create a new post ..? 👼

young bone
#

If you want

limber urchin
#

If you think the issue needs an extensive conversation. If it's just a quick question, making a post isn't necessary.

tough grove
#

hello, how could i do that ?

@option(
    name="minimum"
    name_localizations={"fr":"minimum"},
    description="The minimum number",
    description_localizations={"fr": "Le nombre minimal"},
    min_value=0
)
@option(
    name="maximum"
    name_localizations={"fr":"maximum"},
    description="The maximum number",
    description_localizations={"fr": "Le nombre maximal"},
    min_value=#value of minimum + 1
)```
tough grove
#

yup

young bone
#

discord.option or what do you mean?

tough grove
#

i want to prevent user to give a maximum value lower than minimum value

young bone
tough grove
#

to make bingo between 0 and like 500 or 400 and 600 or anything

distant shale
#

Attribute error: FFmpegPCMAudio object has no attribute '_process'

No idea ☠️

@bot.slash_command()
async def play(ctx, url: str):
    if ctx.author.voice is None:
        await ctx.respond("You're not in a voice channel!")
        return

    channel = ctx.author.voice.channel
    voice_client = get(bot.voice_clients, guild=ctx.guild)

    if voice_client is None:
        await channel.connect()
        voice_client = get(bot.voice_clients, guild=ctx.guild)

    if voice_client.is_playing():
        voice_client.stop()

    source = FFmpegPCMAudio(url)
    voice_client.play(source)

blissful hazel
#

And from what is the FFmpegPCMaudio?

drifting sleet
#

I tried to make a SlashCommandGroup with parent set to another group, but it's commands won't register (it's been over 24h), new commands added to the parent are added immediately. My groups: py ms = SlashCommandGroup("ms", "ETL MasterServer tools") favorites = SlashCommandGroup( "favorites", "Show, add or remove your server favorites.", parent=ms) Example command: ```py
@favorites.command()
async def show(self, ctx) -> None:
"""Show your server favorites."""
await ctx.respond("Here's your favorites")

distant shale
proud mason
proud mason
distant shale
proud mason
#

i think you can download it using apt

dry fulcrum
#

!role_select

#

?tag role_select

obtuse juncoBOT
#

dynoError No tag role_select found.

dry fulcrum
#

i have a quick question, is there a way to limit which roles are selectable in a role_select dropdown?

#

I don't see anything regarding that in the example

versed fern
#
@message_group.command(name="edit", description="Edits the message specified!")
    async def message_edit(self, ctx: discord.commands.context.ApplicationContext,
                           msg: discord.Option(discord.Message, "Please enter the message link or ID!", required=True)
                           ):
        try:
            if msg.author != self.client.user:
                await ctx.respond("Can't edit this message!", ephemeral=True)
                logger.error(f"Message not sent by bot! (Message ID: {msg.id})")
                return
        except discord.ext.commands.errors.MessageNotFound:
            await ctx.respond("Can't find this message!", ephemeral=True)
            logger.error(f"Message not found! (Message ID: {msg}")
            return

Why does it still raise discord.ext.commands.errors.MessageNotFound: Message "asdsd" not found. instead of logging the error and responding to the user?

dry fulcrum
versed fern
proud mason
#

in that case, you need an error handler

#

that gist is for dpy but it works for pycord too

versed fern
#
Ignoring exception in command message edit:
Traceback (most recent call last):
  File "C:\Users\User\Documents\Programming\AIM\venv\Lib\site-packages\discord\bot.py", line 1114, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "C:\Users\User\Documents\Programming\AIM\venv\Lib\site-packages\discord\commands\core.py", line 375, in invoke
    await injected(ctx)
  File "C:\Users\User\Documents\Programming\AIM\venv\Lib\site-packages\discord\commands\core.py", line 124, in wrapped
    ret = await coro(arg)
          ^^^^^^^^^^^^^^^
  File "C:\Users\User\Documents\Programming\AIM\venv\Lib\site-packages\discord\commands\core.py", line 1312, in _invoke
    await command.invoke(ctx)
  File "C:\Users\User\Documents\Programming\AIM\venv\Lib\site-packages\discord\commands\core.py", line 375, in invoke
    await injected(ctx)
  File "C:\Users\User\Documents\Programming\AIM\venv\Lib\site-packages\discord\commands\core.py", line 124, in wrapped
    ret = await coro(arg)
          ^^^^^^^^^^^^^^^
  File "C:\Users\User\Documents\Programming\AIM\venv\Lib\site-packages\discord\commands\core.py", line 950, in _invoke
    arg = await converter().convert(ctx, arg)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\User\Documents\Programming\AIM\venv\Lib\site-packages\discord\ext\commands\converter.py", line 409, in convert
    guild_id, message_id, channel_id = PartialMessageConverter._get_id_matches(
                                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\User\Documents\Programming\AIM\venv\Lib\site-packages\discord\ext\commands\converter.py", line 356, in _get_id_matches
    raise MessageNotFound(argument)
discord.ext.commands.errors.MessageNotFound: Message "123" not found.
proud mason
#

yep thats exactly whats happening. Library is trying to use the converter and find it for you

#

intended behaviour

versed fern
#

I had it without the try exept statement first, but it raised the Exception, added it and it's still the same

#

So ig there's no actual way of catching it?

proud mason
#

you have to use the error decorator

#

or a command error event listener

versed fern
#

oops, didn't even look at it, I'll do this now, thank you

#

regarding the discord.Message, would you recommend changing it to an int? I had it as discord.Message cause it made it easy to access things like msg.author

proud mason
#

if you accept an int, you can check if msg is in cache. it not you can fetch it. that way, you are certain to not have cache issues

versed fern
#

awesome (Well explained btw 👍 )

proud mason
#

np 🙃

limber urchin
#

Pass it to your buttons init function and assign it as an attribute to the class

mild sigil
#
        super().__init__(timeout=10)
        self.ctx = ctx```
#

minus the timeout

#

though probably a good idea unless you want it forever active

limber urchin
#

Timeout defaults to 180 seconds. You need to explicitly set it to None to remove the timeout

mild sigil
#

thanks, good to know

limber urchin
#

And how does your code look?

#

That is not how it works

#

You assigned ctx to self.ctx

proud mason
#

1st parameter of callback is button, not ctx

#

you can get the person who clicked the button from interaction.user

limber urchin
#

When you assign something to self. You can access that attribute from anywhere within the class instance.

#

Through self.<attribute>. But yeah, like Om is saying you don't even need ctx in your case.

proud mason
limber urchin
#

^ you do need to check if the author of the command is the interaction.user as well

loud sail
#

how can I have it reset directly after a successful interaction? It's not very advantageous with a ticket system (as it is in the picture).

proud mason
errant craneBOT
#

Here's the confirm example.

loud sail
proud mason
#

you can create fresh view and edit the message with that if you want

#

Although there can be a better approach which im not aware of

loud sail
#

How do you mean?

proud mason
limber urchin
#

You would have to stop the interaction and return a message saying something like "You are not allowed to use this button" or something.

#

aka returning the callback before anything happens

proud mason
#

you can also send the view in an ephemeral message so you can avoid this altogether

limber urchin
#

Again, the first parameter of the callback is the button

#

.rtfm Button

proud mason
#

first parameter button, second is interaction (ignoring self)

#

uh

#

what did you do?

#

did you do view.add_item(ctx)

limber urchin
#

Discord can't take ints that large

#

it needs to be a string, parsed to an int in Python

versed fern
#

okay :(

limber urchin
#

The error tells you exactly what's wrong

versed fern
marble obsidian
#

uid = int((message.channel.history(limit=2, oldest_first=True)).flatten()[1].content) this is giving me an error: coroutine object is not subscriptable. i tried awaiting it but it just gives me another error

full basin
#

.rtfm channel.history

full basin
marble obsidian
full basin
marble obsidian
full basin
#

Literally scroll down 3 centimeters lmao

marble obsidian
marble obsidian
limber urchin
#

The example tells you exactly how to get the history as a list

marble obsidian
#

I cant find it

limber urchin
#

Did you click the link?

marble obsidian
limber urchin
#

Does that help?

#

How could you not see that?

marble obsidian
marble obsidian
limber urchin
#

Ah, it just magically disappeared from the website thinkCat

limber urchin
#

Oh your browser just doesn't scroll for you

proud mason
silver moat
marble obsidian
#

idk why i use it tbh

silver moat
#

opera on windows 11 works fine with docs

marble obsidian
silver moat
#

Also works on windows 8

#

maybe your computer’s just being bad

marble obsidian
#

anyway thank yall it worked

versed fern
limber urchin
#

Why do you need the bot instance if you're in a cog?

errant craneBOT
#

Here's the slash cog groups example.

proud mason
#

@fervent cradle ^

#

check that out

proud mason
#

no

light sky
#

i get the ValueError: View is not persistent. Items need to have a custom_id set and View must have no timeout error even when there is no timeout and every item has a custom id, how do i fix this?

full basin
#

Code

young bone
#

do you have intents?

limber urchin
#

You're trying to register commands in a guild that your bot isn't it

long moat
#

I'm trying to get the id for my slash command but i cant see to find out how, any pointers?

fervent cradle
long moat
fervent cradle
#

Or you can just type in the command and right click on the little info box

long moat
#

surely theres got to be a way the bot can get its own slash command ids

fervent cradle
#

Right click that

#

Oh you mean have the bot get it

long moat
#

yeh lol

silver moat
#

create a new post, thanks

long moat
silver moat
#

.rtfm applicationcontext.command

winter condorBOT
#

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

silver moat
#

.rtfm applicationcontext.

silver moat
#

there should be a command attribute

winter condorBOT
#

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

silver moat
#

alas, some attributes are missing like always

long moat
#

_> F

silver moat
fallen cove
#

how do you disable the buttons in a view from a modal callback (one of the buttons sends the modal)?

silver moat
#
# pseudocode

send_modal()
button.disable = True
edit_message(view=self)
fallen cove
silver moat
#

then await modal.wait()

fallen cove
#

thank you

fallen cove
silver moat
#

it will return True if timed-out and False if submitted

fallen cove
cyan quail
fallen cove
# silver moat it will return True if timed-out and False if submitted
class SubmitModal(discord.ui.Modal):
    def __init__(self, title="Submition Confirmation"):
        super().__init__(
            discord.ui.InputText(
                label="Start Date",
                style=discord.InputTextStyle.singleline,
            ),
            discord.ui.InputText(
                label="End Date",
                style=discord.InputTextStyle.singleline,
            ),
            discord.ui.InputText(
                label="Reason",
                style=discord.InputTextStyle.long,
        ),
        title=title
    )
        
    async def callback(self, interaction: discord.Interaction):
        db = sqlite3.connect('Ares.sqlite')

        cursor = db.cursor()
        
        
        cursor.execute(f"INSERT INTO Medbay(ChannelID, MemberID, Type, Status, StartDate, EndDate, Reason) VALUES({interaction.channel.id}, {interaction.user.id}, '{interaction.channel.category}', 'pending', '{self.children[0].value}', '{self.children[1].value}', '{self.children[2].value}')")
        db.commit()
        cursor.close()
        db.close()



class MedbaySubmitButtons(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)
        
    ```
#
@discord.ui.button(label="Submit", style=discord.ButtonStyle.blurple, custom_id="MBV2Submit")
    async def submit(self, button: discord.ui.Button, interaction: discord.Interaction):
        db = sqlite3.connect('Ares.sqlite')

        cursor = db.cursor()
        cursor.execute(f"SELECT MemberID FROM Medbay WHERE MemberID = {interaction.user.id} AND Ongoing = {1}")
        result = cursor.fetchone()
        if result is not None:
            await interaction.response.send_message("You already have a medbay request open. You can only have 1 ticket open at once.\n*If this is a mistake contact the dev team imediatly*", ephemeral=True)
            return

        user = interaction.user
        ## await interaction.channel.send(view=medbayconfirmButtonsView())
        #await interaction.response.send_message(f"Processing...", delete_after=0.01)
        submit=discord.Embed(
            title="**Medbay Submission**",
            description=f"{user.mention}\nYour medbay request has been submitted and is now awaiting approval.",
        )
        await user.send(embed=submit)
        embed2=discord.Embed(
            title="Ticket Controls",
            description="Please use the buttons below to approve or deny the request."
            )
        #await interaction.channel.send(embed=embed2, view=MedbayAprovalButtons())

        modal=SubmitModal(title="Submition Confirmation")
        await interaction.response.send_modal(modal)
        await modal.wait()
        if await modal.wait() == False:
            for child in self.children: # loop through all the children of the view
                child.disabled = True
            button.label = "Submitted"
            button.style = discord.ButtonStyle.green
            # edit the message to reflect the changes
            await interaction.response.edit_message(view=self)
            await interaction.channel.send(embed=embed2, view=MedbayAprovalButtons())
#

get no error bur buttons aren't edited

cyan quail
#

you're waiting twice

#

you should do x = await modal.wait() and then check that

#

that code will fail anyway because 1) you don't respond with the callback interaction and 2) you're responding to an interaction twice

#

is there any reason that last if block can't be in the modal callback?

fallen cove
#

tried to do it in the modal call back and couldnt figure it out at all

cyan quail
#

i'd say add a new attribute to your modal __init__ to pass the buttons through

#

then you can access them in the callback easily

#

though wait isn't necessarily bad, but sometimes it overcomplicates things when dealing with timeouts

fallen cove
limber urchin
#

You probably need to learn more about OOP concepts then

fallen cove
cyan quail
# fallen cove i tried that and in all honesty i have no clue how that works i spent most of th...

well for example, this is your own code py class SubmitModal(discord.ui.Modal): def __init__(self, title="Submition Confirmation"): super().__init__(...) you've already added your own title attribute, which you pass into super as it's necessary for the Modal class. However, arguments you add here don't have to be super'd; they can simply exist as an attribute of your custom class```py
class SubmitModal(discord.ui.Modal):
def init(self, title="Submition Confirmation", bot=None):
super().init(...)
self.bot = bot
...

async def some_function(self):
    return self.bot.name
#

if you've ever made a cog, you've probably read self.bot = bot dozens, if not hundreds of times; all you're doing is picking and choosing attributes

fallen cove
cyan quail
#

well it refers to the same object; you aren't creating a new btn, self.btn would be equal to the original btn you passed in

fallen cove
cyan quail
#

So let's go with your example ```py
class SubmitModal(discord.ui.Modal):
def init(self, title="Submition Confirmation", btn=None):
super().init(...)
self.btn = btn

async def callback(self, interaction):
    ...
    self.btn.disabled = True
    await interaction.response.edit_message(...)

...

button = discord.ui.Button(label="...")
modal = SubmitModal(btn=button)
```this code is bs but just for the sake of demonstration; we've defined a variable button which is a new Button. When we call SubmitModal, we pass button in which is assigned to self.btn inside the Modal. You can consider self.btn is button, so doing anything to self.btn is the same as doing the same action on button.

But in the context of editing a View, this is a bad approach and may be where you're getting confused.

#

A better method would be to pass the entire view as a variable and work on view.children, like you were already doing after your wait ```py
class SubmitModal(discord.ui.Modal):
def init(self, view, title="Submition Confirmation"): # view is required
super().init(...)
self.view = view

async def callback(self, interaction):
    for button in self.view.children:
        ...  # do stuff with the buttons, or use view.disable_all_children()
    self.view.children[0].label = "..."
    await interaction.response.edit_message(...)```
fallen cove
#

thank you for the help, sorry it took so long

cyan quail
fallen cove
storm geode
#

My python cannot find pycord

#

anyone know how to fix this?

full basin
#

And what's your python version

storm geode
#

3.9.2 python version

#

and wdym show pip?

#

PIP 20.3.4

limber urchin
#

Show your pip list

storm geode
#

ooh

limber urchin
#

The package name is py-cord, not pycord

storm geode
#

ohhh shit

#

didnt catch that

rose vapor
#

so just learned about the slash command reset limit (200 creations per day per guild)

what is the proper way to test if not simply restarting bot that happens to have a multiple slash commands per startup?

storm geode
#

ok it works thanks @limber urchin :D

limber urchin
cyan quail
#

oops

storm geode
#

Bit late lol

cyan quail
#

channel didn't scroll apensive

rose vapor
# limber urchin Reload your cogs instead of restarting the entire bot

hi, thanks, back from a bit of reading and moving things around

so moved my @ bot.slash_commands into a commands.Cog class now

but then i'm like what's the correct way to reload cog? i see this load and reload_extension but how to trigger reload extension correctly?

I'm guessing load extension is same as restarting bot and recreating the commands

covert kayak
#

Hi, I'm wondering if I set view=None, will the on_timeout function still run, and if so, how to stop the on_timeout function from running for a particular button.

novel jay
#

please, don't, use, global

covert kayak
#

why

novel jay
#

its bad practise

covert kayak
limber urchin
#

you don't need globals for that, at all

novel jay
#

they're hell to keep track of

#

and like.... use class self values not global

covert kayak
#

I'm accessing variables from another function

novel jay
#

then pass that in as a function param

#

not too hard

#

are you using those variables in the same class as that button callback?

limber urchin
#

it's basic OOP, if you don't know that you shouldn't be making a bot

covert kayak
#

Does it work tho? I'm making a plus and minus button. If the value a is greater than 0 than it will keep sending more buttons. How do I keep track of value a using function param

novel jay
#

make sure you don't hit the 25 button limit

limber urchin
#

It might "work" but it's a terrible solution and not sustainable

full basin
#

Assign it as a class attribute?

novel jay
#

global makes things really... really crap to maintain

#

its great at first but then things go to hell

#

don't "lol" me, its good advice

covert kayak
#

i saw the crying face and click cry

#

didn't know it was lol

covert kayak
novel jay
#

there's no harm trying to see if it'll work, just spin up a test bot and test away

#

although from what I've seen with my own bots, no it won't fire if that view is not longer existent, but always double check

covert kayak
novel jay
#

yes, there is a limit of 25 buttons

#

set by discord, pycord can't do anything about it

#

5 buttons per row and 5 rows
5x5 = 25

covert kayak
#

I thought you were talking about the number of time button can be sent

novel jay
#

no

covert kayak
#

thank you

fervent cradle
#

hey so I want to import the "code" parameter that's in a different file, but I'm not sure how to

full basin
fervent cradle
#

well is there anyway I can define the code parameter from that function?

proud mason
#

.botvar

winter condorBOT
#

Need to keep track of a variable between functions? No problem!

⚠️ Careful what you name it though, else you might overwrite something ⚠️

Just add it to your commands.Bot or discord.Client instance like so:

bot = commands.Bot(...)
bot.my_variable = 0

async def foo():
    bot.my_variable += 1

# In a cog
@commands.command()
async def counter(self,ctx):
    await ctx.send("Current Counter is at {}".format(ctx.bot.my_variable))

This also allows you to access this from other cogs/extensions/functions. Anywhere you have access to the bot instance

proud mason
#

Is this what you are looking for?

full basin
#

You pass parameters when calling the function

#

You're calling the function

#

code is just the parameter name on the Code function

fervent cradle
#

but I have to enter the "code" parameter when calling the function, I get a "missing 1 required positional argument: 'code'" error if I don't

#

and if I do, it's just undefined, so idk what to do

full basin
#

This is basic python.

#

.lp

winter condorBOT
#
full basin
#

If you don't know how functions work, you shouldn't even be coding a Discord bot.

rare ice
#

You should be learning basic python before learning Pycord.

novel jay
#

i need to tell my past self that sip

#

big mistake

rare ice
#

now we can refer to the “most recent pin” when someone doesn’t know basic python oldsmiley

novel jay
#

its kinda hard to reach pins in a forum

#

but yes

rare ice
#

For this thread specifically

novel jay
#

yeah

fervent cradle
#

how do i fix this

soft girder
#

Is it possible for a command to make a certain work time. That is, at 12:00 it turns on, and at 18:00 it turns off?

stuck canopy
#

Anyways, I have a question. is it possible to get code from a message? Like if a user sends a code block with ```, is there any way to just grab that from like context.

proud mason
#

Try getting it using regex

stuck canopy
#

Ah alrighty.

proud mason
#

Also guilds ids should a be list of ints

#

Check all your commands

#

It should be guild_ids=[123]
Not guild_ids=123

stuck canopy
#

Are these things on the side just called "App commands"? Can someone point me to some documentation on how I can make one?

proud mason
#

Specifically message commands and user commands

#

I believe the guide has something on it

#

.guide

winter condorBOT
proud mason
#

.rtfm user_command

proud mason
#

.rtfm message_command

stuck canopy
proud mason
#

Check the docs too

proud mason
stuck canopy
#

ah alrighty.

proud mason
#

You can reply with "wrong message selected" or smth if the message.author is not bot.user

stuck canopy
#

Ah all good.

#

Gotcha.

#

Also I'm curious, do slash commands not work on replied messages?

#

I noticed that I have the reply window open and there are no slash commands.

#

This is the case on any server.

#

I wanted to have the user be able to reply to a message with the slash command to like give them a thanks.

proud mason
stuck canopy
#

All good. Just making sure that was the case.

proud mason
stuck canopy
#

Ah, well I guess I could see if a user adds a reaction to a message. That would probably be a good idea.

proud mason
stuck canopy
#

oof true.

fervent cradle
stuck canopy
#

wait also, is getting the last message from a member going to be a hard task?

stable cradle
stuck canopy
#

Maybe lol

proud mason
#

Cuz you will have to search through channel history

#

If you want user's last message in the guild from any channel, you will have to search through history of all channel

stuck canopy
#

how do I fix discord.errors.HTTPException: 400 Bad Request (error code: 30034): Max number of daily application command creates has been reached (200)

#

Like I know what the error means, but is there a workaround

#

oof.

glossy forum
#

Hey, do you know which part of Pycord allows to achieve this kind of menu with slash commands?

#

Or is it just the autocompletion? 🤔

young bone
glossy forum
#

Ah, I see
Thanks

glacial falcon
#

how do i ensure the bot files for sharding on numerous servers are the same?
like if i do an update (possibly through git?), all shards should get real-time updates on files and reload cogs for example

proud mason
glacial falcon
#

can you explain what is a shard manager

proud mason
#

like a script that connects to each server and start/stops/restarts the instance. i would use git pull before starting the bot so latest code is used everytime

#

you could run this script using github actions

full basin
#

Because interaction.user will never be in the players list, you're storing ids

proud mason
#

also, dont define player in the global scope

proud mason
#

override the init like so

#

def __init__(self, players):

#

and set self.players to players

#

and pass it while creating the view view = MyView(players)

#

so what do you not know

#

lol thats simple classes stuff

#

its really good to learn oop

limber urchin
#

Learning basic OOP is essential if you want to make a bot with py-cord.

#

And if you don't know it, you won't understand like 80% of answers given to you here

livid wolf
#

How do I create and add a role with admin permissions to a command

#

And give it to a user

#

with one command

proud mason
#

.rtfm create_role

winter condorBOT
loud sail
# proud mason well, create a new view in the select menu callback, and do `interaction.message...

The code where I send the embed with the select menu into the channel is in my TicketSystem.TicketMSG_Command file. Where the user opens the ticket via the menu is in my TicketSystem.Views.MainTicketView file. Now how can I edit the select menu; I mean the select menu to edit is in a completely different file.

Code:


ticketmsg = self.client.get_channel(1064794830296850453)

        await ticketmsg.send(embed=em, view=TicketViewCreateTicket())

I had already tried:

  • from TicketSystem.TicketMSG_Command import TicketMSG (TicketMSG is the name of the class).
  • from TicketSystem.TicketMSG_Command import ticketmsg
    But i get errors
proud mason
proud mason
#

.rtfm add_roles

winter condorBOT
proud mason
#

And this

loud sail
proud mason
loud sail
#

or is there already an option here for the user's selection not to be saved?

feral lintel
feral lintel
#

I have asked the question before about the decorators @channel.before_invoke, @channel.after_invoke.

It worked as inteded with the prefixed command, but it does not work as inteded for the SlashCommandGroup. any ideas ?
https://pasteio.com/xW9VDE8tPQeb

proud mason
loud sail
proud mason
#

(or interaction.response.edit_message)

proud mason
#

Do you override the on connect event?

#

.slashnoshow

winter condorBOT
#

Checklist for Application Commands Not Showing Up:
• Does your bot have the application.commands scope?
• Are you loading cogs before on_ready and on_connect?
• Is on_connect not overridden?
• Did you update to the newest version of py-cord (tag: install)?
• Is User Settings > Accessibility > Chat Input > Use legacy chat input turned off?
• Did you share your code and errors?
• Do you still have libraries that conflict with the discord namespace (e.g. discord.py)?

lime lichen
#

thanks!

#

probably should delete it since its resolved

#

boop

loud sail
# proud mason How? You get interaction in select menu callback parameters

yes, so: The message to be processed with a new view is in the TicketMSG_Command.py file. If the user now uses the select menu on the message, he will receive a response from the select menu callback from the file MainTicketView.py. But now I want to edit exactly the message from the TicketMSG_Command.py file with a new view. I can't get any further there.

livid wolf
proud mason
#

do you want to continue some code in the command after the select menu has been interacted with?

loud sail
proud mason
proud mason
# loud sail okay: D
# View
class MyView(discord.ui.View):
    def __init__(self, name: str):
        super().__init__()
        self.name = name

    @discord.ui.string_select(...)
    async def button1(self, select: discord.ui.Select, interaction: discord.Interaction):
        await interaction.response.send_message(f"{self.name} chose {select.values[0]}")
        self.stop() # this is the view.stop
#command
@bot.command(...)
async def my_cmd(ctx: discord.ApplicationContext, name: str):
    view = MyView(name)
    await ctx.respond("Please select", view=view)

    # wait till view.stop is called
    await view.wait()

    embed = discord.Embed(description=view.children[0].values[0], ...)
    await ctx.respond(embed=embed)
#

Possible you want to do this?

alpine kernel
#

kinda more of a python question but what would the best way to handle me wanting to call a cog function off of on_ready()? since it's like a static function (no self) and cant call an instance function, should I just use a decorator to wrap self into the function?

the core of the question is i want to ensure my connection to my sqlite db is still ok in case of an interruption ie sleeping computer

#

or i guess the connection could be static, dunno

proud mason
alpine kernel
#

yeah I want to do something like self.check_db_connection() but cant due to no self variable

proud mason
#

where is the on_ready listener? in the same cog or different?

alpine kernel
#

same cog

proud mason
#

hmm

#

move it outside thee cog?

alpine kernel
#

and just call the cog function from like the bot level?

proud mason
#

like a simple function?

#

alpine kernel
#

??? heh

proud mason
alpine kernel
#

I'll try and poke around at it more see if i can answer my own question maybe i'm being dumb, or i might be able to explain it better

#

yeah I dont know if that made sense either -.-

proud mason
#

that made slight sense

alpine kernel
#

are cogs basically singletons? i cant understand an instance where there would be multiple instances, maybe in sharding? (which i havent read up on)

proud mason
#

if so, then yes

alpine kernel
#

yes

#

i guess i could just handle the db connection as a static of the class then :T

#

does my original question make sense of checking the db connection on a on_ready()? or am i just going off on the wrong path?

loud sail
proud mason
# alpine kernel yes

yea there isnt any valid situation where you would need more than 1 object of the specific cog class. v3 changes this as gears (analogous to cogs) isnt class based

proud mason
alpine kernel
#

ok

proud mason
loud sail
proud mason
loud sail
alpine kernel
#

well, it looks like I have to go with opening a db connection per transaction because if i dont close the connection to the db using aiosqlite then the bot just halts and wont even stop with ctrl c

#

and if there's an error that occurs it does the same, guess i'll have to be careful with that heh

fervent cradle
#

hey, with buttons, how do i use server emojis?

grizzled sentinel
#

Please show your code

#

Your Mybutton class is fine.
However you generally would not have your cog (Simonsays) inherit from a view that does not make much sense. Also to use players you need an instance of the class the definition of the class here players = Mybutton.players. (Instance is when you do mybtn_instance = Mybutton(player_string) like what you have in ctx.respond)

Overall I recommend brushing up a little bit on how classes work in python.

grizzled sentinel
#

players would than be a instance of Mybutton so to get the list of players you would need to do players.players but yes that would be how you would do it.

fervent cradle
#

without the \

#

is there a way to get message links btw? like say i put a message link into the bot, itll automatically find the message and get the content etc?

grizzled sentinel
#

If it works 👍 that Is fine. I was not aware that was possible XD

fervent cradle
grizzled sentinel
#

#998272089343668364 message

First ID is guild ID
Second ID Is Channel ID
Third Message ID
Just take the link as text and extract the 3 IDs

fervent cradle
#

ah okay thanks

#

random question, after my bot ahs been on for a long time (over 30 mins) all interactions stop working

#

is there a way to fix this?

silver moat
#

interaction as in view components and/or app commands?

fervent cradle
#

view components

#

app commands still work

silver moat
#

?tag persistent

obtuse juncoBOT
#

dynoError No tag persistent found.

silver moat
#

/exmaple

errant craneBOT
#

Here's the persistent example.

silver moat
fervent cradle
#

oh wait

#

are timeouts set by default?

silver moat
#

yes

fervent cradle
#

ah

#

makes sense i think i fixed it now

silver moat
#

k

fervent cradle
#

ty

#

discord moment

copper knot
#

is there a way to get the current page group of a paginator

#

i only see current_page

#

nevermind

green hinge
#

How can I access a variable here that is set in another .py file ?
I want to display the embed with a button. When I press the button a new view appears with a dropdown menu and the embed is cleared. If I selected something in the dropdown menu, the embed should be sent again and the button should be disabled.
Does my approach make sense or is there a better way?

    def __init__(self, bot: discord.Bot:
        self.bot = bot
        self.embed = discord.Embed(title="Fertig", 
                                    description=f"Fertig", 
                                    color=discord.Color.blurple()
                                    )
        super().__init__(timeout=None)

    if bot.check[0]['wetter'] == True:
        @discord.ui.button(label='Wetter', custom_id="Wetter_Button", style=discord.ButtonStyle.primary, disabled=True)
        async def wetter_button(self, button: discord.ui.Button, interaction: discord.Interaction):
            await interaction.response.defer()
    else:
        @discord.ui.button(label='Wetter', custom_id="Wetter_Button", style=discord.ButtonStyle.primary)
        async def wetter_button(self, button: discord.ui.Button, interaction: discord.Interaction):
            await interaction.response.defer()```
winter condorBOT
# green hinge How can I access a variable here that is set in another .py file ? I want to dis...

Need to keep track of a variable between functions? No problem!

⚠️ Careful what you name it though, else you might overwrite something ⚠️

Just add it to your commands.Bot or discord.Client instance like so:

bot = commands.Bot(...)
bot.my_variable = 0

async def foo():
    bot.my_variable += 1

# In a cog
@commands.command()
async def counter(self,ctx):
    await ctx.send("Current Counter is at {}".format(ctx.bot.my_variable))

This also allows you to access this from other cogs/extensions/functions. Anywhere you have access to the bot instance

green hinge
proud mason
proud mason
#

using view.add_item

green hinge
# proud mason when the new view appears, do the buttons get removed?

So I have a view with an embed. Buttons are displayed under the embed.
If I now press one of these buttons, the embed is deleted and the dropdown menu associated with the button appears.
If I now select something in this dropdown menu, the embed below should be sent again and the button should be disabled.

loud sail
#

I get this error. How can I fix it?

Error:

TypeError: __init__() missing 1 required positional argument: 'name'```
copper knot
#

the error is obvious

loud sail
#

TicketViewCreateTicket(name)

copper knot
loud sail
green hinge
# proud mason subclass discord.ui.Button and programmatically add the buttons in view init

This is my view with my embed:

class OptionalView(discord.ui.View):
    def __init__(self, bot: discord.Bot, spotdaten):
        self.bot = bot
        self.spotdaten = spotdaten
        self.embed = discord.Embed(title="Fertig", 
                                    description=f"Fertig", 
                                    color=discord.Color.blurple()
                                    )
        super().__init__(timeout=None)

        @discord.ui.button(label='Wetter', custom_id="Wetter_Button", style=discord.ButtonStyle.primary, disabled=True)
        async def wetter_button(self, button: discord.ui.Button, interaction: discord.Interaction):
          await interaction.channel.send(view=await WetterView(self.bot, self.spotdaten))
            await interaction.response.defer()```
And after the button click, this view will be called:
```py
class WetterView(discord.ui.View):
    async def __new__(cls, *args, **kwargs):
        obj = super().__new__(cls)
        await obj.__init__(*args, **kwargs)
        return obj
    
    async def __init__(self, bot: discord.Bot, spotdaten):
        self.bot = bot
        super().__init__(await Wetter(self.bot, spotdaten))```
Here a ui.Select is created and after I have selected something there the OptionalView is called again and appears under the select menu.

The whole thing should now be so that the button is disabled and you can no longer click on it.
loud sail
#

how do i have to declare this?


class on_ready(commands.Cog): # für das Select Menü ein extra on_ready Event im Cog!
    def __init__(self, client, name:str):
        self.client = client
        self.name = name

    @commands.Cog.listener(
        'on_ready'
    )
    async def listener(
        self
    ):
        self.client.add_view(
            TicketViewCreateTicket(name)
        )

loud sail
#

the select menu should also still work after bot start

loud sail
#

well, I'll just leave it like that for now.

round rivet
#

if you want the select menu to reset/unselect after you click it just send a message edit with view being the same view

proud mason
green hinge
#

Can I somehow provide the dict 'spotdaten' outside of a function so that I can make this if query?

class OptionalView(discord.ui.View):
    def __init__(self, bot: discord.Bot, spotdaten):
        self.bot = bot
        self.spotdaten = spotdaten
        self.embed = discord.Embed(title="Fertig", 
                                    description=f"Fertig", 
                                    color=discord.Color.blurple()
                                    )
        super().__init__(timeout=None)

    if 'wettercheck' not in self.spotdaten[1]:```
cyan quail
#

nope

#

unless you define spotdaten at the top of your file (after imports) so it's a regular variable

#

but that would assume it's always the same

green hinge
#

I want to check if the button is already pressed or not when I call the view. If yes then it should be disabled and if no it should be active.
But at the moment I have no idea how to do this.

proud mason
#

Add it in the init using view.add_item

green hinge
# proud mason Yea like i said, don't add the button using the decorator

Then it should work like this or?

class OptionalView(discord.ui.View):
    def __init__(self, bot: discord.Bot, spotdaten):
        self.bot = bot
        self.spotdaten = spotdaten
        self.embed = discord.Embed(title="Fertig", 
                                    description=f"Fertig", 
                                    color=discord.Color.blurple()
                                    )
        super().__init__(timeout=None)
        
        if 'wettercheck' not in self.spotdaten[1]:
            self.add_item(WetterButton(self.bot, self.spotdaten))
        else:
            self.add_item(WetterButton(self.bot, self.spotdaten, disabled=True))```
winter condorBOT
static juniper
#

how to use threading with asyncio

loud sail
#

how can i fix this?

AttributeError: 'InteractionResponse' object has no attribute 'send_mesage'```
proud mason
young bone
#

^

proud mason
loud sail
static juniper
proud mason
proud mason
#

in an async program, there should be only 1 event loop

#

it should be the main thread

static juniper
proud mason
#

there shouldnt be other threads too

proud mason
static juniper
#

but when i try to run multiple command it stuck on first command

proud mason
static juniper
#

no

#

i mean when using requests library

#

and wait for response, other command will need to wait for the first command to be done

young bone
obtuse juncoBOT
#

Why you should not use the requests library for your bot
requests is a popular HTTP library for Python. It is however not a good option for Discord bots, since it is not async and blocking.

This essentially means that your bot will not be able to execute any code at all while a request is happening. Since requests usually take a few seconds to complete, this can have a detrimental effect on your bot's performance. E.g if a user executes a command that performs a request taking 5 seconds to complete, no one else will be able to use your bot for those 5 seconds.

Please look at using a HTTP library that has async support, such as aiohttp or httpx

static juniper
#

ok

static juniper
young bone
static juniper
static juniper
#

it's respond the message from slash command

#

*when interact the slash command

young bone
#

so what is it returning?

static juniper
young bone
#

no

static juniper
#

no?

young bone
#

It returns in Interaction

static juniper
young bone
static juniper
#

ok

fossil mulch
#

Hi guys - is there a wrong way of shutting down my bot? Talking especially regarding developement - I've created a second bot account and all, but regarding the "rapid restarting" via pycharm - is there anything i should look for?

proud mason
#

view.children is a list of items in sequential order. get the button at the correct index and set disabled = True. edit the message with the updated view

proud mason
proud mason
fossil mulch
#

but if i made changes to main.py i need to restart - are there any tips on proper way? like first shutdown instead of restart or something like this?
Will have a look at the hot loading, thanks

static juniper
#

ok

proud mason
fossil mulch
#

thanks =)

static juniper
proud mason
proud mason
fossil mulch
#

sure, sounds good

#

How is the devel of v3 going so far? Looking good?

static juniper
#

in terminal it don't throw anything

proud mason
#

huh

#

do you have an error handler?

static juniper
proud mason
proud mason
static juniper
#

@proud mason

proud mason
static juniper
fossil mulch
#

Hi guys, somehow my slash commands wont get recognized anymore - is there something i missed in the upgrade to 2.4 that needs to be changed? Here for example is an basic ping command that wont show up anymore on Discord

mako/cogs/utils.py

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

    @discord.command()
    async def ping(self, ctx) -> None:
        await ctx.respond(f"Pong! {round(self.bot.latency * 1000)}ms.")

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

main.py

@bot.event
async def on_ready() -> None:
    ...
    ...
    load_cogs()

def load_cogs() -> None:
    for file in os.listdir("mako/cogs"):
        if file.endswith(".py"):
            extension = file[:-3]
            try:
                bot.load_extension(f"mako.cogs.{extension}")
                print(f"Loaded Extension {extension}")
            except Exception as e:
                exception = f"{type(e).__name__}: {e}"
                print(f"Failed to load extension {extension}\n{exception}")

I have 3 commands above the on_ready - these work and will show up in discord when opening the command prompt:

@bot.command()
async def reload_utils(ctx):
    bot.reload_extension('mako.cogs.utils')
    await ctx.respond('Reloaded Utils')
#

Or is this just some Discord stuff - because sometimes also my main bot wont show up in the list

full basin
#

You do it on the bot initialization

fossil mulch
#

so before the bot.run you mean?

full basin
#

Yes

#

Or after you define the bot

fervent cradle
#

hi im getting this error:
TypeError: object.__init__() takes exactly one argument (the instance to initialize)
the code that its erroring on is this:
super().__init__(timeout=None)

fossil mulch
#

Thats some easy fix - thanks for your help

fossil mulch
#

dont even know why i changed it - had it that way before ^^

fervent cradle
#

the thing is it allows it without the timeout arg but not with

full basin
#

Can you show what I asked for

#

Literally can't do anything with one line

fervent cradle
#

one second

#
  File "C:\Users\Rio\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\cog.py", line 743, in _load_from_module_spec
    setup(self)
  File "C:\Users\Rio\Documents\GitHub\DBMain-Bot\modules\events\Tickets.py", line 130, in setup
    bot.add_cog(tickets(bot))
  File "C:\Users\Rio\Documents\GitHub\DBMain-Bot\modules\events\Tickets.py", line 19, in __init__
    super().__init__(timeout=None)
TypeError: object.__init__() takes exactly one argument (the instance to initialize)

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

Traceback (most recent call last):
  File "C:\Users\Rio\Documents\GitHub\DBMain-Bot\main.py", line 29, in <module>
    bot.load_extension(f"modules.events.{file[:-3]}",store=False)
  File "C:\Users\Rio\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\cog.py", line 867, in load_extension
    self._load_from_module_spec(spec, name)
  File "C:\Users\Rio\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\cog.py", line 748, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.errors.ExtensionFailed: Extension 'modules.events.Tickets' raised an error: TypeError: object.__init__() takes exactly one argument (the instance to initialize)
full basin
#

Show the class

fervent cradle
#
class tickets(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        global bot1
        bot1 = bot 
        super().__init__(timeout=None)

ignore the jankiness in the first few lines

proud mason
fervent cradle
#

wait

#

have i put the code in the wrong place

#

i was working on this at 4am and i just got home from college

#

i mean its not as bad as what i did last night

green hinge
#

How can I send the second await command with the view only after I have completely run the first view?

await interaction.channel.send(view=await SchnurTypView(self.bot, self.spotdaten))
await interaction.channel.send(embed=self.embed, view=OptionalView(self.bot, self.spotdaten))```
proud mason
#

.tag viewwait

winter condorBOT
#
# View
class MyView(discord.ui.View):
    def __init__(self, name: str):
        super().__init__()
        self.name = name

    @discord.ui.string_select(...)
    async def button1(self, select: discord.ui.Select, interaction: discord.Interaction):
        await interaction.response.send_message(f"{self.name} chose {select.values[0]}")
        self.stop() # this is the view.stop
#command
@bot.command(...)
async def my_cmd(ctx: discord.ApplicationContext, name: str):
    view = MyView(name)
    await ctx.respond("Please select", view=view)

    # wait till view.stop is called
    await view.wait()

    embed = discord.Embed(description=view.children[0].values[0], ...)
    await ctx.respond(embed=embed)
green hinge
proud mason
#

oh and dont forget to call view.stop (or self.stop) in the view

green hinge
# proud mason yep looks right (other than indentaion)

Where do I have to put the stop?

class SchnurFarbeView(discord.ui.View):
    async def __new__(cls, *args, **kwargs):
        obj = super().__new__(cls)
        await obj.__init__(*args, **kwargs)
        return obj
    
    async def __init__(self, bot: discord.Bot, spotdaten):
        self.bot = bot
        super().__init__(await Schnurfarbe(self.bot, spotdaten))```
green hinge
# proud mason oh and dont forget to call view.stop (or self.stop) in the view

So I don't get an error message but the next view is not displayed when I have selected something in the select menu.

class Schnurfarbe(discord.ui.Select):
    def __init__(self, bot: discord.Bot, spotdaten):
        self.bot = bot
        self.spotdaten = spotdaten
        options = [discord.SelectOption(label=farbe) for farbe in schnurfarbe_sortiert]
        super().__init__(
            placeholder="Wähle die Farbe deiner Hauptschnur aus",
            min_values=1,
            max_values=1,
            options=options,
        ) 
async def callback(self, interaction: discord.Interaction):
      .
      .
      .  
self.view.stop()        ```
plush moat
#

        create_tickets = await guild.fetch_channel(CREATE_TICKETS)
        history = create_tickets.history()
        for message in history:
#

Anyone know why I can't iterate through history like this?

#

nvm, figured it out. I impelements AsyncIterator, so I should async for message in history. Ty!

fossil mulch
#

hi, i want to fill an bot admin table with guild and userid

#

But when i try to pass the userid to the command i get an errror telling me i should insert an valid number

#

it seems it is too long, any quick ideas on how i could manage to fix this?

#

type casting into str maybe, do you know of any "cleaner" solution?

silver moat
#

for real tho, just use string since less memory

round rivet
#

your db might have a type like 'bigint'

#

allowing for larger integers

#

int()

#

and if that doesn't work it's not a channel id

true panther
#

How do I go about making command group in a cog? @commands.group()?

silver moat
true panther
silver moat
#

yeah, @commands.group()

true panther
#

and if I want to make subgroup it's the same as commands outside of cog as well? So instead of @commands.group() it's @name_of_parent.group()?

#

I'm asking because that's what I've been doing but it logs error about no such command existing :(

long zealot
#

Hijacking this line of conversation too, how do you make a slash command subcommand group within a cog? Same thing?

errant craneBOT
#

Here's the slash cog groups example.

astral mist
#

Diffrence between ctx and interaction

cyan quail
#

ctx is context, interaction is interaction

astral mist
#

What’s what’s better to use

cyan quail
#

well it's not about what's "better", they're implemented in different scenarios

#

ctx is associated with commands and if it's a slash command, you'll also have access to ctx.interaction

silver moat
#

well, applicationcontext wraps interaction, just like how context also wraps message

green hinge
#

Can I embed icons in pagination to create a voting system?
E.g. a sentence and then behind it 2 icons that you can click for positive or negative?

#

So that I can output 5 sentences per page and behind each sentence then query by icon whether positive or negative?

green hinge
# cyan quail do you mean buttons?

I thought of something like this:

Text ❌ ✅
Text ❌ ✅
Text ❌ ✅
Text ❌ ✅

◀️Button Button▶️

And on the X and hook I wanted to let vote

cyan quail
#

well you can't really interact with embed content/text itself

#

your concept would require you to attach new buttons for your voting system

#

or use reactions, but if the votes are meant to be different per page then it wouldn't work

green hinge
#

So I only have the possibility to make 1 text per page and under the embed 2 buttons for the voting and underneath are the buttons to scroll from the paginator?

cyan quail
#

pretty much

green hinge
#

If each page should be voted individually then I have to use buttons right?

cyan quail
#

if you're using ext.pages, the Paginator has an option to attach a custom view alongside the page buttons

#

yeah

cyan quail
green hinge
cyan quail
#

kind of yeah

#

just check the examples on that page, it handles the pagination for you

green hinge
#

Okay I will have a look and try my luck 🙂
Thanks!

latent veldt
#

whats the difference between bot.command and bot.slash_command

young bone
#

?tag client

obtuse juncoBOT
#
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
bridge.Bot # above + bridge commands (application commands and text commands in one)
latent veldt
#

discord.Bot

silver moat
latent veldt
#
for filename in os.listdir('./cogs'):
    if filename.endswith('.py'):
        try:
            bot.load_extension(f'cogs.{filename[:-3]}')
        except Exception as e:
            print(f'Failed to load extension {filename}: {e}')```?
silver moat
#

that works

latent veldt
#

and then like this in the file?

class uptime(commands.Cog):
    def __init__(self, client):
        self.client = client

        @client.slash_command(name="uptime", description="Get the bot's uptime")
        async def uptime(ctx):
            now_time = time.time()
            uptime_seconds = now_time - start_time
            uptime_hours, remainder = divmod(uptime_seconds, 3600)
            uptime_minutes, uptime_seconds = divmod(remainder, 60)

            uptime_string = "{:02.0f}:{:02.0f}:{:02.0f}".format(uptime_hours, uptime_minutes, uptime_seconds)
            await ctx.respond(f"Uptime: `{uptime_string}`")

def setup(client):
    client.add_cog(uptime(client))```

or should I change it
young bone
#

discord.Cog

latent veldt
young bone
#

yes

latent veldt
# young bone yes

and then last question lmao, if I have a class outside of the one that gets setup like this, is it ok? because Im getting an error about registering commands or something

import os
import discord
from discord.ext import commands
import logging

color = 0x2a2c31

logger = logging.getLogger(__name__)

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

        self.add_item(discord.ui.InputText(label="Length", required=True, min_length=2, style=discord.InputTextStyle.short))
        self.add_item(discord.ui.InputText(label="Winners", required=True, min_length=1, max_length=2, style=discord.InputTextStyle.short))
        self.add_item(discord.ui.InputText(label="Prize", required=True, min_length=1, max_length=128, style=discord.InputTextStyle.short))
        self.add_item(discord.ui.InputText(label="Description", required=False, max_length=1000, style=discord.InputTextStyle.long))

    async def callback(self, interaction: discord.Interaction):
        try:
            embed = discord.Embed(title="Giveaway Created", color=3092790)
            embed.add_field(name="Length", value=self.children[0].value)
            embed.add_field(name="Winners", value=self.children[1].value)
            await interaction.response.send_message(embeds=[embed], ephemeral=True)
        except Exception as e:
            logger.exception(f"An error occurred while creating a giveaway: {e}")
            await interaction.response.send_message("An error occurred while creating a giveaway.", ephemeral=True)

class creategw(discord.Cog):
    def __init__(self, client):
        self.client = client

        @client.slash_command()
        async def create_gw(self, ctx: discord.ApplicationContext):
            """Shows an example of a modal dialog being invoked from a slash command."""
            modal = giveawaymodal(title="Create Giveaway")
            await ctx.send_modal(modal)

def setup(client):
    client.add_cog(creategw(client))```
```Ignoring exception in on_connect
Traceback (most recent call last):
  File "C:\Users\oriel\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 378, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\oriel\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\bot.py", line 1164, in on_connect
    await self.sync_commands()
  File "C:\Users\oriel\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\bot.py", line 719, in sync_commands
    registered_commands = await self.register_commands(    
                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^    
  File "C:\Users\oriel\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\bot.py", line 588, in register_commands
    data = [cmd["command"].to_dict() for cmd in filtered_deleted]
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\oriel\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\bot.py", line 588, in <listcomp>
    data = [cmd["command"].to_dict() for cmd in filtered_deleted]
            ^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\oriel\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 844, in to_dict
    "options": [o.to_dict() for o in self.options],        
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\oriel\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 844, in <listcomp>
    "options": [o.to_dict() for o in self.options],        
                ^^^^^^^^^^^
  File "C:\Users\oriel\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\options.py", line 333, in to_dict
    "type": self.input_type.value,
            ^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'value' 
ProGiveaways#1875 is ready and online!```
young bone
#

read the error

errant craneBOT
#

Here's the slash cog example.

latent veldt
#

oh last question, do I need to specify guild ids or have that in the code

errant craneBOT
#

Here's the slash basic example.

latent veldt
#

so no ok thanks

latent veldt
young bone
#

what is the py-cord version?

latent veldt
#

2.4.0

young bone
#

can you show the pip list

latent veldt
#
aiosignal                1.3.1
aiosqlite                0.18.0
asgiref                  3.6.0
astunparse               1.6.3
async-timeout            4.0.2
attrs                    22.2.0
bcrypt                   4.0.1
beautifulsoup4           4.11.2
bleach                   6.0.0
boto3                    1.26.57
botocore                 1.29.57
braceexpand              0.1.7
bs4                      0.0.1
button-paginator         1.0.1
certifi                  2022.12.7
cffi                     1.15.1
charset-normalizer       2.1.1
click                    8.1.3
cloudinary               1.31.0
colorama                 0.4.6
discord-py-slash-command 4.2.1
DiscordUtils             1.3.4
dnspython                2.3.0
docopt                   0.6.2
email-validator          1.3.1
ffmpeg-python            0.2.0
Flask                    2.2.2
Flask-Cors               3.0.10
frozenlist               1.3.3
future                   0.18.3
gevent                   22.10.2
greenlet                 2.0.1
humanfriendly            10.0
idna                     3.4
imageio-ffmpeg           0.4.8
import-expression        1.1.4
itsdangerous             2.1.2
Jinja2                   3.1.2
jishaku                  2.5.1
jmespath                 1.0.1
line-profiler            4.0.2
MarkupSafe               2.1.2
multidict                6.0.4
numpy                    1.24.1
oauthlib                 3.2.2
pandas                   1.5.3
pip                      23.0
pipreqs                  0.4.11
py-cord                  2.4.0
pycparser                2.21
pymongo                  4.3.3
pyreadline3              3.4.1
python-dateutil          2.8.2
python-dotenv            0.21.1
pytz                     2022.7.1
requests                 2.28.2
requests-oauthlib        1.3.1
s3transfer               0.6.0
setuptools               66.1.1
six                      1.16.0
soupsieve                2.4
tweepy                   4.12.1
urllib3                  1.26.14
webencodings             0.5.1
websocket-client         1.5.1
websockets               10.4
Werkzeug                 2.2.2
wheel                    0.38.4
yarg                     0.1.9
yarl                     1.8.2
zope.event               4.6
zope.interface           5.5.2```
young bone
#

you dont use env?

latent veldt
#

ur confusing me

young bone
#

uninstall py-cord and this and reinstall py-cord

#

?tag install

obtuse juncoBOT
#
  1. Uninstall discord.py or any other forks of discord.py you might have with the namespace discord.
    python -m pip uninstall discord.py discord -y

2a. Install py-cord
python -m pip install py-cord

2b. Update py-cord
python pip install -U py-cord

Installing other builds:
Note: You need to have git installed. Use ?tag git to find out how to install git.

Updating the module to master branch (unstable):
pip install -U git+https://github.com/Pycord-Development/pycord

latent veldt
#

alr

latent veldt
young bone
#

close the terminal and restart the editor

latent veldt
#

same issue

young bone
#

did you uninstall this?

latent veldt
#

yup

#

its not in my pip list anymore

meager heron
#

Do you mean it’s not in requirements.txt, or that it’s not in pip freeze

proud mason
proud mason
green hornet
#

Guys, how to make a discord button open a url

limber urchin
#

.rtfm discord.ButtonStyle.link

winter condorBOT
green hornet
#

Um

#

that doesn't really help

#

oh wait

limber urchin
#

?

green hornet
#

thats cool

limber urchin
#

how does it not help?

green hornet
#

nvm, the internet was lagging, so the bot's message didn't show up

limber urchin
#

And don't cross post, stick to your own post or this channel. Not both

green hornet
#

*__**`Sorry`**__*

#

Ok, so now I am able to change the style of the button. How can I add a url to the button though?

#

I have this so far

  def init(self):
    super().init(timeout=None)
  @discord.ui.button(label="Upload Audition Now",
                     style=discord.ButtonStyle.link
                    )
  async def hello(self, interaction: discord.Interaction, button:discord.ui.Button):
    await interaction.response.send_message("opened link")
    ```
loud sail
#

Anyone have any ideas?

limber urchin
green hornet
#

what is a kwarg

full basin
limber urchin
full basin
#

Link Buttons dont have a callback so

limber urchin
#

Oh, fair enough

full basin
#

@green hornet you have a thread

green hornet
#

ok

full basin
#

#1077460125872312371

green hornet
#

yes

green hornet
#

yes, I should have told you guys to switch to the thread, sorry

copper magnet
#

How can I wait long after a slash command? I'm calling a neural network method that works for a long time, which discord will not tolerate

copper magnet
#

hmm?

full basin
#

Defer it

copper magnet
#

It's not clear, but it's very interesting. Can I have the full path of the function and where to insert it

full basin
#

Why do you need the function path?..

#

It's a context method

#

You just context.defer() at the start of your callback

copper magnet
#

🥹

full basin
#

Code

copper magnet
#

Badcode version 1:)))

full basin
#

If you're getting interaction then that's a not a slash command

#

Ita a button or any other ui thing

#

.rtfm Response.defer

winter condorBOT
full basin
#

Same logic

copper magnet
#

discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: InteractionResponded: This interaction has already been responded to before
Ok, error. cat

stuck canopy
#

I have this with my slash commands, those two options come from:

async def holyc(self, ctx: Context, style: str = None, delete: bool = True):

These two options are made by the bool I guess. how can I create my own options there?

#

Like I can create custom options, how do I create custom values under said options

fringe socket
#

WHAT THE HECK

#

I've done nothing wrong

#

and I'm getting

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

and i can't trace the error because it gets raised in pycord not my bot :/

#

screw it im just gonna defer it and see what happens

serene spindle
#

How can I disable Discord converting 2 regional indicators to a flag, as with my bot on mobile it does that when sending text with the indicators, but not on desktop

proud mason
proud mason
errant craneBOT
#

Here's the slash options example.

true panther
#

Is there a way to gatekeep listeners in cogs with roles or it must be inside the listener with ifs?

grizzled sentinel
#

Are you listening for a specific message or any message from a person with a role. (Or other event)

grizzled sentinel
#

Yeah, ifs are the only way.

true panther
#

Thanks

#

Can I make listener for specific channels only?

grizzled sentinel
#

No.

true panther
green hinge
#

Is it possible, if I create a new room via a button click, that the user is then also directly in this room to be able to write there or do you always have to manually click on the room then on it?

green hinge
loud sail
obtuse juncoBOT
loud sail
proud mason
#

.rtfm utils.get

winter condorBOT
loud sail
proud mason
soft girder
#

Is it possible with a button to get user ID. And if so, tell me the correct code.

full basin
#

There's literally inconsisent indentation

soft girder
full basin
#

.rtfm Interaction.user

winter condorBOT
full basin
#

Didn't know replit coded for you

#

Then it's not a replit error

#

You have inconsistent indentation

wary rover
#

Hi everyone!
Nowadays it is easily possible to play a sound. My problem is that I want to play two sounds at the same time but I have to wait until the first one is finished to play the second one, any idea how to do that?

proud mason
#

||try asking this to chatgpt||

wary rover
#

ChatGPT does not help me much

livid wolf
full basin
#

Then why you answer lmao

soft girder
#
@commands.has_permissions(administrator =True)
    @commands.guild_only()
    @game.command(name='teamlist', description='Displays TimList.',guild_ids=[944934277777326090,769823680695107594])
    async def teamlist(self , ctx: discord.ApplicationContext,*,time: Option(str,max_length=17, description='Start time')):
        cursor.execute(f"SELECT rowid,* FROM teamlist WHERE server_id = {ctx.guild.id}")
        item = cursor.fetchmany(19)

        class MyView(discord.ui.View):

            @discord.ui.button( label="Confirm",style=discord.ButtonStyle.success)
            async def button_callback(self, button, interaction):
                user = interaction.user

                for child in self.children:
                    child.disabled = False
                await interaction.response.edit_message(view=self)
                await ctx.send(f"доработаю{user.id}")

        await ctx.respond("Done.",ephemeral=True)
        a = ""
        i = 0
        for el in item:
            i+=1
            if i<17:
                a += f"**{i}**. {el[1]} | {el[2]} | <@{el[3]}>\n"
            else:
                a += f"Reserve🔴**{i}**. {el[1]} | {el[2]}  | <@{el[3]}>\n"
        #await ctx.send(f":scroll: TEAM LIST :scroll:\n🕐Time: {time}\n  \n{a}")
        embed1 = discord.Embed(title =f":scroll: TEAM LIST :scroll:",description=f"**🕐Time: {time}**\n  \n{a}", colour = discord.Colour.embed_background())
        await ctx.send(embed = embed1,view=MyView())
        #tlist = await ctx.send(embed = embed1)
        #await tlist.add_reaction("✅")
        db.commit()
#

Hi all. I need a code to get ID from the button, it turned out to be some kind of garbage. Or is everything right?

full basin
#

You got an answer

#

And my god. Move your class out of the command

soft girder
#

Is the code correct? Or can it be simplified?

soft girder
#

It is for copy

full basin
#
  1. I don't know what your code does.
  2. It's messy and mixed with command attributes and callback attributes
stable cradle
astral mist
#

How do I make buttons

hallow oriole
astral mist
#

Ty

astral mist
full basin
#

Yes

full basin
#

Hardcode it and see if it works

limber urchin
#

And please don't call your variables str. That's already a keyword in Python-

proud mason
# stable cradle What's the issue with doing that? I need the class in my command so that I can g...

defining classes is an expensive task and is a waste of resources if you do it inside the command. it will only cause you added lag and bugs. there will be scope conflicts with the self variable as you start using even slightly advanced functionality in the buttons. defining view classes outside the cog (or in a separate file) gives you all the features while protecting you from thee above mentioned issues

#

you should rather pass the option to the view init

proud mason
hallow oriole
#

Hey, I'm a little bit confused because I can't find any documentation for AuditLog-Events regarding timeouts... Neither does AuditLogDiff or AuditLogAction contain anything with communication_disabled_until or something similar... Do I oversee anything or is this a missing feature in the library? 🤔

meager mica
#

im trying to ping user on reply but it just dont turn yellow

#

message = await ctx.followup.send(f"<@{ctx.user.id}>", embed=embed, view=view, allowed_mentions=discord.AllowedMentions(users=True, everyone=False, roles=False))

limber urchin
#

Just use ctx.user.mention.

meager mica
#

i did

#

but i switched to that after it didnt work

#

just incase lol

limber urchin
limber urchin
#

You can still respond even if you defer

meager mica
#

it still dont ping me

#

am i using allowed mentions right

proud mason
#

try without allowed mentions

limber urchin
#

Well, why are you using allowed mentions anyways?

meager mica
limber urchin
#

Are you sure it isn't just a bug with your client? Have you looked at your phone for instance?

meager mica
#

i even tried replied_user=True

#

oh ill try that

#

it works on phone

#

so oopsies

#

ig my discord bugged

limber urchin
#

Try CTRL + R to reload your client

meager mica
#

Yep it's yellow now haha thanks

loud sail
#

The "m" is made small in discord. Should I therefore rather use the ID, i.e. that the channel is then called what the user ID of the member is?

proud mason
#

discord does some formatting with text channel names, thats why you are facing these errors

proud mason
loud sail
proud mason
#

or you could do ticket-1 ticket-2 etc and use a db to store stuff

loud sail
proud mason
proud mason
#

thats basic python ngl

#

you couldve googled

#

lel

novel jay
#

read pins

You should be learning basic python before learning Pycord.

loud sail
proud mason
#

cool 👍

loud sail
#

^^

wary rover
#

Hi there!
I have a problem, the py-cord update removes the spaces on my buttons when they are not between the letters. This is a real problem, is there a solution?

#

From this

#

to this

novel jay
#

which update, 2.4.0? which version were you on before?

wary rover
novel jay
#

Try 2.3.0

#

since there were a lot of updates from 2.2.2 to 2.4.0

wary rover
# novel jay Try 2.3.0

I have the impression that the problem comes from python, my pc and my server have the problem, it's strange I didn't have this problem until 21 days ago and I haven't touched anything since.

proud mason
loud sail
# proud mason cool 👍

Got it like this now. But it doesn't work either. Am I doing something wrong?

        if 'Ticket1' in select.values:
            cat = client.get_channel(985994142704353290)
            tickket = f'ticket-{interaction.user.name.lower().replace(" ", "-")}'
            print(tickket)
            channelll = discord.utils.get(interaction.guild.channels, name=tickket)
            print(channelll)

            if channelll:
                existiert = discord.Embed(
                    title='![AC_Nope](https://cdn.discordapp.com/emojis/1060555374815629362.webp?size=128 "AC_Nope") - Leider kein Ticket erstellt',
                    description=f'Du kannst kein neues Ticket öffnen, weil du **grade schon ein offenes Ticket** auf diesem Server hast.',
                    color=0x2b2c30
                )
                await interaction.response.send_message(embed=existiert, ephemeral=True)

            else:

                ticket_channel = await interaction.guild.create_text_channel(
                    f'ticket-{interaction.user}',
                    topic=f'![AC_PunktBlau](https://cdn.discordapp.com/emojis/1035563214752202833.webp?size=128 "AC_PunktBlau") - Dieses Ticket wurde von {interaction.user} erstellt.',
                    category=cat
                )
proud mason
#

and the channel name in discord

loud sail
proud mason
#

huh

#

no prints?

loud sail
#

I'll try again tomorrow. Then let me know

loud sail
#

But I'm not in the IDE anymore

proud mason
#

hmm

stuck canopy
proud mason
errant craneBOT
#

Here's the slash options example.

stuck canopy
#

I'm sorry.

errant craneBOT
#

examples/app_commands/slash_options.py line 15

@option("gender", description="Choose your gender", choices=["Male", "Female", "Other"])```
stuck canopy
#

Ah okay I see it.

#

Thank you so much.

proud mason
#

np 👍

astral mist
#

how do u add roles

#

on interaction

young bone
#

but with interaction...

astral mist
astral mist
full basin
#

.tias

winter condorBOT
astral mist
#

Alr

young bone
alpine kernel
#

any way to set a bot's font? I want to use a monospaced font, but not in a code block (because discord timestamps arnt parsed in them) I know you can copy/paste fonts into discord, but dunno how that would be done in a bot, if possible

full basin
#

Just copy and paste the text into the code?...

alpine kernel
#

not really a viable answer

full basin
#

Your question doesn't make sense

#

You want to send responses with some font

#

Get the formatted text and paste it in the code

#

Don't know what else you expect

silver moat
#

I suppose you can use emojis for each of the characters and punctuations you are using in your bot, but that racks up character usage really quickly.

latent veldt
#

how do I edit an embed with pycord

silver moat
#

await foo.edit(embed=new_embed) where foo is something that has an edit method

latent veldt
#
          ^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'Embed' object has no attribute 'edit'```
silver moat
#

yeah it doesn't

latent veldt
#

so how would I.

silver moat
#

depends on how you send the embed

latent veldt
silver moat
latent veldt
#

ohh

latent veldt
#

is there a way to edit it by id

silver moat
#

what ID

#

a message id?

latent veldt
#

maybe

#

not sure

silver moat
#

...

latent veldt
silver moat
#

where are you getting the ID

latent veldt
silver moat
#

what ID are you getting

latent veldt
#

???

silver moat
#

or planning to

latent veldt
#

the message id possibly if thats possible

silver moat
#

ok

latent veldt
silver moat
latent veldt
# silver moat why

I just have it set up odd I guess, I don't pass in anything like that I think

silver ice
latent veldt
#

this is how I send the embed await interaction.channel.send(embeds=[public_embed], view=enter_giveaway_view) and then in a different class ```py
class EnterGiveaway(discord.ui.View):
def init(self, public_embed):
super().init()
self.public_embed = public_embed`
@discord.ui.button(label="Enter Giveaway", style=discord.ButtonStyle.primary, emoji="🎁")
async def button_callback(self, button, interaction):
entries_field = self.public_embed.fields[-1]
entries_text = entries_field.value
current_entries = int(re.search(r'Entries: **(\d+)**', entries_text).group(1))
new_entries = current_entries + 1
new_entries_text = re.sub(r'Entries: **\d+**', f'Entries: {new_entries}', entries_text)
new_embed = discord.Embed(
title=self.public_embed.title,
description=self.public_embed.description,
color=self.public_embed.color
)
for field in self.public_embed.fields[:-1]:
new_embed.add_field(name=field.name, value=field.value, inline=field.inline)
new_embed.add_field(name=entries_field.name, value=new_entries_text, inline=entries_field.inline)
await interaction.edit_orginal_response(embed=new_embed)


Thats what I'm trying to do but the edit wont work
full basin
#

Use google

dusky sorrel
#

Okay so basically I can't find anything in the docs about this so if there's actually a page just direct me there thx

anyway

How do you add categories in the help command

silver moat
dusky sorrel
#

thx

soft girder
#

is it possible to somehow make it so that there is a code that writes out my plan sheet or ban plate and after the expiration of time - this plate was deleted, let's say I issue a ban to a person for 2 days and after 2 daysBan is removed.

astral mist
#

is there a tag that shows all the attribute

proud mason
#

try it out in #883236900171816970

astral mist
#

so theres a rtfm attribute

proud mason
#

uh waa?

astral mist
proud mason
#

is there a tag
what did you mean by this?

astral mist
#

all those things

proud mason
astral mist
#

all attributes and methods of ctx?

#

yes

proud mason
#

.rtfm commands.Context

proud mason
#

check it on the docs page

astral mist
#

user isnt defined

#

oh

proud mason
#

channel ids are an int

#

dont use a while True loop

#

use on_reaction_add event

#

dude there is so much wrong with your code

astral mist
#

ik i said oh

proud mason
#

looks like you are using stuff from very old dpy tutorials

proud mason
#

i suggested you check out pycord guides

#

.guide

winter condorBOT
proud mason
#

slow bot blobpain

astral mist
#

i am trying to make a reaction roles

#

for my bot

proud mason
#

use the on_reaction_add event

#

.rtfm on_reaction_add

winter condorBOT
fringe socket
#

Hey, anybody know how I can add the current Unix timestamp in seconds to a number?

Current code:

def convert(time):
    pos = ["s", "m", "h", "d"]

    time_dict = {"s": 1, "m": 60, "h": 3600, "d": 3600 * 24}

    unit = time[-1]

    if unit not in pos:
        return -1
    try:
        val = int(time[:-1])
    except:
        return -2

    return val * time_dict[unit]


time = convert(duration)
embed.add_field(
            name=f"Ends:",
            value=f"<t:{discord.utils.utcnow() + time}:R>"
        )
proud mason
#

Also try using datetime.datetime.now instead of utcnow

#

Sometimes i have found weird stuff when using UTC time instead of local time

#

Oh btw

#

There is this cool library called time_str that does what you want but much better

fringe socket
#
embed.add_field(
            name=f"Ends:",
            value=f"<t:{discord.utils.utcnow().timestamp + time}:R>"
        )
pale mica
# fringe socket

Use int(time.time()) it gives you the current Unix time in seconds (but also you could've just wrapped it with int since integers are convertible to floats)

tired goblet
#

what are my options if i have 29 choices for the user to pick from?

#

it supports a maximum of 25

errant craneBOT
#

Here's the slash autocomplete example.

tired goblet
#

Thank you

#

I was also looking at select menus, do you think they'd be a better fit?

#

Oh but what if they are also limited to 25

fervent cradle
#

hi, when getting the channel history with ```py
async for message in msg.channel.history(limit=x):

#

I'd like to get about a 100k messages this way - so 100 is pretty low :')

fringe socket
fringe socket
tired goblet
#

can i define my select callback function in a seperate py file?

full basin
#

Why would that be needed

tired goblet
#

ah it just looks ugly where i have it now

#

but yeah it works

proud mason
fervent cradle
fringe socket
#

It won't let you do it at all bro

loud sail
proud mason
#

Use str(interaction.user).lower()...

loud sail
proud mason
loud sail
midnight torrent
#

is it possible to check if a command has already been defered?

loud sail