#Basic Pycord Help (Quick Questions Only)

1 messages · Page 54 of 1

rose moon
#

bcz i cant use online payment

green hinge
#

Should I check if the fish dropdown menu already exists and if so remove it and then create it again?

proud mason
#

😭 how didd you get it? i need answers

proud mason
#

there is railway.app

there are google cloud, aws, azure, oracle free vps. but you need a card for verification

young bone
proud mason
green hinge
proud mason
#

sorry im really confused now

sick quest
#

how can I add a slash command group to a cog/extension?

errant craneBOT
#

Here's the slash cog groups example.

sick quest
#

thanks

green hinge
sick quest
#

oh wait never mind

#

I misread it

fervent cradle
#

only accepts discord.Interaction or commands.Context

pager = Paginator(maps_list)
  await pager.start(ctx)```
#
@client.slash_command(description="")
async def maps(ctx):
  maps_list = [EMBEDS IN HERE]
  pager = Paginator(maps_list)
  await pager.start(ctx)```
fervent cradle
green hinge
#

How can I solve the problem?

    async def callback(self, interaction: discord.Interaction) -> None:
        spot = self.user.value
        pattern_spot = re.compile(r'^([1-9]\d{0,1}|200):([1-9]\d{0,1}|200)$')
        if not pattern_spot.match(spot):
            embed = discord.Embed(
                title="Fehler",
                description="Spot muss im Format '100:100' eingegeben werden. Der Maximalwert beträgt '200:200'"
            )
            await interaction.response.send_message(embed=embed)
            await interaction.response.send_modal(AddSpot(self.bot, interaction.channel))
        self.view.add_item(AngelArt(self.bot))
        await interaction.response.edit_message(view=self.view)
    await interaction.response.send_modal(AddSpot(self.bot, interaction.channel))
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\interactions.py", line 1049, in send_modal
    raise InteractionResponded(self._parent)
discord.errors.InteractionResponded: This interaction has already been responded to before```
wraith hull
#

How can I restart my bot in VSC?

green hinge
wraith hull
green hinge
green hinge
wraith hull
#

I made a slash command but it isn't showing

#

How can I make it show?

fallen cove
clever thistle
#

Is it possible to get information on linked accounts for guild members? I'd like to autoassign a certain role to people with Twitch "VIP" status

gleaming falcon
#

There was something just merged for linked roles. Unsure if you can get other linked accounts though; I don’t fully know how it works

fallow hawk
#

is there any way to have the callback for each button be different? like so that if i click on the second button, it will respond with the number 2, btw im generating these procedurally

final fractal
#

Hey guys, what is the most reliable and inexpensive way to keep my bot online. I'm not too sure how to go upon this. (I am using VSC)

silver moat
#

railway.app

rose vapor
#

am i clueless or where is the list index that is out of range?
i click run and immediately error
asking here cause slash command

young bone
rose vapor
#

same thing

young bone
#

can you show the pip list?

rose vapor
young bone
#

mhm

#

do you get it only at this one?

rose vapor
#

this is all that's in there, it goes on_ready(), this function, then bot.run()

for fun, before this, i tried the dropdown example (which worked) and then basically removed that function and put this one in

fallow hawk
#

is there any way to have the callback for each button be different? like so that if i click on the second button, it will respond with the number 2, btw im generating these procedurally

rose vapor
# young bone mhm

for knowledge, the error goes away when i include 'description' in slash_command()

here was that full traceback i never shared cause silly me in debug mode

silver moat
#

fun

mild sigil
#

I want to display a message after a button press but it is not working.

    async def fourth_button_callback(self, button, interaction):
        for child in self.children:
            child.disabled = True
        await interaction.response.edit_message(view=self)
        await interaction.response.send_message("You clicked the sloth button!")```
#

I assume its due to the await causing issues

royal spindle
#

Is there a way to get all active views on the bot?

#

(discord.ui.View)

silver moat
mild sigil
#
Traceback (most recent call last):
  File "C:\Users\Akira\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ui\view.py", line 414, in _scheduled_task
    await item.callback(interaction)
  File "C:\Users\Akira\PycharmProjects\helloWorld\buttonTest.py", line 42, in fourth_button_callback
    await interaction.response.send_message("You clicked the button!")
  File "C:\Users\Akira\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\interactions.py", line 765, in send_message
    raise InteractionResponded(self._parent)
discord.errors.InteractionResponded: This interaction has already been responded to before```

I see that its because it has responded once before that
#

need to rethink the code on that one

silver moat
#

The issue is that you are responding twice. You can edit the message with interaction.edit_original_response

#

instead of interaction.response.edit_message

royal spindle
mild sigil
#

hmm, edited the file but now I'm getting a new error

Traceback (most recent call last):
  File "C:\Users\Akira\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ui\view.py", line 414, in _scheduled_task
    await item.callback(interaction)
  File "C:\Users\Akira\PycharmProjects\helloWorld\buttonTest.py", line 41, in fourth_button_callback
    await interaction.edit_original_response(view=self, content="You clicked the button!")
  File "C:\Users\Akira\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\interactions.py", line 428, in edit_original_response
    data = await adapter.edit_original_interaction_response(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Akira\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\webhook\async_.py", line 215, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook```

Does the ```interaction.edit_original_response``` only allow for one argument?
#
    async def fourth_button_callback(self, button, interaction):
        for child in self.children:
            child.disabled = True
        await interaction.edit_original_response(view=self, content="You clicked the button!")```
silver moat
#

oops, it should've been interaction.message.edit

mild sigil
#

ok, the text is updating but I am getting this now:

#

Not getting any tracebacks for it so I assume it is maybe fine?

silver moat
#

Where did your await interaction.response.send_message("You clicked the sloth button!") go?

mild sigil
#

Looks like this:

#

Changes to this

#

so, it did the thing,

silver moat
#

well, basically, you need to respond to an interaction

#

if you are sending a message and editing a message, you would edit the message not as a response, and send the message as a response.
if you are just editing a message, then that should be the response.

mild sigil
#

so, my bot code looking like this:

async def button(ctx):
    await ctx.respond("Which did you complete?", view=MyView()) # Send a message with our View class that contains the button```

means it is looking to respond but their is nothing to respond to since I interacted with it already?
silver moat
#

well, buttons presses are also interactions

#

each time they are pressed, they should also be responded to.

mild sigil
#

ok, thank you for your help, I got it working for now

#
    async def fourth_button_callback(self, button, interaction):
        for child in self.children:
            child.disabled = True
        await interaction.message.edit(content="You clicked the sloth button!")
        await interaction.response.edit_message(view=self)```
proud mason
#

Saves you api calls and prevents ratelimits

#

Also faster

mild sigil
#

That definitely worked, thanks. If I wanted to call a function upon button press, would that be placed here or in the /slash command?

royal spindle
#

I receive this in console
You are on cooldown. Try again in 47.35s
<class 'discord.ext.commands.errors.CommandOnCooldown'>
In help command subclassed on commands.HelpCommand

but it sends No command called "..." found.

#

how does this work?
I need the error but it gives me cooldown error in the
async def on_help_command_error(self, ctx, error)
but it sends that message using
async def send_error_message(self, error)

#

I have this help command setup with all the other methods overridden but not shown here.

class MyHelp(commands.HelpCommand):
    def __init__(self):
        attrs = {
            'cooldown': commands.CooldownMapping.from_cooldown(1,                            60, commands.BucketType.member),
            'aliases': ['commands'],
        }
        super().__init__(command_attrs=attrs)

    async def on_help_command_error(self, ctx, error):
        print(error)
        print(type(error))
young bone
#

stay in one channel pls

#

@royal spindle

royal spindle
#

Ok.

royal spindle
young bone
#

I cannot help with this one, I always create a custome help command

proud mason
errant craneBOT
#

discord/ui/view.py line 556

self._views: dict[tuple[int, int | None, str], tuple[View, Item]] = {}```
proud mason
#

also i have no idea how it works, so you are out on your own

proud mason
# rose vapor same thing

what is phyner_guild_id ?
also try running the bot from the terminal rather than vscode. ive found that vscode sometimes hides the full traceback

proud mason
fervent cradle
#

I saw some bots using Postgresql+redis (aioredis) so what's the reason they use both ?? And should i have to do same to solve "x" problems ?

royal spindle
fervent cradle
#

So I accidentally perm deleted my bot's folder, and there were some slash commands registered. Is there any way to remove them from the bot?

fervent cradle
#

they were registered in the bot

#

(i want to delete the commands from the bot)

royal spindle
#

I called the disable_all_items() on the View but I cannot find the message to edit the View with.
I only have the message id.

proud mason
proud mason
proud mason
#

You installed py-cord right

#

Mhm

#

You must be having environment issues

#

Confirm that the python version is correct in vscode

#

Which python version do you have?

#

Then try python3.11 -m pip install py-cord

#

Not really

#

Oh uh

#

Try py -3.11 -m pip install py-cord

#

I don't use python on windows sorry lol

royal spindle
fervent cradle
#

And how can I impliment those setup to make improvements in my bot can you please elaborate?

obtuse vale
#

is there a simple way to allow only integers in discord.ui.InputText?

proud mason
proud mason
proud mason
fervent cradle
fervent cradle
obtuse vale
#

how do i make so only the the author of the slash command can use the select menu?

limber urchin
#

Compare the id of the interaction user to the author in your callback

hollow drum
#

Im trying to make a script that sends hello world to a webhook

webhook = discord.Webhook.from_url(webhook_url)

but i get this error : TypeError: Webhook.from_url() missing 1 required keyword-only argument: 'session'
How can i send "hello world" to a webhook?

stuck bough
#

what does it return if multiple user has same username when looking up by username

proud mason
buoyant mesa
#

hey i have made cogs system and done it according to category and how can i list the commands according to the name of cog

#

for eg if a cog name in utility then it displays only the commands created within the file

tough briar
#

does anyone else have problems with slash commands when using those in cogs?

winter condorBOT
proud mason
#

do you want this?

proud mason
tough briar
#

i tried the cogs out but atm i'm trying to use slash commands at a cog file.

If i'm using the slash command inside the start file from where i load my cogs in, there the slash command works.

But as soon as i put the slash command into a cog, it doesn't work anymore

proud mason
errant craneBOT
#

Here's the slash cog example.

proud mason
#

check that

buoyant mesa
proud mason
#

.guidee

#

.guide

winter condorBOT
proud mason
#

and that too

tough briar
proud mason
#

.rtfm bot.walk

proud mason
#

you have that ig

proud mason
tough briar
#

via the on_ready event

#

in a for loop with the files in a specific folder

proud mason
#

slash cmds internally rely on the on_connect event to register, which is fired before on_ready

tough briar
#

okay

buoyant mesa
#

hey isnt there anything like i get the cog and then get the commands of the cog

obtuse vale
proud mason
tough briar
proud mason
obtuse vale
proud mason
#

you will have to subclass view, override the init, accept the author and assign it to a self variable. check if interaction.author == self.author in the callback

#

and pass ctx.author while creating the view

dapper flare
#
    if data.startswith(b"\x89\x50\x4E\x47\x0D\x0A\x1A\x0A"):
       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: startswith first arg must be str or a tuple of str, not bytes

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

Traceback (most recent call last):``` help getting error
limber urchin
#

If you can't show your code we can't help you

dapper flare
# limber urchin If you can't show your code we can't help you
                        soup = BeautifulSoup(jsu["descriptions"][a]["descriptions"][6]["value"], 'html.parser')
                        img_tags = soup.find_all('img')
                        src_values = []
                        for img in img_tags:
                            src_values.append(img['src'])
                        if gname[1] == "True":
                            for x in src_values:
                                await ctx.guild.create_custom_emoji(name="example_emoji", image=x)```
proud mason
dapper flare
# proud mason full traceback please
Traceback (most recent call last):
  File "C:\Users\Siddharth\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 124, in wrapped
    ret = await coro(arg)
          ^^^^^^^^^^^^^^^
  File "C:\Users\Siddharth\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 980, in _invoke
    await self.callback(ctx, **kwargs)
  File "c:\Users\Siddharth\Desktop\code\steam_bot\main.py", line 144, in sell
    await ctx.guild.create_custom_emoji(name="example_emoji", image=x)
  File "C:\Users\Siddharth\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\guild.py", line 2747, in create_custom_emoji
    img = utils._bytes_to_base64_data(image)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Siddharth\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\utils.py", line 658, in _bytes_to_base64_data
    mime = _get_mime_type_for_image(data)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Siddharth\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\utils.py", line 644, in _get_mime_type_for_image
    if data.startswith(b"\x89\x50\x4E\x47\x0D\x0A\x1A\x0A"):
       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: startswith first arg must be str or a tuple of str, not bytes

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

Traceback (most recent call last):
  File "C:\Users\Siddharth\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\bot.py", line 1114, in invoke_application_command
    await ctx.command.invoke(ctx)
discord\commands\core.py", line 375, in invoke
    await injected(ctx)
  discord\commands\core.py", line 132, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: startswith first arg must be str or a tuple of str, not bytes```
#

the src_values list is like this ['https://steamcdn-a.akamaihd.net/apps/730/icons/econ/stickers/community02/just_trolling.fb233588789ce024c2edff140301948530fe3b67.png', 'https://steamcdn-a.akamaihd.net/apps/730/icons/econ/stickers/illuminate_capsule_01/cheongsam_2_holo.e0aca4521f3fbb5566e5ae34a08faa1dd723aae4.png']

#

help 😥

limber urchin
#
  1. The error tells you what's wrong
  2. You just revealed your db password
  3. Never use f-strings for sql queries
fervent cradle
#

By not available, thats saying it isnt online right

limber urchin
#

It means the connection failed. And you should always use parameterized queries unless you want your bot to be destroyed by sql injections

fervent cradle
limber urchin
#

Nope

proud mason
#

wth would "an SQL queriy outside of the python" even mean lmao

limber urchin
#

Whatever library you're using has a built-in way to parse parameters into your query. Use that instead of mergeing them to the string yourself

fervent cradle
obtuse vale
#

is psycopg2 supported by asyncio and pycord?

quick sand
#

Is there a preferred way to 'cache' messages?
I'm using fetch_message recursively if a message has a reference, and those API hits stack up quickly. I'm looking for a way to cache these, maybe with LRU or something else

proud mason
#

It's better

young bone
#

With fetch you do every time a API call and you will get a rate limit

proud mason
fallow hawk
#

any way to stop a button from responding? but not give the interaction failed error?

fervent cradle
#

I think you can use 'None', not sure tbh

fallow hawk
fallow hawk
fervent cradle
#

Note that it won't disable the button, just won't do anything (saying again im not sure)

white steeple
#

I found this helpful resource https://guide.pycord.dev/extensions/commands/help-command for making pretty help commands. It only mentions prefixed commands though, so I'm wondering if there's a way to turn the help command into a slash command.

Pycord's commands extension comes with a built-in help command. In this guide, we will take a look at them as well as learn how to create your own. Let's dive in!

uneven beacon
#

how can i check what voice a specific person is in?

proud mason
#

.rtfm member.voice

winter condorBOT
proud mason
#

.rtfm voicestate

alpine kernel
#

mmm another dumb database question, is it best practice to create a new connection per command? or do you establish a connection on initialization and ensure it's still up each command?

#

researched it a bit and i think i'm going with the former unless someone has better insight heh

gleaming falcon
#

UI question -- if you need to validate a numeric-ish input from a Modal (I know inputs are strings, but assume they will be cast to floats), is there a good way to display that to the user? Just in the message the view is attached to?

limber urchin
alpine kernel
#

sqlite likely at max 20 commands in a minute?

limber urchin
#

For sqlite you can keep a persistent connection

#

if you're using a server based db it's better to just use a connection pool

alpine kernel
#

ok yeah it's just going to be a local db on a small project

alpine kernel
#

mmm is there a way to pass data in a cog to a check? i cant send self.ok_channels because self isnt defined in the decorator

#

like trying to have a dynamic list of acceptable command channels
@is_command_channel(channels)

#

feels like i need to have a global variable to pass, doesnt feel right =T

silver moat
#

you can do something like

class Foo:
  channels = None

  def __init__(self, ...):
    channels = channels_list

  @bar(channels)
  async def spam(self):
    ...
alpine kernel
#

yeah that could do

#

that would like make channels static for the class right?

silver moat
#

yup

alpine kernel
#

how would a function know that it's a static variable vs creating a function scope variable? if i were to update the data in a function?

#

or is the convention never to assign it anywhere accept in init?

#

sorry this is python stuff not pycord stuff heh

silver moat
#

or self.__class__.static_attribute

alpine kernel
#

ok, and you didnt do that in your snippet just as an example right? or is it a special case? sorry, and thanks

silver moat
alpine kernel
#

np thanks a bunch i'll figure the rest out 🙂

alpine kernel
#

still having issues, I think it has to do with the check being set up the time it's defined and at that time the data is None, i'm having no issues accessing the static anywhere in the class but still blows up when the check is run =T

#

I'll probably take a break, need to go play board games and check back with a fresh head

#

ok, last minute tooling around, just doesnt work because the check is in a separate file, works fine if the check is in the same file as the cog.
i guess I'd have to import the cog's class and access the static variable like that? seems wonky but wouldnt be the first time

silver moat
alpine kernel
#

yeah it works in the same file, but I think i'm doing something dumb

#

like this works

import discord
from discord.ext import commands


#from checks.IsCommandChannel import is_command_channel, NotCommandChannel

class NotCommandChannel(commands.CheckFailure):
    pass

def is_command_channel():
    async def predicate(ctx):
        #if ctx.channel_id in MyCog.CONFIG[str(ctx.guild.id)]['command_channels']:
        if ctx.channel_id in MyCog.CONFIG['command_channels']:
            return True
        raise NotCommandChannel()
    return commands.check(predicate)
        

class MyCog(commands.Cog):
    CONFIG = None
    
    def __init__(self, bot):
        self.bot = bot
        MyCog.CONFIG = {'command_channels': 12345678910}
    
    @commands.slash_command(name = "hello", description = "Say hello to the bot")
    @is_command_channel()
    async def hello(ctx):
        await ctx.respond("Hey!")
    
    
    async def cog_command_error(self, ctx: commands.Context, error: commands.CommandError):
        if isinstance(error, NotCommandChannel):
            await ctx.send_response(content=f"You cant perform that command in this channel, {ctx.command} - {ctx.selected_options}")
        else:
            raise error
  
#

but i havent been able to put the check in another file and then do

@is_command_channel(CONFIG)

just says config is none when the check is ran

#

i looked up some stackoverflow stuff suggesting i wrap the decorator but it's already being wrapped and i think pycord is looking for specific stuff from it and it's making my head spin trying to work from that angle heh

alpine kernel
#

looks like I'd have to do something to recompile the check code at runtime which looks pretty technical heh

undone falcon
#

How do you create forms with pycord ?

errant craneBOT
#

Here's the modal dialogs example.

undone falcon
#

ooh thanks !

undone falcon
#

I get this error when sending a view: Forbidden: 403 Forbidden (error code: 50001): Missing Access
NoneType: None

#
class MyView(discord.ui.View):
    @discord.ui.button(label="Modal Test", style=discord.ButtonStyle.primary)
    async def button_callback(
        self, button: discord.ui.Button, interaction: discord.Interaction
    ):
        modal = MyModal(title="Modal Triggered from Button")
        await interaction.response.send_modal(modal)

    @discord.ui.select(
        placeholder="Pick Your Modal",
        min_values=1,
        max_values=1,
        options=[
            discord.SelectOption(
                label="First Modal", description="Shows the first modal"
            ),
            discord.SelectOption(
                label="Second Modal", description="Shows the second modal"
            ),
        ],
    )
    async def select_callback(
        self, select: discord.ui.Select, interaction: discord.Interaction
    ):
        modal = MyModal(title="Temporary Title")
        modal.title = select.values[0]
        await interaction.response.send_modal(modal)


class RecurrentRoleCog(WriteCog):
    def __init__(self, bot):
        super().__init__(bot)
        
    @slash_command(guild_ids=guildIds, description="Add a new recurrent time role")    
    @discord.default_permissions(manage_roles=True)
    async def add_recurrent_time_role(self, ctx: discord.ApplicationContext):
        view = MyView()
        await ctx.send("Click Button, Receive Modal", view=view)
#

Do you know what can be causing it ?

#

this is code from the exemple on the git

young bone
undone falcon
#

ooh the .repond fixed it

#

thanks ! But what intent do you need ?

young bone
#

Im not really sure if you need intents for this

buoyant mesa
#

hey how do i use walk slash command through the discord.bot thing

#

i meant cog thing

silver moat
#

?

proud mason
errant craneBOT
#

discord/ext/commands/help.py line 1004

async def send_pages(self):```
proud mason
#

And also register the cmd as a Slash cmd

white steeple
#

Thanks

blissful spear
#

Is there a way to get an event if the user clicks cancel in a modal?

proud mason
blissful spear
#

:/ really stupid if you have a command with a max_concurrency...
But thanks :D will do it via the timeout

grizzled sentinel
#

Is Thread.total_messages_sent an estimation and cached or a real value that is sent by discord? I having some troubles were it is not incrementing.

boreal abyss
#

await ctx.respond(embed=em, ephemeral=True)
?? doesnt work if anyone can help me would be lovely

winter condorBOT
boreal abyss
proud mason
boreal abyss
#

pip?]

#

pip 22.3.1 from C:\Users\

#

await ctx.send(embed=em, ephemeral=True)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Messageable.send() got an unexpected keyword argument 'ephemeral'

#

its mabey just a respond?

#

like ctx.respond instead

#

nvm its a respond already

full basin
#

Providing different code than the error

#

Smart

young bone
proud mason
young bone
proud mason
echo egret
#

is there a simple way to schedule a coroutine to a certain time (eg 5min) ?

#

i've searched but haven't found anything convenient

proud mason
echo egret
#

nope just once

proud mason
#

I would create a function that accepts a time to wait in seconds and a coroutine. In the function, i would sleep for the time and then await the coroutine

echo egret
#

oh

#

i thought it wasn't a good way to do it but ig it's fine

echo egret
#

(sorry for the dumb questions but i wanna make sure)

echo egret
#

well it does, i will search further by myself, thx for your help

proud mason
uneven beacon
#

how can i make a member select menu?

young bone
uneven beacon
silver moat
#

add, not select

uneven beacon
#

yeah you`re right

#

still one tho

silver moat
#

then is that a select menu?

uneven beacon
#

yep

silver moat
#

Are you sure that the choices that someone wants to select from, only contain one person?

uneven beacon
#

uhhh

#

i want to make a select menu that contains all the members in a server

young bone
#

app_commands?

#

you would have to check it at your own

#

else no

#

but it would be interaction.user

undone falcon
#

I disable all button, but they dont go gray, they stop working tho as I want

#

How would I make sure they go disable

silver moat
undone falcon
#

oooh I see

#

thanks !

uneven beacon
#

another stupid question
how can i update the permissions of a voice channel im in?

undone falcon
silver moat
silver moat
undone falcon
#

in the init of the view

#

all button one after the others

silver moat
#

hmm ic, so it wasn't a child of the view when the view was constructed.

undone falcon
#
class MyView(discord.ui.View):
    
    def __init__(self):
        super().__init__(
            ButtonCallModal(
                DateModal(
                    ... ,
                    title="Start date form", update_co=self.on_update
                ),
                label="Select start date (default = now)", style=discord.ButtonStyle.primary
            ),
            ButtonCallModal(
                TimeModal(
              ...,
                    title="Start time form", update_co=self.on_update
                ),
                label="Select start time (default = 00h00:00s )", style=discord.ButtonStyle.primary
            ),
            ButtonCallModal(
                DeltaModal(
              ...,
                    title="Time interval form", update_co=self.on_update
                ),
                label="Select time interval", style=discord.ButtonStyle.primary
            ),
            discord.ui.Button(label="Approve", style=discord.ButtonStyle.success, disabled=True, row=2)
        )
        self.interaction = None
        self.data = {}
        self.children[3].callback = self.approve_callback
undone falcon
#

for init

#

it was a child of the view when constructed !

silver moat
#

could you print the value of self.children in any one of the callbacks??

undone falcon
#

yess !

undone falcon
# silver moat could you print the value of `self.children` in any one of the callbacks??

[<ButtonCallModal style=<ButtonStyle.primary: 1> url=None disabled=False label='Select start date (default = now)' emoji=None row=1>, <ButtonCallModal style=<ButtonStyle.primary: 1> url=None disabled=False label='Select start time (default = 00h00:00s )' emoji=None row=1>, <ButtonCallModal style=<ButtonStyle.primary: 1> url=None disabled=False label='Select time interval' emoji=None row=1>, <Button style=<ButtonStyle.success: 3> url=None disabled=False label='Approve' emoji=None row=2>]

#

there is the 4 buttons

#

plus that approve button start as disable, and is enable when all the data is set

#

but I cant redisable it

silver moat
#

try using ```py
for child in self.children:
child.disabled = True

instead of `self.disable_all_items()`
undone falcon
#

it is possible you can only disable one time a button ?

silver moat
undone falcon
#

[<ButtonCallModal style=<ButtonStyle.primary: 1> url=None disabled=False label='Select start date' emoji=None row=1>, <ButtonCallModal style=<ButtonStyle.primary: 1> url=None disabled=False label='Select start time (default = 00h00:00s )' emoji=None row=1>, <ButtonCallModal style=<ButtonStyle.primary: 1> url=None disabled=False label='Select time interval' emoji=None row=1>, <Button style=<ButtonStyle.success: 3> url=None disabled=False label='Approve' emoji=None row=2>] [<ButtonCallModal style=<ButtonStyle.primary: 1> url=None disabled=True label='Select start date' emoji=None row=1>, <ButtonCallModal style=<ButtonStyle.primary: 1> url=None disabled=True label='Select start time (default = 00h00:00s )' emoji=None row=1>, <ButtonCallModal style=<ButtonStyle.primary: 1> url=None disabled=True label='Select time interval' emoji=None row=1>, <Button style=<ButtonStyle.success: 3> url=None disabled=False label='Approve' emoji=None row=2>]

#

ooh yeah, he dose not get disable

#

it is still as false

#

for last button

silver moat
#

what is self.on_update()?

undone falcon
#

it just update a embed

#
async def on_update(self):
        self.update_data()
        year = self.data.get("year")
        month = self.data.get("month")
        day = self.data.get("day")
        hours = self.data.get("hours")
        minutes = self.data.get("minutes")
        seconds = self.data.get("seconds")
        days_delta = self.data.get("days_delta")
        hours_delta = self.data.get("hours_delta")
        minutes_delta = self.data.get("minutes_delta")
        seconds_delta = self.data.get("seconds_delta")
        
        current_date = None
        if year is not None and month is not None and day is not None:
            current_date = date(year=year, month=month, day=day)
        current_time = timedelta(seconds=0)
        if hours is not None and minutes is not None and seconds is not None:
            current_time = timedelta(hours=hours, minutes=minutes, seconds=seconds)
        current_interval = None
        if days_delta is not None and hours_delta is not None and minutes_delta is not None and seconds_delta is not None:
            current_interval = timedelta(days=days_delta, hours=hours_delta, minutes=minutes_delta, seconds=seconds_delta)
            
        if current_date is not None and current_time is not None and current_interval is not None:
            self.children[3].disabled = False
        embed = discord.Embed(title="Create a reccurent time role",
                              description=f"Use the button to set information \n Current value: **delete the role __ starting at {current_date} at {current_time} each {current_interval}**")
        embed.set_footer(text="This is a premium feature. Server under 200 member can still use it")
        await self.interaction.edit_original_response(embed=embed, view=self)
#

oooh, I see the problem, I put disable at false in that method 😄

#

I am dumb

undone falcon
uneven beacon
silver moat
uneven beacon
#

i mean like i did this
voice = ctx.author.voice

#

i know the voice

proud mason
uneven beacon
green hinge
#

Can I only reopen the modal via a button or can I have it reopen automatically after 5 seconds?

class AddSpot(discord.ui.Modal):
    def __init__(self, bot, interaction):
        super().__init__(
          title = "Trage deinen Spot ein",
          timeout=300,
          )

        self.bot = bot
        self.interaction = interaction

        self.user = discord.ui.InputText(
          label="Spot eintragen",
          min_length=2,
          max_length=30,
          required=True,
          placeholder="Trage deinen Spot im Format 100:100 hier ein"
          )
        self.add_item(self.user)

    async def callback(self, interaction: discord.Interaction) -> None:
        spot = self.user.value
        pattern_spot = re.compile(r'^([1-9]\d{0,1}|200):([1-9]\d{0,1}|200)$')
        if not pattern_spot.match(spot):
            embed = discord.Embed(
                title="Fehler",
                description="Spot muss im Format '100:100' eingegeben werden. Der Maximalwert beträgt '200:200'"
            )
            await interaction.response.send_message(embed=embed)
            await interaction.response.send_modal(AddSpot(self.bot, interaction.channel))
        self.view.add_item(AngelArt(self.bot))
        await interaction.response.edit_message(view=self.view)```
proud mason
uneven beacon
proud mason
#

pretty sure you added () after voice.channel

uneven beacon
#

ah i saw my mistake

proud mason
#

lol

uneven beacon
green hinge
# proud mason can you please elaborate

I open this modal. A text is entered there and it is checked for the format.
If the required format was not entered, a message appears that the format was wrong and then the modal should open again to be able to enter the value again.

proud mason
proud mason
#

Although you can send a message with a button that sends a modal

#

smart to have it recursive like you did

green hinge
green hinge
# proud mason np 👍

How can I fix the error?

AttributeError: 'AddSpot' object has no attribute 'view'```
```py
class AddSpot(discord.ui.Modal):
    def __init__(self, bot, interaction):
        super().__init__(
          title = "Trage deinen Spot ein",
          timeout=300,
          )

        self.bot = bot
        self.interaction = interaction

        self.user = discord.ui.InputText(
          label="Spot eintragen",
          min_length=2,
          max_length=7,
          required=True,
          placeholder="Trage deinen Spot im Format 100:100 hier ein"
          )
        self.add_item(self.user)

    async def callback(self, interaction: discord.Interaction) -> None:
        spot = self.user.value
        pattern_spot = re.compile(r'^([1-9]\d{0,1}|200):([1-9]\d{0,1}|200)$')
        if not pattern_spot.match(spot):
            embed = discord.Embed(title="Fehler", 
                                description=f"Spot muss im Format '100:100' eingegeben werden. Der Maximalwert beträgt '200:200'", 
                                color=discord.Color.blurple()
                                )
            await interaction.response.send_message(embed=embed, view=ModalAgain(self.bot))
        self.view.add_item(AngelArt(self.bot))
        await interaction.response.edit_message(view=self.view)```
full basin
#

Self is already your view

silver moat
proud mason
full basin
green hinge
silver moat
#

where is self.view being created?

safe stirrup
#

I'm preparing to ditch the commands module in favor of the new integration for slash commands, is there anything I should be aware of?

#

Other than that prefixes won't work anymore

silver moat
#

otherwise have fun

safe stirrup
#

Fair, just didn't know if there was a standard boilerplate of "while you're fixing the code, don't do this"

green hinge
# silver moat where is `self.view` being created?

Here:

class Setup_SpotInsert(commands.Cog):
  def __init__(self, bot):
    self.bot = bot
    self.persistent_views_added = False

  @commands.Cog.listener()
  async def on_ready(self):
    if not self.persistent_views_added:
      self.bot.add_view(InsertSpot(self.bot))
      self.persistent_views_added = True

  @slash_command(description="Spot System einrichten")
  async def setup_spotinsert(self, ctx):
    embed = discord.Embed(title=f'Herzlich Willkommen!',
                          description=f"""Wenn du einen Spot eintragen möchtest drücke bitte auf den "📃 Spot eintragen" Button!\n Anschließend wirst du durch den Prozess geführt.""",
                          color=ORANGE)
    embed.set_thumbnail(url=f"{ctx.guild.icon}")
    await ctx.respond(embed=embed, view=InsertSpot(self.bot))```
proud mason
safe stirrup
#

I'm reading the core api, is @bot.slash_command() necessary? I thought it was just bot.command for the core api

full basin
#

If you're using a discord.Bot instance, bot.command will get registered as a slash command, otherwise it'll be a prefixed command if you're using commands.Bot instance

safe stirrup
#

Straight up, is there even an issue with still using the commands module? I guess I heard it was getting deprecated but I never confirmed this.

silver moat
safe stirrup
#

Core doesn't have permissions checks? O: oh.

#

Suppose I could code my own but that's like, overhead and stuff...eh. Thanks for the help, maybe I'll hold off and just use slash_command.

proud mason
#

i mean you can do bridge commands

#

which are cool

safe stirrup
#

Oh. I'll have to look into it O:

proud mason
#

.guide

winter condorBOT
proud mason
#

pretty cool too

safe stirrup
#

I mean, I already have the bot made, just trying to figure out what I want the next version to be. Thanks though, I'll check it out :D

#

Right now I'm integrating openai, which is fun.

proud mason
#

nice

#

from what i remember, openai uses requests library, so you might want to wrap its function calls inside asyncio.to_thread

safe stirrup
#

That's...a really good idea, actually. I'm utilizing both GPT-3 and the content filtering endpoints so 🤔

uneven beacon
#

can anyone tell what am i doing wrong?
its supposed to be a temp vc but it doesnt make a vc

uneven beacon
proud mason
#

never heard of it before

uneven beacon
proud mason
safe stirrup
#

That's not how cog listeners work :l

proud mason
#

you can specify a name in the decorator tho

uneven beacon
chrome mural
#

Can I get an int value instead of a string?

uneven beacon
young bone
#

?tag file

obtuse juncoBOT
#

dynoError No tag file found.

limber urchin
safe stirrup
#

Cog listeners "listen" for an event, in the most bastardized way I can put it.

proud mason
#

.localfile

#

waa

#

one sec

uneven beacon
novel jay
#

How do i make my bot start "typing" in a channel? I remember using async with ctx.typing(): but is there any better way? my bot does not support slash commands as the client doesn't want slash commands

limber urchin
safe stirrup
safe stirrup
#

API reference is your best friend.

proud mason
#

?tag localfile

obtuse juncoBOT
#
f = discord.File("some_file_path", filename="image.png")
e = discord.Embed()
e.set_image(url="attachment://image.png")
await messagable.send(file=f, embed=e)```
safe stirrup
limber urchin
novel jay
#

its useful to know how to program before using a lib like pycord

uneven beacon
safe stirrup
#

I didn't say it wasn't. I said it wasn't helpful. :D

proud mason
novel jay
#

alright thx

waxen whale
safe stirrup
#

I have the API reference bookmarked for a reason. :P

waxen whale
limber urchin
#

It doesn't make sense to use a complex library without knowing the basics first. It's like trying to play a really difficult song on the guitar without knowing the basic techniques first.

safe stirrup
#

It does if you're a pull stack developer.

waxen whale
uneven beacon
spare juniper
#

ask bill wurtz to voice it for you

silver moat
real snow
#

hey!
im new to pycord
i was just wondering how can i use move_to in an event?

async def on_voice_state_update(member,ctx):
await member.move_to(temp)

it gives me an error
'voice' object has no attribute 'move_to'

limber urchin
#

Read the docs, those are not the parameters for that event

real snow
limber urchin
#

Read the docs

real snow
#

i saw it
thanks for the help

chrome skiff
#

what libary should i use for flask discord oauth2?

silver moat
chrome skiff
#

why quart

#

some say flask is better

silver moat
#

quart implements asyncio

young bone
chrome skiff
obtuse juncoBOT
#
Tags (99)

youtube, xy, wavelink, virtualembed, usercmd, unofficialguide, um_cmds, tryitandsee, tokens, token, timer, tias, tcr, tca, tags, tagrules, swasvid, subcommands, sslfix, sqli, solved, snowflake, slashcommandmention, rie, restartcmd, requests, replit-install, replit, removeall, pythonserver, python, paste, partial_objects, oracle, option, oop, official, objects, notpycord, norepl, nojson, nohelp, nohello, name-conventions, mybot, msgcmd, mongodb, modal, missing_access, message-content, lp, localfile, learnpython, json, intents, install_slash, install_git, install, inline-fields, importerror, idw, ide, how2sql, helpgist, guide, getalpha, get_x, get-help, fork, forbidden, exception, examples, ex, ephemeral, eh, docs, discord.app, discord.Bot, deploy, commandnoshow, colors, codeexamples, codeblock, closing, client, buttons2, buttonlimit, bridge, breaking-changes, botvar, bitwise, asset, applicationcommands-registration-delay, announcement_channel_options, aiohttp, activedevbadge, Woc, Timestamps, DMChannel

#

The library name is py-cord not pycord

boreal abyss
#

view=like() how to add dislike

grizzled sentinel
harsh canyon
#

how do i determine if a member has a certain permission? i coudnt find anything in the docs, copilot suggested ctx.author.has_permission("permission") but that didnt work either

silver moat
harsh canyon
#

ty

proud mason
harsh canyon
#

bridge.bridge_command()
async def play(self, ctx, *video):
this command works as a prefixed command(*args for spaced arguments) but doesnt as a slash command i think because having infinite args for a slash command doesnt make sense(error: discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: Voice.play() got an unexpected keyword argument 'video') is there a easy way around this or is the best option to just not use bridge in this case

proud mason
#

Also, what is voice.play?

#

It doesn't seem to be related to bridge cmds at all

harsh canyon
#

its a bridge.command in a cog called voice

harsh canyon
proud mason
#

Can you show code and full error traceback

proud mason
#

.rtfm greedy

harsh canyon
#

relevent code

    @bridge.bridge_command()
    async def play(self, ctx, *video):
        args = list(video)
        channel = ""
        for arg in range(len(args)-1):
            if args[arg] == "-channel" or args[arg] == "-c":
                channel = discord.utils.get(ctx.guild.channels, name=args.pop(arg+1)).id
                args.pop(arg)
                break

error:

#

Ignoring exception in command play:
Traceback (most recent call last):
File "/home/ion/.local/lib/python3.11/site-packages/discord/commands/core.py", line 124, in wrapped
ret = await coro(arg)
^^^^^^^^^^^^^^^
File "/home/ion/.local/lib/python3.11/site-packages/discord/commands/core.py", line 976, in _invoke
await self.callback(self.cog, ctx, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Voice.play() got an unexpected keyword argument 'video'

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

Traceback (most recent call last):
File "/home/ion/.local/lib/python3.11/site-packages/discord/bot.py", line 1114, in invoke_application_command
await ctx.command.invoke(ctx)
File "/home/ion/.local/lib/python3.11/site-packages/discord/commands/core.py", line 375, in invoke
await injected(ctx)
File "/home/ion/.local/lib/python3.11/site-packages/discord/commands/core.py", line 132, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: Voice.play() got an unexpected keyword argument 'video'

proud mason
#

Also typehint video as str

harsh canyon
#

whats the difference between *video and *,video?

proud mason
fair ledge
#

Hello there!
Is is possible to build a message or a modal, where both buttons and textinputfields are present? In the Modal I can insert Textinputfields, but no buttons and in a message it is vice versa, so that I can not insert Inputtextfields in a view. Somebody knows how to implement this? 😦

grizzled sentinel
#

Discord only alows text input as of now. I think they are working on an update to allow buttons.

royal spindle
#
Traceback (most recent call last):
  File "/home/ec2-user/.local/lib/python3.9/site-packages/discord/client.py", line 377, in _run_event
    await coro(*args, **kwargs)
  File "/home/ec2-user/.local/lib/python3.9/site-packages/discord/bot.py", line 1164, in on_connect
    await self.sync_commands()
  File "/home/ec2-user/.local/lib/python3.9/site-packages/discord/bot.py", line 719, in sync_commands
    registered_commands = await self.register_commands(
  File "/home/ec2-user/.local/lib/python3.9/site-packages/discord/bot.py", line 599, in register_commands
    registered = await register("bulk", data, _log=False)
  File "/home/ec2-user/.local/lib/python3.9/site-packages/discord/http.py", line 366, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In options.1: Required options must be placed before non-required options

How do I check which bridge command this is?

real snow
#

how can i fix this? ( its a temp vc event )
1-the delete part is broken
2-i want to make the vc get deleted when it hase 0 members in it

grizzled sentinel
royal spindle
#

Only this Ignoring exception in on_connect

grizzled sentinel
#

I guess look through all of your command functions and make sure all required options are before optional options.

royal spindle
grizzled sentinel
#

.rtfm guildchannel.delete

winter condorBOT
grizzled sentinel
grizzled sentinel
real snow
#

i read the article
but it doesnt tell a way to use it..

grizzled sentinel
# real snow ...

That would delete the guild. You want to delete the channel.
chan is a guildChannel object. You need to call delete on it.

grizzled sentinel
real snow
royal spindle
#
Ignoring exception in on_connect
Traceback (most recent call last):
  File "/home/ec2-user/.local/lib/python3.9/site-packages/discord/client.py", line 377, in _run_event
    await coro(*args, **kwargs)
  File "/home/ec2-user/.local/lib/python3.9/site-packages/discord/bot.py", line 1164, in on_connect
    await self.sync_commands()
  File "/home/ec2-user/.local/lib/python3.9/site-packages/discord/bot.py", line 719, in sync_commands
    registered_commands = await self.register_commands(
  File "/home/ec2-user/.local/lib/python3.9/site-packages/discord/bot.py", line 599, in register_commands
    registered = await register("bulk", data, _log=False)
  File "/home/ec2-user/.local/lib/python3.9/site-packages/discord/http.py", line 366, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In 64: Application command names must be unique
#

now what's this 64, Is this the command serial number?

grizzled sentinel
grizzled sentinel
real snow
grizzled sentinel
#

That would make the most sense so you could compare it to 0.
But a property is basically a variable for a class instance. You can use it in an if statement or pass it to a function and so on.

grizzled sentinel
royal spindle
#

and I'm using @bridge.bridge_command

real snow
grizzled sentinel
#

This includes properties.

fair ledge
grizzled sentinel
# fair ledge ok, thx. 🙂 So is it possible to use text input fields anywhere else than in a m...

Unfortunately no
Buttons/select menus can be used on a message
Text input can be used in a model
Options, autocomplete, "text input" (as in the argument takes a string) can be used in a command.

I think discord is working on adding more features to components but we have not got a major update in a few months relating to components so I'm not sure how long you will have to wait.

Trust me I am waiting for some of these features on my bot as well.

proud mason
real snow
#

hey
i made a temp vc event but i cant make it to delete the channels it has made
it doesnt even give any errors

tiny hearth
#

Hey, how can I deafen the bot when it joins a voice channel?

loud holly
#

Say you send view1 ephemerally once you click it, it'll send in view2 ephemerally too, I have noticed that once view1 gets timed out, view2 will stop interacting, is this an intended cause?

uneven beacon
#

bruh why this isnt working

full basin
#

.rtfm guild.clone

winter condorBOT
#

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

full basin
#

Cause it doesn't exist? Xdnt?

full basin
uneven beacon
#

bruh

uneven beacon
#

i just want to clone a channel...

full basin
#

I mean you just have to create another channel with the same name and permissions

silver moat
#

.rtfm channel.clone

full basin
uneven beacon
full basin
#

If you can't read the embed, that's not my problem

uneven beacon
#

i did but i didnt understand it
maybe a sample would help?.....

silver moat
#

.rtfm context.channel

royal spindle
#

I've used bridge commands

open tusk
#

How can I edit a button if there are multiple instances of ToggleButton in my view?

class ToggleButton(discord.ui.Button):
    def __init__(self, label: str, value: bool, emoji: str or None):
        super().__init__(
            label=label,
            style=discord.ButtonStyle.red if value else discord.ButtonStyle.green,
            emoji=emoji
        )
        self.value = value

    async def callback(self, interaction: discord.Interaction):
        # change the button's style
        ...
limber urchin
open tusk
limber urchin
#

yes it does

real snow
#

but i dont think that solves my issue

full basin
#

You need to edit the message and pass the view again. It doesn't magically update

full basin
#

It's member, before, after

#

.rtfm on_voice_state_update

limber urchin
open tusk
real snow
limber urchin
real snow
#

i changed ctx with member now it doesnt even move / create the vc

full basin
open tusk
tiny hearth
#

.rtfm self_deafen

winter condorBOT
#

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

tiny hearth
#

.rtfm self_deaf

winter condorBOT
loud holly
novel jay
#

Does adding more shards to a bot require a restart?

proud mason
novel jay
#

alright good

limber urchin
#

?

#

increase the timeout in the constructor?

rose moon
limber urchin
#

Then you need to get a card, or deal with using crappy hosts

fervent cradle
#

Freinds?

#

Freinds parents?

#

All probably have cards u could use

rose moon
#

there are only card that u can only use in algeria and no other countries

fervent cradle
rose moon
limber urchin
#

A single chip computer that's out of stock basically everywhere

fervent cradle
#

oh rip

limber urchin
#

or find a way to bypass your restrictions

rose moon
limber urchin
#

🤷‍♂️

rose moon
limber urchin
#

replit

fervent cradle
#

I know one but it does have limitations

rose moon
limber urchin
#

All free hosts are going to have limitations

#

they're free for a reason

fervent cradle
#

google discloud, I really don't know how good is it compared to other free ones but it's alright

rose moon
#

there are discloud :0

fervent cradle
#

is you're bot public or for one server

rose moon
#

i was parterned with a discord server for free hosting

#

and now they canceled the deal

#

now im broke ;-;

fervent cradle
limber urchin
#

your*

rose moon
#

i was using a host from a parterned servr

#

now they canceled the deal

limber urchin
#

and you'll probably struggle finding a free host that can handle more than 1k servers

fervent cradle
limber urchin
fervent cradle
#

idk if discloud going to handle that but sure

limber urchin
rose moon
#

nah its good

#

100 mb ram 🙂

#

👍

limber urchin
#

Oh god

#

Good luck with that

fervent cradle
#

I haven't used it much and idk what specs are good

rose moon
#

@limber urchin

#

you have credit card right?

limber urchin
#

yes

rose moon
#

means you have azure right?

limber urchin
#

no?

rose moon
#

google cloud?

limber urchin
#

no

rose moon
#

dang it

#

you can have free rdp if you verify an azure account

#

you cold host bot with it but no credit card :0

full basin
#

bot.guilds returns a list of the guilds the bot is in

harsh canyon
#

[tls @ 0x562f44513cc0] Error in the pull function.
[https @ 0x562f445115c0] Will reconnect at 3014640 in 0 second(s), error=Input/output error.

#

is this a pycord error?

#

just randomly happens to my bot

#

every ~10 minuts

full basin
#

No

fervent cradle
#

how do i delete a message that was in dms and i know the id?

solar vortex
#

Is there a way to ephemerally respond to an on_raw_reaction_add()/RawReactionActionEvent?

gleaming falcon
#

Unfortunately not, since ephemeral messages are based on interactions (e.g. slash commands, buttons, etc)

solar vortex
#

Thanks

#

I just didn't know whether a reaction counted as an interaction.

meager heron
#

How do I add a check to a cog?

alpine kernel
#

or is it a check for all commands?

meager heron
#

I know how to add a check to an individual command. I've read that it's possible to do a "cog-wide" check

meager heron
alpine kernel
#

hmm yea, it's clear from the documentation for a bot, but cant do self on the check

meager heron
#

I did find Cog.cog_check, but I'm wondering if there's anything like a Cog.add_check type feature

alpine kernel
#

like dynamic checking?

meager heron
#

Not really. Same as Bot.add_check, only scoped to individual cogs

#

It might be possible, though, for me to just do self.cog_check = commands.guild_only (or whatever individual check I want)

alpine kernel
#

oh you'd do self.cog_check(guild_only) right?

#

not too experienced to know if a check IS an commands.Context though but that should be a quick check on a test

meager heron
#

I'll play around with it in a bit

#

It looks to me like you have to implement it yourself, but I suppose I could be misreading it

alpine kernel
#

oh yeah that makes sense you just implement the function in your cog

#

it's like capturing check errors, but i guess you can only have one cog_check function

zinc cloak
#

Is there a limit on the total amount of slash commands you can have on a discord bot?

silver moat
# zinc cloak Is there a limit on the total amount of slash commands you can have on a discord...

You can have 100 global 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 (because every command would have an average of 6.4 characters).

You can also multiply this number by two if you register the bot's commands in every guild as guild commands.

errant craneBOT
#

Here's the slash groups example.

zinc cloak
errant craneBOT
#

Here's the slash cog groups example.

zinc cloak
#

Awesome!

#

Thx!

safe stirrup
#

Doth bridge have a commandnotfound handler

rough roseBOT
#

You need to wrap the code into a code block.

zinc cloak
safe stirrup
#

A response message...telling you that you need to wrap your code in a code block.

safe stirrup
#

A support bot...

zinc cloak
#

Does it just straight up run code?

safe stirrup
#

No

zinc cloak
#

lol

umbral island
#

is there an event that will listen for the trigger of any other event? Im looking for a simple way to keep track of how often my bot is "detecting" something with a listener, other than adding a function to each command that writes the count data to a file.

#

len(bot.guilds)
bot is your client object.

fervent cradle
#

Can I define how long a modal's text input must be?

umbral island
proud mason
#

did i interpret your question correctly? or did you mean something else?

umbral island
#

wait

proud mason
umbral island
#

yeah just realized that XD

proud mason
#

😂

#

brb ill just check if this is possible

umbral island
#

okii

proud mason
#

it's the simplest way to implement

umbral island
#

this looks perfect, ill give it a go

proud mason
#

Although it has almost all the events, so filter out the ones you want

umbral island
#

I want all! haha

proud mason
#

lmao alr

umbral island
# proud mason lmao alr

So im not sure if im implementing this properly? Could you explain the proper way to use this?

My attempt:

@commands.Cog.listener()
    async def on_socket_event_type(on_presence_update):
        try:
            try:
                with open("interaction_count") as e:
                    num = int(e.read())
            except:
                num = 0            
            num = num + 1           
            with open("interaction_count", "w") as f:
                f.write(f"{num}")
        except:
            print(f"Failed to count this interaction!\n\n{traceback.format_exc()}")```

Error:
```TypeError: Listeners.on_socket_event_type() takes 1 positional argument but 2 were given
Ignoring exception in on_socket_event_type
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.11/site-packages/discord/client.py", line 377, in _run_event
    await coro(*args, **kwargs)```
proud mason
umbral island
#

ahh that would make sense

proud mason
#

so smth like async def on_socket_event_type(self, event_type: str):

#

also, dont use a text file. use a database

umbral island
#

I see, that makes a lot more sense

umbral island
proud mason
#

i suggest sqlite. dont use txt or json

umbral island
# proud mason i suggest sqlite. dont use txt or json

Even more odd.. ive completely removed the on_socket_event_type yet it still continues to trigger this errored event somehow 🤔 there's definitely not multiple sessions running so i dont even know where its pulling this error from now... time to do some digging

#

I even attempting using an old backup of the file the command was in what the heckkk. on_socket_event_type no longer exists in my bot yet is still producing errors tohruconfused

#

wow so i used the same code on a separate test bot and do not get the error. But it seems my main bot cannot get rid of this error for some reason. I even changed the token thinking maybe there were multiple sessions running.

#

I notice an error loading the cog on startup, it seems the cog is never being unloaded when the bot goes offline somehow... I get a cog already loaded error on startup.

true pewter
#

I am making a command that muste a message at the beginning and at the end of the method I modify the first message, but I get an error.


@commands.slash_command
async def prueba(ctx):
    # send menssge "test"
    message = await ctx.send("test")

    # safe id
    message_id = message.id

    # code
    # ...

    # modify by id
    await ctx.message.channel.fetch_message(message_id).edit(content="final test")
rotund flicker
#

hi

young bone
fervent cradle
grizzled sentinel
grizzled sentinel
green hinge
#

How can I make it so that when I change the letter in 'LetterFish', the dropdown menu of 'Fish' is refreshed instead of being resent as a message?

class BuchstabeFischView(discord.ui.View):
    def __init__(self, bot: discord.Bot):
        self.bot = bot
        super().__init__(BuchstabeFisch(self.bot))

class FischView(discord.ui.View):
    def __init__(self, bot: discord.Bot, selected_letter: str):
        self.bot = bot
        self.selected_letter = selected_letter
        super().__init__(Fisch(self.bot, self.selected_letter))

class BuchstabeFisch(discord.ui.Select):
    def __init__(self, bot: discord.Bot):
        self.bot = bot
        options = [discord.SelectOption(label=letter) for letter in ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y"]]
        super().__init__(
            placeholder="Wähle den Anfangsbuchstaben von deinem Fisch aus",
            min_values=1,
            max_values=1,
            options=options,
        )
        
    async def callback(self, interaction: discord.Interaction):
        selected_letter = self.values[0]
        await interaction.response.send_message(view=FischView(self.bot, selected_letter))

class Fisch(discord.ui.Select):
    def __init__(self, bot: discord.Bot, selected_letter):
        self.bot = bot
        options = [discord.SelectOption(label=fish) for fish in bot.fische if fish.startswith(selected_letter)]
        super().__init__(
            placeholder="Wähle deinen Fisch aus",
            min_values=1,
            max_values=1,
            options=options,
        )
        
    async def callback(self, interaction: discord.Interaction):
        await interaction.response.send_modal(AddSpot(self.bot, interaction.channel))```
grizzled sentinel
#

You can edit the message with the dropdown.

uneven beacon
#

how can i fix this?

green hinge
grizzled sentinel
#

That looks like it would work, just dont get message confused with self.message because they would be different

grizzled sentinel
green hinge
grizzled sentinel
green hinge
#

Then how do I define message beforehand?

class BuchstabeFisch(discord.ui.Select):
    def __init__(self, bot: discord.Bot):
        self.bot = bot
        options = [discord.SelectOption(label=letter) for letter in ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y"]]
        super().__init__(
            placeholder="Wähle den Anfangsbuchstaben von deinem Fisch aus",
            min_values=1,
            max_values=1,
            options=options,
        )
        
    async def callback(self, interaction: discord.Interaction):
        selected_letter = self.values[0]
        if message:
            await message.edit(view=FischView(self.bot, selected_letter))
        else:
            message = await interaction.response.send_message(view=FischView(self.bot, selected_letter))```
young bone
grizzled sentinel
#

I guess you could do self.attached_message = None in the __init__ The name is changed so you do not override the built in self.message

grizzled sentinel
young bone
#

oh, nvm

grizzled sentinel
green hinge
#

How can I edit the message correctly?
Do I have to bold the message first to be able to edit it?

        if self.attached_message:
            await self.attached_message.edit(view=FischView(self.bot, selected_letter))```
```  File "c:\Users\User\Documents\Coding\OnlyFrames\cogs\spot.py", line 64, in callback
    await self.attached_message.edit(view=FischView(self.bot, selected_letter))
AttributeError: 'Interaction' object has no attribute 'edit'```
proud mason
green hinge
# proud mason What is `self.attached_message` You use interaction.edit_original_response to e...

What am I doing wrong?

class BuchstabeFisch(discord.ui.Select):
    def __init__(self, bot: discord.Bot):
        self.bot = bot
        self.attached_message = None
        options = [discord.SelectOption(label=letter) for letter in ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y"]]
        super().__init__(
            placeholder="Wähle den Anfangsbuchstaben von deinem Fisch aus",
            min_values=1,
            max_values=1,
            options=options,
        )
        
    async def callback(self, interaction: discord.Interaction):
        selected_letter = self.values[0]
        if self.attached_message:
            await interaction.edit_original_message(view=FischView(self.bot, selected_letter))
        else:
            self.attached_message = await interaction.response.send_message(view=FischView(self.bot, selected_letter))```
uneven beacon
grizzled sun
#

How do I keep a variable when using for example button interactions?

Like for example a page counter, or the time since you pressed the button. How do I keep the session going and just wait for a response without discarding where the execution currently is.

asking this as a quick question as I assume I just need the right link to where to read up

uneven beacon
young bone
#

do you have intents?

#

@uneven beacon

uneven beacon
#

intents = discord.Intents.all()

grizzled sentinel
grizzled sentinel
grizzled sun
grizzled sentinel
#

Don't use the example I just showed its not a good one

errant craneBOT
#

Here's the tic tac toe example.

grizzled sentinel
grizzled sentinel
#

1st line yes. But the next line put it back how it was. No id. You already have the ID you need to object.

green hinge
#

I have now solved it like this. How can I make it so that I can always delete and recreate the message when I change the selection in the dropdown menu?

class BuchstabeFisch(discord.ui.Select):
    def __init__(self, bot: discord.Bot):
        self.bot = bot
        self.attached_message = None
        options = [discord.SelectOption(label=letter) for letter in ["A", "Ä", "B", "C", "D", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "Ö", "P", "Q", "R", "S", "T", "U", "V", "W", "Z"]]
        super().__init__(
            placeholder="Wähle den Anfangsbuchstaben von deinem Fisch aus",
            min_values=1,
            max_values=1,
            options=options,
        )
        
    async def callback(self, interaction: discord.Interaction):
        selected_letter = self.values[0]
        if self.attached_message:
            await self.attached_message.delete_original_response()
            await interaction.response.send_message(view=FischView(self.bot, selected_letter))
        else:
            self.attached_message = await interaction.response.send_message(view=FischView(self.bot, selected_letter))```
grizzled sentinel
uneven beacon
proud mason
proud mason
#

and use member.guild.get_channel(id_goes_here)

uneven beacon
proud mason
proud mason
uneven beacon
proud mason
#

that's the channel name.. not the id

#

at this point, just show the full code

uneven beacon
proud mason
#

ok so

#

since you have the name and not the id, you would have to use utils.get

#

my bad for asking you to switch

#

use utils.get on guild.voice_channels

#

.rtfm guild.voicee_ch

winter condorBOT
#

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

proud mason
#

.rtfm guild.voice_ch

winter condorBOT
green hinge
proud mason
#

||when your keyboard is broken 💀||

green hinge
#

If I have several dropdown menus one after the other and want to have all selected contents at the end, can I solve the whole thing more elegantly than passing the values from each dropdown to the next view?

west quest
#

hey, how would i setup an error handling for missing permission?

#

figured it out

#

nvm, i cant seem to figure out how i can remove the this command did not respond

full basin
#

You're doing ctx.send

#

When you should ctx.respond

rotund flicker
rotund flicker
young bone
#

read the error

#

@rotund flicker

rotund flicker
#

cant figure out the error

full basin
#

"Cannot send empty message"

#

There isn't too much to figure out

rotund flicker
#

Yeah i read that

rotund flicker
full basin
#

.pastebin

#

?tag paste

obtuse juncoBOT
rotund flicker
rotund flicker
errant craneBOT
full basin
#

A DM?

grizzled sentinel
#

.rtfm member.send

winter condorBOT
grizzled sentinel
#

What do you mean? You are getting a specific user. And responding if they are online or offline

#

So what is wrong

#

Lowercase s in status

full basin
#

And it's not a coroutine

grizzled sentinel
#

.rtfm user look at the attributes and you will see everything

fallen yacht
#

I am very new to this. I have the latest version of python as well as pycharm. when I try to make a new project it dose not allow me to code. I think it is the configuration but I am not sure

green hinge
#

Is there any way to check if I have 1 or 2 dropdown menus in a view?
I want to continue if there is only one dropdown menu after selecting a property and if there are 2 dropdown menus I want to continue only after selecting something in the second dropdown menu.

class FischView(discord.ui.View):
    def __init__(self, bot: discord.Bot, selected_letter: str, gewaesser):
        self.bot = bot
        self.gewaesser = gewaesser
        self.selected_letter = selected_letter
        super().__init__(Fisch(self.bot, self.selected_letter, gewaesser))

    @discord.ui.button(label='➕ Weiteren Fisch hinfügen', custom_id="TestButton", style=discord.ButtonStyle.primary)
    async def start_button(self, button: discord.ui.Button, interaction: discord.Interaction):
        self.add_item(Fisch2(self.bot, self.selected_letter, self.gewaesser))
        await interaction.response.edit_message(view=self)

class Fisch(discord.ui.Select):
    def __init__(self, bot: discord.Bot, selected_letter, gewaesser):
        self.bot = bot
        self.gewaesser = gewaesser
        options = [discord.SelectOption(label=fish) for fish in bot.fische if fish.startswith(selected_letter)]
        super().__init__(
            placeholder="Wähle deinen Fisch aus",
            min_values=1,
            max_values=1,
            options=options,
        )
        
    async def callback(self, interaction: discord.Interaction):
        await interaction.response.send_modal(AddSpot(self.bot, interaction.channel, self.gewaesser, self.values[0]))

class Fisch2(discord.ui.Select):
    def __init__(self, bot: discord.Bot, selected_letter, gewaesser):
        self.bot = bot
        self.gewaesser = gewaesser
        options = [discord.SelectOption(label=fish) for fish in bot.fische if fish.startswith(selected_letter)]
        super().__init__(
            placeholder="Wähle deinen Fisch aus",
            min_values=1,
            max_values=1,
            options=options,
        )
        
    async def callback(self, interaction: discord.Interaction):
        await interaction.response.send_modal(AddSpot(self.bot, interaction.channel, self.gewaesser, self.values[0]))```
proud mason
proud mason
#

.rtfm view.children

winter condorBOT
#

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

proud mason
#

Uh

#

.rtfm discord.ui.View

proud mason
#

Why does it not show .children

rose vapor
#

can i do a slash command that is a reply to a message?

like i want to click reply, then type a slash command as the reply

i've tried already but the slash command doesn't pop up, only the builtins do

green hinge
#

Why does my loop not start and I always get the error message that my Channel_ID is missing although both values are printed correctly?

Unhandled exception in internal background task 'update_events'.
Traceback (most recent call last):
  File "/usr/local/lib/python3.8/dist-packages/discord/ext/tasks/__init__.py", line 169, in _loop
    await self.coro(*args, **kwargs)
TypeError: update_events() missing 1 required positional argument: 'channel_id'
@bot.event
async def on_ready():
    bot.waters = await dab.get_waters()
    bot.fische = await dab.get_fisch()
    for guild in bot.guilds:
        data = await dab.get_calender(guild.id)
        if data[0] != None:
            channel_id = data[0]
            print(guild.id)
            print(channel_id)           
            calender.Calender.update_events.start(guild.id, channel_id)

class Calender(commands.Cog):

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

    @tasks.loop(minutes=10)
    async def update_events(self, guild_id, channel_id):
robust hatch
#

I want to pass an argument to a select list so that it is different every time the command is run. Is that possible?

robust hatch
#

class ThisView(discord.ui.View):
def init(self, select_list):
super().init()
self.assignments = select_list
for item in self.assignments:
discord.ui.View.add_item(self, discord.ui.Select())
@discord.ui.select(
placeholder="Select an assignment",
options=[discord.SelectOption(label="Select:", value="Select")])
@full basin how would i do it here?

full basin
#

Why are you "creating" new selects for each item

#

Don't you want different select options depending on the items passed?

robust hatch
#

yeah

#

i want to pass a list of options

#

a list of strings

full basin
#

You have to subclass the select menu

robust hatch
#

how do i do that?

full basin
#

Just like you subclassed the View but now a Select?

robust hatch
#

tbh i have no idea of what im doing

#

sry

full basin
#

.lp

winter condorBOT
#
robust hatch
#

ty

#

tysm

full basin
#

It's useless for me to help you out if you don't know what it does.

#

Try learning the basics of python and OOP.

robust hatch
#

k

#

ty

rare ice
copper knot
#

i wish there was a way to get the username of a webhook message

gleaming falcon
#

I may be overthinking it, but is there a way to hide a button without outright removing it (so I don’t have to try inserting it back in)?

I have other UI elements that may change the availability of the button and while I can disable it, it would look better if it’s just hidden

copper knot
#

that would make it easy to insert again

gleaming falcon
gleaming falcon
#

No, need a specific position. Thanks for the thought!

gleaming falcon
#

Ick. Continuing on this path, is there any better ways of getting an element other than the children list? Definitely not super elegant.

#

oh wait, I guess I can at least search it by name since it's directly defined by decorator, as far as collecting the index.

gleaming falcon
#

I'm sure my logic is terribad (help? in my defense, it's super late), but unless I'm doing something super-wrong, this does seem a little overcomplicated. But it does look kinda nice; the button displays when relevant and doesn't otherwise.

class MyView(discord.ui.View):
    ... 
    def toggle_value_button(self, hide=True):
        if hide:
            if self.hidden.get(self.token_value):
                return
            value_button_idx = self.children.index(self.token_value)
            value_button = self.children.pop(value_button_idx)
            self.hidden[value_button] = value_button_idx
        else:
            # Restore it
            idx = self.hidden.get(self.token_value)
            if not idx or self.children[idx] == self.token_value:
                return
            self.token_value.disabled = False
            self.children.insert(idx, self.token_value)
            del self.hidden[self.token_value]
    ...
    @discord.ui.button(label='Value', custom_id='value_button', style=discord.ButtonStyle.primary, emoji='🪙', row=2)
    async def token_value(self, button: discord.ui.Button, interaction: discord.Interaction):
        modal = TokenAmountModal(view=self, input_type='value')
        await interaction.response.send_modal(modal)
green hinge
#

Why does my loop not start and I always get the error message that my Channel_ID is missing although both values are printed correctly?

Unhandled exception in internal background task 'update_events'.
Traceback (most recent call last):
  File "/usr/local/lib/python3.8/dist-packages/discord/ext/tasks/__init__.py", line 169, in _loop
    await self.coro(*args, **kwargs)
TypeError: update_events() missing 1 required positional argument: 'channel_id'
@bot.event
async def on_ready():
    bot.waters = await dab.get_waters()
    bot.fische = await dab.get_fisch()
    for guild in bot.guilds:
        data = await dab.get_calender(guild.id)
        if data[0] != None:
            channel_id = data[0]
            print(guild.id)
            print(channel_id)           
            calender.Calender.update_events.start(guild.id, channel_id)

class Calender(commands.Cog):

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

    @tasks.loop(minutes=10)
    async def update_events(self, guild_id, channel_id):
olive marsh
#

ctx and discord interaction don't seem to go together. what can I use instead of ctx?

olive marsh
green hinge
young bone
olive marsh
#

That works fine with interactions

young bone
young bone
olive marsh
errant craneBOT
#

Here's the slash basic example.

olive marsh
green hinge
young bone
#

No?

olive marsh
#

module 'discord' has no attribute 'ApplicationContext'

young bone
#

Can you show the pip list?

green hinge
olive marsh
young bone
#

did you add to the task "await self.bot.wait_unitil_ready()"?

olive marsh
#

Yes

young bone
olive marsh
#

I switched to slash commands today

#

I used pip freeze

young bone
#

?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

olive marsh
#

Wait a sec. I got a package

young bone
#

I really should switch to my pc...

olive marsh
#

It seems to work now. Thanks ❤️

young bone
young bone
olive marsh
proud mason
#

Either start the loop in cog init or in an on ready listener in the cog

olive marsh
#

Replit automatically installs discordpy whenever I run the repl

#

How can I stop this from happening?

obtuse juncoBOT
green hinge
olive marsh
grizzled sentinel
#

Do you have the presence intent?

proud mason
green hinge
proud mason
green hinge
proud mason
green hinge
# proud mason Yes

But I need the query if the Guild ID and the Channel ID are in the database because otherwise the loop can't start because the data is missing. What is the best way to do this in the init?

    for guild in bot.guilds:
        data = await dab.get_calender(guild.id)
        if data[0] != None:
            channel_id = data[0]         
            calender.Calender.update_events.start(guild.id, channel_id)```
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

green hinge
proud mason
#

smth like bot.dab = dab

#

And then use the database in the cog init

#

Oh wait. You can't await in init

#

So you need a task loop to start a task loop 💀

green hinge
green hinge
# proud mason So you need a task loop to start a task loop 💀

Then just like that?

class Calender(commands.Cog):

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

    @commands.Cog.listener()
    async def on_ready(self):
        for guild in self.bot.guilds:
            data = await dab.get_calender(guild.id)
            if data[0] != None:
                channel_id = data[0]         
                self.update_events.start(guild.id, channel_id)```
green hinge
# proud mason Oh yeah that works

It worked but after restarting the bot I now get this error message:
I do not know why I have not changed anything 😄

  File "/home/Bot/Bot/utils/database.py", line 49, in get_calender
    await cursor.execute("SELECT Calender_ChannelID, Calender_MessageID FROM config WHERE GuildID = %s", (guild_id))
  File "/home/Bot/.local/lib/python3.8/site-packages/aiomysql/cursors.py", line 239, in execute
    await self._query(query)
  File "/home/Bot/.local/lib/python3.8/site-packages/aiomysql/cursors.py", line 457, in _query
    await conn.query(q)
  File "/home/Bot/.local/lib/python3.8/site-packages/aiomysql/connection.py", line 469, in query
    await self._read_query_result(unbuffered=unbuffered)
  File "/home/Bot/.local/lib/python3.8/site-packages/aiomysql/connection.py", line 672, in _read_query_result
    await result.read()
  File "/home/Bot/.local/lib/python3.8/site-packages/aiomysql/connection.py", line 1153, in read
    first_packet = await self.connection._read_packet()
  File "/home/Bot/.local/lib/python3.8/site-packages/aiomysql/connection.py", line 618, in _read_packet
    raise InternalError(
pymysql.err.InternalError: Packet sequence number wrong - got 1 expected 7
#

If I remove the on_ready event again everything works without error message but the loop does not start again.

proud mason
#

Try searching on google

green hinge
# proud mason Hmm smth with aiomysql

I use the following to connect to the database. Is this where my error lies?
On the internet it says something about single and multithreading 🤔

async def get_db_conn():
    if not hasattr(get_db_conn, "conn"):
        get_db_conn.conn = await aiomysql.connect(host=host,port=port,user=user,password=password,db=db)
    return get_db_conn.conn```
proud mason
green hinge
# proud mason How do you get dab? Try using bot vars instead of global variable or importing d...

I have a database.py where the connection is inside and with the functions I then access the connection:

async def get_db_conn():
    if not hasattr(get_db_conn, "conn"):
        get_db_conn.conn = await aiomysql.connect(host=host,port=port,user=user,password=password,db=db)
    return get_db_conn.conn

async def get_calender(guild_id):
    db_con = await get_db_conn()
    async with db_con.cursor() as cursor:
        await cursor.execute("SELECT Calender_ChannelID, Calender_MessageID FROM config WHERE GuildID = %s", (guild_id))
        result = await cursor.fetchone()
        await cursor.close()
    return result```

Since I have to read out something from the database every now and then. 

I'm just wondering if I should switch the whole thing to multithreading so that multiple accesses to the database are possible at the same time?
#

Would this solve my problem?

async def get_db_conn():
    if not hasattr(get_db_conn, "conn"):
        get_db_conn.conn = await aiomysql.connect(host=host,port=port,user=user,password=password,db=db, loop=loop)
    return get_db_conn.conn

async def get_calender(guild_id):
    async with get_db_conn(asyncio.get_event_loop()) as db_conn:    
      async with db_con.cursor() as cursor:
        await cursor.execute("SELECT Calender_ChannelID, Calender_MessageID FROM config WHERE GuildID = %s", (guild_id))
        result = await cursor.fetchone()
        await cursor.close()
    return result```
grizzled sentinel
#

What lib do you use for db?

green hinge
grizzled sentinel
#

You might need to look at pooling your connections. Search up "connection pool in aiomysql"

#

How your code is it is a small change to use pools.

green hinge
grizzled sentinel
#

Yes it is a "pool" of available connections that you use than return to the pool.

green hinge
# grizzled sentinel Yes it is a "pool" of available connections that you use than return to the pool...

Okay that works 🙂

async def get_db_conn():
    if not hasattr(get_db_conn, "conn"):
        get_db_conn.conn = await aiomysql.create_pool(host=host,port=port,user=user,password=password,db=db, minsize=1, maxsize=10)
    return get_db_conn.conn

async def get_calender(guild_id):
    pool = await get_db_conn()
    async with pool.acquire() as db_con:
        async with db_con.cursor() as cursor:
            await cursor.execute("SELECT Calender_ChannelID, Calender_MessageID FROM config WHERE GuildID = %s", (guild_id))
            result = await cursor.fetchone()
        return result```
grizzled sentinel
#

And to make it simpler you can have get db conn return a connection instead of the whole pool

gleaming falcon
green hinge
# grizzled sentinel And to make it simpler you can have get db conn return a connection instead of t...

So ?

async def get_db_conn():
    if not hasattr(get_db_conn, "conn"):
        get_db_conn.conn = await aiomysql.create_pool(host=host,port=port,user=user,password=password,db=db, minsize=1, maxsize=10)
pool = get_db_conn.conn.acquire()
    return pool 

async def get_calender(guild_id):
    async with get_db_conn() as db_con:
        async with db_con.cursor() as cursor:
            await cursor.execute("SELECT Calender_ChannelID, Calender_MessageID FROM config WHERE GuildID = %s", (guild_id))
            result = await cursor.fetchone()
        return result```
grizzled sentinel
#

.rtfm view.add_item

winter condorBOT
grizzled sentinel
gleaming falcon
#

I was avoiding hardcoding the slot just in case other layout changes happened

spring drift
#

how would i check if a member has permission over another member

#

so basically just checking if said member is able to ban/kick/timeout the other member

#

nvm i figured it out

#

im an idiot lmao

north gorge
#

I'm guessing that in the case of discord generating an embed for a link that you can't listen to on_message and just look for .embeds[0] because the adding of the embed doesn't happen immediately? Can't figure out why else message.embeds[0].description wouldn't seem to work in on_message

fervent cradle
#

Is there any way to disable + edit the button's label after submitting a modal?

gleaming falcon
copper magnet
#

i need help 🥹 . My bot give me this error: discord.errors.InvalidArgument: Could not resolve appropriate move position
But whyy?
piece of my code: await ctx.channel.move(category=get(ctx.guild.categories, name="closed"))

proud mason
north gorge
#

I realized what I was looking for wasn't in embeds[0] LOL it seems to work as I'd expect after I changed that

#

Turns out the problem was between keyboard and chair all along

proud mason
proud mason
#

Also, full traceback please

tired goblet
#

How can i receive inputs along with my slash commands?

livid monolith
#

how would i set the colour of my embed?

full basin
#

.rtfm Embed.colour

winter condorBOT
livid monolith
#
    async def test(self, ctx):
      try:
        server_list = []
        for server in ctx.bot.guilds:
            server_list.append(f"Name: {server.name}, Member Count: {server.member_count}")
        if len(server_list) > 2000: #split into two messages if more than 2000 servers
            await ctx.send("\n".join(server_list[:2000]))
            await ctx.send("\n".join(server_list[2000:]))
        else:
            await ctx.send("\n".join(server_list))
      except Exception as e:
          await ctx.respond(":warning: There was an error, this has been reported to staff.")
          print(e)```

400 Bad Request (error code: 50035): Invalid Form Body
In content: Must be 2000 or fewer in length.
proud mason
errant craneBOT
#

Here's the slash options example.

north gorge
fallen cove
#

is there a way to make a task loop to ack like the listener on_message. so the task starts when start command is sent and stops when the stop command is sent?

proud pagoda
#

However, if the task is still executing some code, it will continue until it is complete, but it won't run again after stop is run if that makes sense

fallen cove
#

I more meant the on_message imitation part

proud pagoda
#

wdym?

fallen cove
#

But thank you

proud pagoda
#

yw