#Basic Pycord Help (Quick Questions Only)

1 messages · Page 64 of 1

grizzled sentinel
#

And fixes a breaking bug

fervent cradle
#

seems to be fixed

fervent cradle
#

i dont understand why it ratelimits and doesnt send reactions even though its like 1 reaction every 2 minutes

zinc cloak
#

How do I allow the user to select multiple roles within a command parameter?

full basin
grizzled sentinel
grizzled sentinel
marsh swan
#

what is the difference between pycord and discord.py?

full basin
#

Pycord was a fork of dpy

#

And now they're different

marsh swan
silver moat
long zealot
#

If I'm working with a command that displays a select menu and then resumes the command after the user has made their selection, what's the easiest way to resume the command after a selection has been made?

#

Currently i'm using await view.wait, which seems to just be waiting for it to time out

long zealot
#

Basically players create a treaty with a command, are presented with a select menu to select the people involved, and then the command resumes and adds the data to a JSON file

silver moat
#

self.stop() also triggers await view.wait()

long zealot
#

ohhh, I'm an idiot

#

thanks

soft girder
#

Good afternoon Yesterday I made endless buttons, but in the end nothing works.

#

As a result, all buttons are valid for 5 minutes, after which they do not work.

errant craneBOT
#

Here's the persistent example.

silver moat
#

and you spelled timeout as timeoiut

soft girder
#

🤣

soft girder
silver moat
#

IDEs like Pycharm would mark that as a warning.

soft girder
silver moat
#

Please look at the example

soft girder
#

I think it can put 3600 in a timeout. Is it counted by seconds?

#

@silver moat

#

Buttons are disabled every 5 minutes

silver moat
#

Please read

soft girder
#

Ok

#

Will try

soft girder
#
 
@bot.event
async def on_ready():
    bot.add_view(TlB()) # Registers a View for persistent listening
#

Now I wrote endless buttons and ran into a problem

#
@commands.Cog.listener()
    async def on_ready(self):
        self.add_view(TlB())
#

I need a similar function to work in COG

proud mason
#

add_view is a method on the bot and not the cog

soft girder
#

I made a 'self.bot' but now it gives me an error. And I don’t even know how to change it.

soft girder
# proud mason `self` is the cog. `self.bot` will be the bot
class TlB(discord.ui.View):
    def _init_(self):
        super()._init_(timeout=None)
    

    @discord.ui.button( label...)...

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

    @commands.Cog.listener()
        async def on_ready(self):
            self.bot.add_view(TlB())
#

This is roughly what is happening now.

proud mason
#

whats the error?

soft girder
proud mason
# soft girder

you need to set custom id on all the items in the view

soft girder
# proud mason you need to set custom id on all the items in the view
class TlB(discord.ui.View):
    def _init_(self):
        super()._init_(timeout=None)
    

    @discord.ui.button( label="Confirm participation",custom_id="button-1",emoji="✅",style=discord.ButtonStyle.success)
    async def button_callback(self, button, interaction):
        await interaction.response.send_message(f"You confirm participation.",ephemeral = True)
            

    @discord.ui.button( label="Admin button",custom_id="button-2",emoji="🔄",style=discord.ButtonStyle.primary)
    async def second_button_callback(self, button, interaction):
        await interaction.response.edit_message(view=self)

        guild = interaction.guild_id
        msg = interaction.message


        cursor.execute(f"SELECT rowid,* FROM vipteamlist WHERE server_id = {guild}")
        item2 = cursor.fetchmany(4)
        db.commit()
        b = ""
        i = 0
        for el in item2:
            i+=1
            b += f"**{i}**.:coin: __{el[1]}__ | {el[2]} | <@{el[3]}>\n"

        cursor.execute(f"SELECT rowid,* FROM teamlist WHERE server_id = {guild}")
        item = cursor.fetchmany(16)
        db.commit()

        a = ""
        f=4
        for el in item:
            f+=1
            if 4<f<17:
                a += f"**{f}**. __{el[1]}__ | {el[2]} | <@{el[3]}>\n"    
            if f>16:
                a += f"Reserve🔴**{f}**. __{el[1]}__  | {el[2]}  | <@{el[3]}>\n"
        embed2 = discord.Embed(title =f":scroll: TEAM LIST :scroll:",description=f"**🕐Time: 21:00 Moscow **\n \n{b}{a}", colour = discord.Colour.embed_background())
        embed2.set_footer( text =f'To confirm participation, click on ✅')
        await msg.edit(embed=embed2)
#

I think the problem is that I write the event after the class🤔

proud mason
soft girder
#

Then what doesn't he like?

round rivet
#
    def _init_(self):
        super()._init_(timeout=None)
soft girder
#

@proud mason What's wrong?

round rivet
#

not just one

proud mason
#

aah lmao

soft girder
#

ahahahaha

young bone
#

@soft girder do you have the Python one installed for Visual Studio?

soft girder
#

@young bone yes

soft girder
ornate current
#

hey i am using mongodb for my bot, should i make connections in every cog?

#

or is there any way to make connection in one place and access it in every cog

limber urchin
#

Realistically you should only need to make a connection when you actually need to access the database. Your best option is probably to set up a connection pool and use those connections on-demand. Unless you have something that is very frequently accessing the database, in that case having a persistent connection would be better.

ornate current
#

Uh ok

#

and i am having a problem here

TypeError: duplicate base class TimeoutError```
#

I am trying to use aioredis

#
@bot.event
async def on_ready():
  bot.pool = await aioredis.create_redis_pool('redis://localhost')```
limber urchin
#

What are you using redis for?

ornate current
#

for storing stuff

limber urchin
#

You know that redis doesn't persist any data right? As soon as you restart your redis instance all data is going to be cleared.

ornate current
#

oh

#

wow nevermind

#

even a dictionary is better lol

limber urchin
#

Redis is a cache, not a database. It's literally the same as storing things in a variable.

ornate current
#

i am trying to avoid mongo db cuz its only 512 mb

young bone
#

what is redis?

limber urchin
#

So it's useless unless you have multiple applications needing to access the cache

ornate current
#

storage

limber urchin
#

It's mostly used when you need to cache things that are accessed by multiple applications

ornate current
#

my bot is going to store alot of data that is why i am trying to avoid mongodb... are their any other nosql alternatives?

limber urchin
ornate current
#

my bot is going to store alot of data tho

limber urchin
#

And?

ornate current
#

is it enough?

limber urchin
#

Wtf do you mean by Mongodb only being 512mb? That makes no sense

ornate current
#

wait a sec

proud mason
#

I believe they mean thier host only has 512 mb storage

#

That is enough for sqlite

ornate current
#

atlas's free plan is 512 mb

limber urchin
#

If your host only has 512mb then it doesn't matter what database you use? It's still going to b 512mb

limber urchin
ornate current
proud mason
#

Sqlite files are very small. You would need hundreds and thousands of lines to hit 10MBs ngl

ornate current
limber urchin
#

the free atlas tier isn't even meant to store things, it's just a testing space to play around with

ornate current
#

its just that nosql is easier to manage

limber urchin
#

Use whatever you want

#

If you want to use mongo, use mongo

proud mason
#

Yea sqlite is pretty good and powerful. Asqlite library and WAL mode will help you achieve best performance out of it

proud mason
ornate current
#

That's what I am asking keeping in mind there are 20,000 members and each of them is storing bunch of data.

#

Inventories, money, and others

limber urchin
#

Storage is cheap, use whatever database you prefer

#

it's not like you're going to have 1TB of data just because you're storing a few thousand members

#

you'll need literally millions of rows in your database tables before you need to worry about disk space

ornate current
#

i should use json then what

limber urchin
#

no

ornate current
#

lmao

proud mason
#

||You can even estimate your db size to a very large extent||

One way for SQL- each datatype has a specified size. find the size of 1 row based on its columns. You can get the size for sqlite data types from google. Multiply this row size by the estimated number of rows. Do this for all the tables and add it

proud mason
limber urchin
#

To put into perspective, I have a database table here with ~10k members. 8 columns with various types of data, and it's not even 1MB using Postgres

ornate current
#

oh alright

#

thx

#

i am gonna stick to aiosqlite

proud mason
#

But aiosqlite is pretty good too

#

Just thought of letting you know

ornate current
#

@proud mason

py -m pip install asqlite
ERROR: Could not find a version that satisfies the requirement asqlite (from versions: none)
ERROR: No matching distribution found for asqlite```
#
  • i found nothing on the web regarding asqlite
proud mason
ornate current
#

3.11.0

grizzled sentinel
turbid ginkgo
#

I found a solution to edit slash command response on stackoverflow: ctx.edit("new content") but it returns an error:
TypeError: Interaction.edit_original_response() takes 1 positional argument but 2 were given
I didn't find any other solutions to this. How do I fix?

proud mason
proud mason
ornate current
#

sorry if i ask alot of questions but

@bot.event
async def on_ready():
  bot.db = await aiosqlite.connect()```
should i establish connection once or do it in each and every command
proud mason
#

As a kwarg

somber pelican
#

can I pass extra arguments to a Loop object?

turbid ginkgo
ornate current
#

or do it like this

@bot.command()
async def test(ctx):
  db = await aiosqlite.connect()
  #stuff here
  await db.close()
#

and what about closing the databse? should i worry about it

proud mason
grizzled sentinel
grizzled sentinel
soft girder
#

I think this will be a dumb question. But how to make a button that can be used by a person who has certain permissions .For example : administrators.

grizzled sentinel
soft girder
#

Yea

ornate current
long zealot
#

Anyone familiar with bot computing/data requirements? We’re running an online game on March 25th with 36 people on discord, with the bot performing a few key tasks, so will be processing a lot of commands. I currently have it running on a Heroku basic dyno with 512mb RAM. Should I move it to a VPS? It only needs to be used for a few hours so I don’t care about persistency but it will be heavily used

limber urchin
#

And the hardware requirements depends a lot on what your bot is actually going to do. But if it really will be "heavily" used, then at least 2G RAM and 2vCPUs.

silent meadow
#

hey all, I want to make a sound dispatch command somewhat similar to Airhorn Solutions... This is what I made but I am having an error

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

Code:

@discord.slash_command(name='quack', description = 'Quack, Quack, Quack!')
    async def quack(self, ctx):
        vc = ctx.author.voice.channel
        if vc == None:
            ctx.respond("You must be connected to a voice channel!")
        else:
            vc.connect()
            vc.play(discord.File('duck-quacking-37392.mp3'))
#

where am I going wrong?

meager heron
silver moat
silent meadow
silver moat
#

.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.

turbid ginkgo
#

How would i make a slash command option user selection only? I mean to get the parameter to list all members without a specific role?

silver moat
errant craneBOT
#

Here's the slash autocomplete example.

turbid ginkgo
#

Yeah, I'm trying to figure out how to get the users of the currect guild that doesn't have a specific role.

silver moat
turbid ginkgo
#

What is connectionState?

#

Is that optional or required?

limber urchin
#

what?

turbid ginkgo
#

in discord.Role(guildId,ConnectionState, data)

#

I'm new to these things

limber urchin
#

Why do you want to create an instance of the Role class?

turbid ginkgo
#

So, I'm trying to make a slash command that has two required parameters, where the first one lists all members without a specific role. The second consists of 3 roles.

#

I somewhat understood the autocomplete feature

limber urchin
#

That doesn't answer why you're trying to manually initialize a new instance of the role class?

turbid ginkgo
#

I don't know how to do it?

limber urchin
#

I'm asking you why you're trying to do it in the first place

turbid ginkgo
limber urchin
#

You can, but why do you need to manually create an instance?

turbid ginkgo
#

I wasn't sure know what that does. I'm new to pycord and python

limber urchin
#

Read rule 1 in #help-rules

turbid ginkgo
#

I assume I can't even ask for help to HELP me LEARN it

silver moat
#

?tag learnpython

obtuse juncoBOT
#

To be clear:

When we tell you to learn Python before asking questions here, it is not meant in a derogatory way, we are not calling your dumb or incompetent. We are simply stating the fact that usage of PyCord requires a fair bit of knowledge with using OOP, Async/Await etc. in Python. If you are not comfortable with these concepts, chances are you will not understand the answers given to you in this channel.

We understand that everyone learns at a different pace, and your current knowledge with Python may have been enough so far. When we say "you need to learn Python", it is most likely a sign that we have given you an explanation that you could not understand and there is no way for us continue to help you without spoonfeeding.

limber urchin
#

We're here to help you with issues regarding pycord, not teach you basic Python concepts so that you'll understand our solutions.

soft girder
#
    @discord.ui.button( label="Admin button",custom_id="button-2",emoji=":arrows_counterclockwise:",style=discord.ButtonStyle.primary)
    async def second_button_callback(self, button, interaction):
        await interaction.response.edit_message(view=self)

        guild = interaction.guild_id
        msg = interaction.message
        
        interaction.user.guild_permissions(administrator)
#

Hello everyone. Now I wrote the code. You need to know how to organize the button so that only administrators can click on it.

full basin
zinc cloak
#

How do I do a persistent view, if the view has parameters that changes the custom_ids of the buttons?

    bot.add_view(reaction_roles.ReactionRoles.ReactionView([]))  # Just leaving an empty list doesn't make the view work
tiny spire
#

How do I set the status of my bot? I can't figure it out for some reason

    async def on_ready():
        await client.change_presence(status=Status.online, activity=Activity(type=ActivityType.custom, name=status))
        print(f"{client.user} is connected.")```
note that the status variable is just a string
fervent cradle
#

Does anyone have a recommended open-source bot made with pycord that I could review the code of to learn the library?

silver moat
full basin
full basin
zinc cloak
#

It's for reaction roles

#

But a select menu is a LOT easier

maiden lake
#

is there a common way people remove button's when a view times out? I have a sorta of solution but it has some weird kinks

full basin
#

Edit the message and pass view None?..

maiden lake
#

that's kinda what I'm doing but it only seems to work for the most recent message and also doesn't like it when it has attachments.

full basin
#

What and what

maiden lake
#

if you run 1 command that sends a message with buttons, then another before the first times out the first keeps the buttons.

limber urchin
#

All you need to do is override on_timeout of the view and edit the message with view=None.

#

It sounds like you're making it way more complicated than it has to be

maiden lake
#

I could have sworn I tried that, thought when I did it had a issue with self.message but it worked fine now so 🤷

#

this makes things so much easier

hushed ledge
#

One message removed from a suspended account.

somber pelican
#

in modals, if a non-required field is blank, what is the default value? None?

young bone
somber pelican
#

i see this

#

i would prefer if it was None already tho

grizzled sentinel
somber pelican
#

alright

#

is there a way to send a modal after sending a select menu?

#

interaction.followup has no option for sending a modal

young bone
somber pelican
young bone
#

use interaction.respond

hushed ledge
#

One message removed from a suspended account.

somber pelican
#

okay thank you

#

last question, im subclassing a MyView(View) inside of a Cog class, how do I access the Cog class's attrbutes?

grizzled sentinel
grizzled sentinel
somber pelican
#

ah alright, i'll move everything about then

grizzled sentinel
#

Just wondering what cog attributes do you need? Bot?

hushed ledge
grizzled sentinel
#

Send the modal first. Than edit the message with followup.edit()

somber pelican
#

but i separated everything

hushed ledge
#

One message removed from a suspended account.

#

One message removed from a suspended account.

cerulean yacht
#

i have two server (oracle vm) is there any way i can use both to host one bot?

limber urchin
#

Use both?

#

What does that even mean

cerulean yacht
#

i mean use computational power of both?

limber urchin
#

This is a support channel for pycord/python related issues. Your question has nothing to do with any of those

cerulean yacht
#

okay 👍

proud mason
thorny kindle
#

Hi, How would i add muliple buttons too a command. Right now my command is:

class Rock(discord.ui.View): 
    @discord.ui.button(label="Rock!", style=discord.ButtonStyle.primary, emoji="🧱") 
    async def button_callback(self, button, interaction):
        await interaction.response.send_message("You Chose Rock! I choose:")
class Paper(discord.ui.View): 
    @discord.ui.button(label="Paper!", style=discord.ButtonStyle.primary, emoji="📰") 
    async def button_callback(self, button, interaction):
        await interaction.response.send_message("You Chose Paper! I choose:")
class Scissors(discord.ui.View): 
    @discord.ui.button(label="Scissors!", style=discord.ButtonStyle.primary, emoji="✂") 
    async def button_callback(self, button, interaction):
        await interaction.response.send_message("You Chose Scissors! I choose:")  
        
@bot.slash_command()
async def button(ctx):
    await ctx.send('Rock, Paper, scissors', view=Rock(), view=Paper(), view=Scissors())
#

When its just the rock alone, It works.

soft girder
#
@commands.guild_only()
@bot.slash_command(name='registration', description='Write down command data.',guild_ids=[944934277777326090,769823680695107594])
async def reg(ctx):

    cursor.execute(f"SELECT rowid,* FROM counter1 WHERE server_id = {ctx.guild.id}")
    item = cursor.fetchmany(16)
    db.commit()

    for el in item:
        nom=el[2]

    author= ctx.author

    if nom<12:
        if ctx.guild.id == 9-0:
            guild = bot.get_guild(9-0)
            role=guild.get_role(1-0)
            await author.add_roles(role,reason=None, atomic=True)
        if ctx.guild.id == 7-4:
            guild = bot.get_guild(7-4)
            role=guild.get_role(7-5)
            await author.add_roles(role,reason=None, atomic=True)

        cursor.execute(f"UPDATE counter1 SET count= count + 1 WHERE server_id = {ctx.guild.id}")
        db.commit()
    else:
        await ctx.respond("TEST")
young bone
thorny kindle
soft girder
young bone
thorny kindle
#

What else would i put for the callback then?

young bone
soft girder
thorny kindle
#

Im still learning python, right now i dont know much with it but im just trying to make random commands until they work. Now ive decided to attempt it with buttons.

#

Im trying to learn as i go a lont

#

along*

thorny kindle
#

I know.

soft girder
#

I try all methods

young bone
#

We will not help if you dont even know the basic´s of Python

thorny kindle
#

Alright.

#

Any tips to learn though? Youtube has not helped me even a little bit. Ive learned most of my python by just doing it.

young bone
#

create small projects

#

a discord bot is not a good beginner project

young bone
thorny kindle
dry fulcrum
#

small question: what could cause a repeating task to reset itself mid execution? I have a task set to repeat every 120 seconds, but for some reason it stops executing at a specific line, and start all over again

young bone
dry fulcrum
#

i know, i meant as in what could be a potential cause, like as of right now, if there's no answer in the thread yet, then probably some pointer would be useful to see where thing went wrong

soft girder
young bone
thorny kindle
#

So is it the button_callback i would need to change? Or would it be something in (self, button, interaction)?

soft girder
#

I tried all the ways. He constantly doesn’t like it ...

young bone
#

button cannot have the same callback name

thorny kindle
#

Oh ok, So if i do buttonrock_callback etc that would work?

young bone
#

ye

thorny kindle
#

Alr

young bone
thorny kindle
#

💀 Still saying theres a problem with this line:


    await ctx.respond('Rock, Paper, scissors', view=Rock(), view=Paper(), view=Scissors())
young bone
thorny kindle
#

Oh, Just 1 view then?

dry fulcrum
#

uhhh

#

that's.. setting 1 thing.. to 3 different thing

#

I'm trying to get where his logic was at

young bone
soft girder
#

Mmm.. Yes...

young bone
#

if its a number it should work

#

@proud mason I see you saisneaky

soft girder
#

But it's didn't WORK 😦

proud mason
#

you are just reassigning a variable

soft girder
#

I have tried all the ways

proud mason
#

?tag xy

obtuse juncoBOT
#

An XY problem is when you're trying to ask about your attempted solution, rather than your actual problem.

You are trying to solve problem X, using solution Y. Instead of asking for help with X, you ask about Y. This only results in frustration as whoever is trying to help you needs to ask several questions before even beginning to help you with your actual issue, wasting both their own, and your time. Always include as much information as you can about your problem, including attempted solutions. If there are solutions you've ruled out, include them along with an explanation as to why you've ruled them out.

soft girder
soft girder
#

Look. I am making a command for registration. For the first 12 people, a role should be issued. And for the rest, it should be written "You in reserve"...

#

I tried all the ways, but it does not give me an opportunity.

soft girder
proud mason
#

so

#

what i would do is, set nom to the length of item

#

because that would represent the number of people in the db

proud mason
soft girder
#

This f.... CODE didn't WORK

#

!!!!

soft girder
#

@proud mason

#
class TlB(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)
    

    @discord.ui.button( label="Confirm participation",custom_id="button-1",emoji="✅",style=discord.ButtonStyle.success)
    async def button_callback(self, button, interaction):
        await interaction.response.send_message(f"You confirm participation.",ephemeral = True)
         

    @discord.ui.button( label="Admin button",custom_id="button-2",emoji="🔄",style=discord.ButtonStyle.primary)
    async def second_button_callback(self, button, interaction):
        await interaction.response.edit_message(view=self)

        guild = interaction.guild_id
        msg = interaction.message

        data1=f"SELECT rowid,* FROM vipteamlist WHERE server_id = {guild}"

        cursor.execute(data1)
        item2 = cursor.fetchmany(4)
        db.commit()
        b = ""
        i = 0
        for el in item2:
            i+=1
            b += f"**{i}**.__{el[1]}__ | {el[2]} | <@{el[3]}>\n"

        data2=f"SELECT rowid,* FROM teamlist WHERE server_id = {guild}"

        cursor.execute(data2)
        item = cursor.fetchmany(16)
        db.commit()

        a = ""
        f=4
        for el in item:
            f+=1
            if 4<f<17:
                a += f"**{f}**. __{el[1]}__ | {el[2]} | <@{el[3]}>\n"    
            if f>16:
                a += f"Reserve🔴**{f}**. __{el[1]}__  | {el[2]}  | <@{el[3]}>\n"
        embed2 = discord.Embed(title =f":scroll: TEAM LIST :scroll:",description=f"**🕐Time: 21:00 Moscow **\n \n{b}{a}", colour = discord.Colour.embed_background())
        embed2.set_footer( text =f'To confirm participation, click on ✅')
        await msg.edit(embed=embed2)

#

How to make it so that only the admin can click the second button?

#

interaction.user.guild_permissions maybe

#

but i don't know ?how to use this right

#

Can teach me pls 🙂

ornate current
#

Hey, i think pillow library won't be good with discord.py

#

so is there any asynchronous library for it

proud mason
#

for some reason, the docs dont mention the return type...

#

anyways

#

check if perms.administrator is True

#

where perms is that above thing

proud mason
ornate current
#

hmm alr

#

i just found one named aioEasyPillow

#

gonna test it out

proud mason
soft girder
# proud mason where perms is that above thing
@discord.ui.button( label="Admin button",custom_id="button-2",emoji="🔄",style=discord.ButtonStyle.primary)
    async def second_button_callback(self, button, interaction):
        await interaction.response.edit_message(view=self)

        if interaction.user.guild_permissions.administrator=True:

            guild = interaction.guild_id
            msg = ...

            await msg.edit(embed=embed2)
        else:
            await interaction.response.send_message(f"You aren`t admin.",ephemeral = True)
young bone
#

why do you send the whole code again?

winter condorBOT
proud mason
#

any errors?

#

whats wrong with it

soft girder
#

Extension 'cogs.NS' raised an error: SyntaxError: cannot assign to attribute here. Maybe you meant '==' instead of '='? (NS.py, line 34)

#

@proud mason^

young bone
#

which line is that?

soft girder
#

if interaction.user.guild_permissions.administrator=True:

proud mason
soft girder
#

this line ^^^

ornate current
soft girder
#

aaaaa...

leaden relic
#
member = discord.utils.get(ctx.guild.roles, name="Member")
        catergoryOverwrite = {
            guild.default_role: discord.PermissionOverwrite(read_messages=False, view_channel=False),
            guild.me: discord.PermissionOverwrite(read_messages=True, view_channel=True),
            guild.get_role(member): discord.PermissionOverwrite(read_messages=False, view_channel=False)
        }

category = await guild.create_category(name="RECORDS", overwrites=catergoryOverwrite, position=0)

is throwing me an error

Traceback (most recent call last):
  File "path\to\project\venv\lib\site-packages\discord\commands\core.py", line 124, in wrapped
    ret = await coro(arg)
  File "path\to\project\venv\lib\site-packages\discord\commands\core.py", line 978, in _invoke
    await self.callback(self.cog, ctx, **kwargs)
  File "path\to\project\cogs\test.py", line 43, in setuporder
    category = await guild.create_category(name="RECORDS", overwrites=catergoryOverwrite, position=0)
  File "path\to\project\venv\lib\site-packages\discord\guild.py", line 1586, in create_category
    data = await self._create_channel(
  File "path\to\project\venv\lib\site-packages\discord\guild.py", line 1142, in _create_channel
    "id": target.id,
AttributeError: 'NoneType' object has no attribute 'id'
#

create channel works properly but create category causes an error

grizzled sentinel
leaden relic
#

hmmm let me try without the permission for the role

leaden relic
#

thanks

grizzled sentinel
#

So you will need to check if the role is none than fetch it instead 👍

errant craneBOT
#

An HTTP exception has occured: 400 HTTPException: Invalid Form Body
In data.components.0.components.0.url: Not a well formed URL.

leaden relic
fervent cradle
#

What is a difference between discord.Bot and discord.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)
proud mason
#

(each class has all features of the class above it)

soft girder
#

How can I make the buttons have the same size?

#

@proud mason

silver moat
soft girder
#

Oh ... 😦

white scarab
#

Is there any way to control any Uncaught exception?
I would like to be able to do something before the bot crashes.

silver moat
leaden relic
#

is there an easy a way to make all views persistent?

maybe by using custom_id

grizzled sentinel
#

Not exactly sure what you mean. Persistent views are just views with no timeout and all items have a custom_id

leaden relic
#

i mean watching all the views you create and making sure they are all persistent is hard

ex is the ticket bot
each close button ticket needs their own persistence

uncut current
#

it doesn't need to have a different persistent id for each button

leaden relic
grizzled sentinel
#

It depends on what info you would need. I gtg now be back later

leaden relic
uncut current
leaden relic
grizzled sentinel
thorny kindle
#

How would i cancel a command after a set of time? Just using this?:

import time

-discord command bla bla bla-
time.sleep(10)
return
```?
full basin
#

what does the user need to do for it not to cancel

#

how does the command work

#

and no, you dont use the time lib in async enviroments

thorny kindle
#

So i have a rock paper scissors button thing, But it works all the time until bot resets. How would i cancel that time after like 10 seconds?

full basin
#

give it the view a timeout?..

thorny kindle
#

?

full basin
#

if you have buttons, you have a view, if you have a view you can give it a timeout and disable the buttons on timeout

thorny kindle
#

Oh ok.

#
@bot.slash_command()
async def button(ctx):
    await ctx.respond('Rock, Paper, scissors', view=RPS(timeout=10))
#

So like that then?

full basin
#

try it and see

thorny kindle
#

Nah, didnt work

#

Ok, i think i got it now. Changed it to the parent class with the timeout=10

#

Epic. Works 👍

alpine kernel
#

I have a printer function that displays a refreshing 'dashboard' that has quite a few calls to a local db to pull data. Some consequences of this are that when attempting to stop the bot (using keyboard interrupt) it seems to have to wait for the printer function to 'finish' as it takes a good 15-30s to stop the bot.

wondering if I'm doing something wrong or if this is expected using loop tasks

#

nevermind, had the brilliant idea of turning logging from info to debug, looks like i'm making a lot of suspicious calls somewhere >_>

elfin escarp
#

Why would a button work in one server but not work in another server? Well, more specifically it works but doesn't send the response and rather gets the Unknown Interaction error?

#

Nvm on that ^ just needed to defer the response while bot queried the google sheet

alpine kernel
#

how is a bot's guild member cache determined (without members intent)? just people who have interacted with the bot? or does the bot get an initial package of 'active' members?

#

I'm trying to reduce my fetches of members, and opting to use get instead of members intent, but wondering if that's going to cause a lot of misses on cache and confusion on the users when they see "missed cache" heh

limber urchin
#

Why not just get from the cache and if that returns None, use fetch?

alpine kernel
#

that's pretty true, I was just hoping to pre-fetch I guess, or rather try not to bombard the api with 50 some requests at one time, but even that I could limit in other ways

#

I get pretty stubborn when I choose a course of action heh but you're right

limber urchin
#

Well if you have a specific use case you can always just work on caching the members yourself in some way

alpine kernel
#

nah i'm just being lazy and dumb and expecting there to be an api to solve my problem instead of changing a database query to limit the number of returns, I really only need <20 get/fetches but right now my database is returning everying and i'm sorting and querying everything -.-

round rivet
#

what are you using this for

#

@alpine kernel

alpine kernel
#

basically a timekeeping system that refreshes once a minute and shows leaderboard for who's highest

round rivet
#

public bot?

#

100 servers

#

it might be worth it to get members intents

alpine kernel
#

nah private, 1 server, 1 test. I think discord would hire hitmen on me if it was public heh

round rivet
#

yeah just turn on members

alpine kernel
#

aight, I'll think about it, just wanted to try out 'best practices' heh

round rivet
#

best practice is turn it on if you need it

alpine kernel
#

NODDERS but if it was a >100 server bot, would you suggest not turning it on?

round rivet
#

depends on how the leaderboard works

#

i'd probably still say yes

alpine kernel
#

monkaHmm ok thanks heh

#

ok, kinda hard determining new discord features/systems if the intent of it is to move away from it or not, like application commands, i imagine discord's idea is to transition fully to that in the future, but cant be sure

#

guess I could read all the blogs

silver moat
# alpine kernel ok, kinda hard determining new discord features/systems if the intent of it is t...
alpine kernel
#

thanks 🙂

#

yeah that doc makes sense, it's something (somewhat) in the back of my head and want to do a good job, but this is just a small fun project for me all the same

#

all the same I got some paths forward, thanks!

zinc cloak
#

Is there a way to make a select menu reselectable? As in, the same values can be inputted if the menu is selected again?

#

Nvm, that's probably a discord limitation

hybrid flower
#

hi all, I use slash_command load some cogs, but the commands in cogs are not sync to my server, do I need to do something additional? I've restarted discord app.

young bone
hybrid flower
young bone
hybrid flower
#

What's the difference between Bot.sync_commands & Bot.register_commands? I'm confused by the document

silver moat
#

one of them doesn't exist

hybrid flower
oak elm
#

Is there a way I can get an announcement channel message using the invite link without joining the server by discord api?

young bone
soft girder
#

wtf

soft girder
#

who can help me?

#
@discord.ui.button( label="Confirm participation",custom_id="button-1",emoji="✅",style=discord.ButtonStyle.success)
    async def button_callback(self, button: discord.ui.Button, interaction):
        #await interaction.response.send_message(f"You confirm participation.",ephemeral = True)

        guild = interaction.guild_id
        msg = interaction.message
        user = interaction.user

        data4=f"SELECT id FROM teamlist WHERE server_id = {guild} AND id={user.id}"

        cursor.execute(data4)
        item3 = cursor.fetchone()
        db.commit()

        if user.id == item3:
            cursor.execute(f"UPDATE teamlist SET status = '✅' WHERE server_id = {guild} AND id={user.id}")
            db.commit()

            cursor.execute(f"SELECT rowid,* FROM vipteamlist WHERE server_id = {guild}")
            item2 = cursor.fetchmany(4)
            db.commit()
            b = ""
....
#

this code didn't work

#

but didn't have error

soft girder
#

@proud mason

proud mason
hybrid flower
#

is there a api for bot to get the guilds with a member together?

grizzled sentinel
dry fulcrum
#

quick question, how do i embed a video (mainly youtube video) into a embed?

#

do i just add_image() it on?

young bone
#

yes

dry fulcrum
#

that didn't quite work..

#

i just ends up with this

young bone
dry fulcrum
#

No, it's a youtube video

young bone
#

that will not work

dry fulcrum
#

Then.. why did you answer yes?

#

and well, how can i do that?

#

Or is it just not possible yet

young bone
#

url=imageurl

proud mason
#

You could send a video link in the msg content part of the message

#

And discord will embed it in a standard way for you

dry fulcrum
#

got it then..

cerulean yacht
#

how can i send a paginator using select menu?

young bone
cerulean yacht
dry fulcrum
#

Question: what's the biggest file size a bot can send?

#

8MB like normal user or a higher limit?

cerulean yacht
full basin
cerulean yacht
#

👍

dry fulcrum
young bone
#

they have the limits like a normal user

dry fulcrum
#

but when the server is boosted, when users get the higher upload limit (50MB/100MB), do bots in the same server get the same benefit too?

#

when they send message in the server, of course

gleaming falcon
#

I feel like there's a way to pop a modal based on a dropdown selection, but didn't see any examples anywhere. Am I correct that this is possible?

proud mason
#

What does that even mean

#

If you mean send a modal, then yes you can

#

You can do it just like you would do with a button

gleaming falcon
#

...? Display the text input modal when selecting a particular value from a dropdown, similar to "popping one" from a button press

proud mason
#

Mhm ofc

#

Same as with buttons interaction.response.send_modal

gleaming falcon
#

Cool. Would I have to evaluate the Option value in the Dropdown callback?

proud mason
gleaming falcon
#

Okay, use case for clarity:

Five options in the dropdown; four presets and a fifth one that when you select it, displays a modal for custom input
So would the fifth one just need some value that is used in the callback to then display the Modal?

proud mason
#

Mhm

#

Yea would need to check if the option selected is the custom one

gleaming falcon
#

Cool, thanks. That helps me select a rabbit hole to go down.

proud mason
wintry wasp
#

I have a webserver listening for requests and I want to somehow couple it with a discord bot. Is there a way to invoke a method declared in a cog just by passing around the bot instance to the webserver? (similar to ctx.invoke but starting from a "higher level"). I know this is a weird question but bear with me.

proud mason
#

There is a library called better-ipc on GitHub

#

It works with pycord the last time i checked

wintry wasp
#

Thanks! I'll do that.

soft girder
#

@proud mason to the SelectMenu module can be changed presistent for permanent functioning as in buttons?

ocean pumice
#

What's wrong in this? It's telling that the "option" keyword is not valid

#
 @bot.command()
async def select_menu(interaction):
    the_options = [
        discord.SelectOption(label="Option 1", value="1"),
        discord.SelectOption(label="Option 2", value="2"),
        discord.SelectOption(label="Option 3", value="3")
    ]
    await interaction.response.send_message(
        "Please select an option:",
        components=[
            discord.SelectMenu(options=the_options, placeholder="Select an option", max_values=1, min_values=1, id="my_select_menu")
        ]
    )```
#

discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: SelectMenu.init() got an unexpected keyword argument 'options'

fervent cradle
#

i made an discord bot, in python, but whats the code for making channels, ive tried many things but mb you guys now something? you can dm me

proud mason
#

And see #help-rules

#

Dont ping for help...

winter condorBOT
proud mason
#

discord.SelectMenu is a library internal thing for select menus. Don't use that

ocean pumice
#

Thanks

proud mason
#

bruh who pinged

wintry wasp
#

Is there any alternative to cog_load? This is what I'm trying to achieve (this is discordpy code and I want to find a pycord equivalent)

#

Would on_ready achieve the same result?

proud mason
proud mason
wintry wasp
#

Ok that's not too bad, thanks

lost lodge
#

Hey guys!

How can i get the reaction user (like i did in this example, but it doesn't work)

for reaction in msg.reactions:
                        if reaction.user == self.bot:
                            if reaction.emoji == "✅":
                                last_counting_msg = msg
                                break```
full basin
#

.rtfm Message.reactions

full basin
#

Message.reactions returns a list Reaction objects

#

.rtfm Reaction

full basin
#

Read the docs.

lost lodge
#

ah

full basin
#

I literally provided you the doc links?..

lost lodge
full basin
#

Bro

#

Read the docs

#

A discord.Reaction object doesn't have a users attribute

#

It has a method

proud mason
#

*async iterator to be precise

blissful hazel
#

*use async for to read it

soft girder
#

@proud mason

#

How to make a similar function?

proud mason
proud mason
errant craneBOT
#

Here's the slash autocomplete example.

soft girder
#

Ok thanks

uncut current
#

is anyone able to tell me why this

    async def con_nodes(self):
        with open("lavalinks.json", "r") as f:
            data: dict = json.load(f)
        rand_idents = statics.random_node_idents()
        print(rand_idents)  # <---- the list is actually here
        await self.wait_until_ready()
        for node, values in data.items():
            identifier: str = random.choice(rand_idents)
            rand_idents = rand_idents.remove(identifier)
            identifier = f"'{identifier.upper()}'"

code gives me this

Ignoring exception in on_ready
Traceback (most recent call last):
  File "E:\DragonBot\venv\Lib\site-packages\discord\client.py", line 378, in _run_event
    await coro(*args, **kwargs)
  File "E:\DragonBot\DragonBot.py", line 100, in on_ready
    await self.con_nodes()
  File "E:\DragonBot\DragonBot.py", line 49, in con_nodes
    identifier: str = random.choice(rand_idents)
                      ^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\pauln\AppData\Local\Programs\Python\Python311\Lib\random.py", line 370, in choice
    raise IndexError('Cannot choose from an empty sequence')
IndexError: Cannot choose from an empty sequence

error?

I expect it to choose me a random name from this rand_idents = statics.random_node_idents() function which returns a list of str

blissful hazel
uncut current
#

yea it does

#

that is what confuses me too

#

ohh and btw it already chooses one name [ WARNING ] [14-03-23 21:44:23] [DragonLog] [DragonBot:75] : Node didn't respond: Lavalink 'ONION' didn't connect on http://127.0.0.1:2333

#

but after that it throws this error

#

even if I replace the function directly with the list it throws this error

#

btw I'm using python 3.11.1

#

I guess I found a workaround it's not nice, but it works i guess

    async def con_nodes(self):
        with open("lavalinks.json", "r") as f:
            data: dict = json.load(f)
        rand_idents = ['apple', ...]
        await self.wait_until_ready()
        for node, values in data.items():
            rand_num = random.randint(0, len(rand_idents))
            identifier = rand_idents[rand_num]
            rand_idents.pop(rand_num)
            identifier = identifier.upper()
gleaming falcon
#

If anyone knows offhand - when choosing to delete messages with a ban action, is bulk_message_delete called, or just message_delete for each?

(Answer: message_delete. However, my plan was to show the message that got someone banned, and there's no real way to correlate. Could prob report the last message, though)

uncut current
turbid ginkgo
#

Perhaps I'm missing something, but I gave details to a slash command where there is only one option that should be set 'required'. I gave the option the required=True property, but it displays as a "optional".

turbid ginkgo
#

It works fine, I only need the option to be displayed as a required option

#

I'm guessing I'm missing something

full basin
#

That makes it automatically non required

torpid wraith
#

How would I go about creating a slash command group within a cog?

#

I use the slash_command decorator and I'm assuming I need to call bot.create_group(), but I'm not sure how to call bot correctly within the cog.

round rivet
#

you can use discord.SlashCommandGroup

errant craneBOT
#

Here's the slash cog groups example.

torpid wraith
#

Tyvm. I see add_application_command(groupVar) is not called in the example, but I thought it had to be when using SlashCommandGroup?

silver moat
#

Not in cogs.

torpid wraith
#

Side question: If I wanted to set default_permissions, would I do that with the groupVar decorator or the discord decorator?

silver moat
torpid wraith
#

Trying to do something like this (will move to thread if requested):

# Within Cog class
# <__init__ code here>

praise = discord.SlashCommandGroup("praise", "Praise people")

@praise.command(name = "set", description="Set number of praises for user")
@discord.default_permissions(
    administrator=True,
) # Only members with admin can use this command.
async def set(self, ctx, member: discord.Option(Member), praises: discord.Option(int)):
    # does stuff```
#

I think @discord.default_permissions is correct, but I'm not sure...
I'm now getting NameError: name 'Member' is not defined, but I thought Member was a valid option for discord.Option?

torpid wraith
silver moat
torpid wraith
silver moat
#

As long as it applies to the whole cog, it is fine

torpid wraith
#

If I wanted the permissions to apply to the whole cog, is there a permissions kwarg for the cog class?

silver moat
#

afaik no

torpid wraith
#

Ahh, because permissions are a decorator, and the command attributes of the class get directly passed to the kwargs of the command (which guild_id is one of the many).

#

This has been a journey to learn 😅 Appreciate your help. I'm used to Java and this is wildly different...

silver moat
#

I don't think the Java Discord API even has cogs

torpid wraith
#

Cogs just seem like helpful code organization by splitting up code into external classes, so I thought it would be a good investment to learn early. It's more so decorators and kwargs that are throwing me for a loop... Like, the documentation states to just pass whatever kwargs you want to the function, but never states what kwargs are supported by each function.

limber urchin
silver moat
#

Sadly that doesn't support the default_permissions factor.

limber urchin
#

Right

undone falcon
#

Is there a way to run a function before all commands in a Cog (like a before_command() or something like that)

silver moat
undone falcon
#

Thank you !

tidal grail
#

I want to code slash command and normal command separately using pycord I don't want to use bridge any other alternative ways?

undone falcon
silver moat
silver moat
undone falcon
#

I see and can you call the before function with custom arguments? For exemple I know all the commands in my cog take a role as parameter

undone falcon
#

Yess but sometimes their is workaround to do it, or the doc is just outdated

#

So we never know

limber urchin
#

If the docs say that a method takes one parameter, there is never a workaround to magically add another parameter.

silver moat
undone falcon
#

I see thank you !!

#

It is exactly what I was searching for

undone falcon
limber urchin
#

which you would have found if you read them

silver moat
#

you both should just chillax

limber urchin
#

huh?

torpid wraith
#

Is it possible to have a default command for a SlashCommandGroup? What would that look like?

limber urchin
#

It is not, Discord removed that feature

torpid wraith
#

aww sadge

#

Follow up: If I define a slash command with the same name as a group, I'm assuming it will get mad?

limber urchin
#

Yeah, I think so

torpid wraith
#

Welp, I tried, lol peeposadrain

torpid wraith
#

Can I have an on_message event method in both bot.py and a cog?

silver moat
#

yes

torpid wraith
#

tyvm

#

I'm assuming it would look like this?

# Cog file
from discord.ext import commands

@commands.Cog.listener()
async def on_message(self, message):
  # Do stuff...```
silver moat
torpid wraith
#

Good now?

silver moat
#

.tag tias

winter condorBOT
prisma atlas
#

I was wondering how to make an on_message event where the bot detects embeds it has sent itself and only change the color of the embed leaving the content the same?

silver moat
prisma atlas
silver moat
#

.rtfm message.embeds

silver moat
#

.rtfm message.edit

prisma atlas
#

Ahh thanks a lot!!

royal copper
#

not sure if this is a good channel to ask this, but I don't know that much javascript so what does this do? or what is it for? (docs/_static/js/custom.js)

silver moat
royal copper
#

well yeah, but it's in the library, maybe not like the actual library but it's in the github repo, where else am I supposed to ask this? I thought it might be specific to this use case since google didn't provide any help

silver moat
limber urchin
royal copper
#

why are you guys so aggressive

#

this is why people are afraid to ask questions

limber urchin
#

If that's "aggressive" then you're in for a treat by being on the internet

royal copper
#

well imo a better way a helper in a programming discord server's help channel could have said that would be smth like "I'm not sure what this does but this isn't a good place to ask, you could try asking in a javascript discord server, they might be able to help you better"

#

but that's just a suggestion

#

sorry if I offended anyone

limber urchin
#

Well sometimes you assume that people read #how-to-get-help and #help-rules before asking a question. And by reading those it should be pretty obvious that this is not the right place to ask a JavaScript question.

#

But I'm sorry if that was too aggressive

royal copper
#

I'll admit I didn't read those before posting, I don't see anywhere where it says it should be python only, but I guess that should just be inferred, and this is a help channel for the pycord api, not help for understanding internal code

limber urchin
#

Where did you even find that code anyways?

royal copper
#

I noticed it was something added after forking and the commit comment was "improve toctrees" but removing it didn't seem to change anything

#

but it doesn't really matter I was just curious

#

ah looks like it's part of a scrollspy script library in js, weird that it didn't come up on google, I need to get better at searching for things

royal copper
#

I know

proud mason
#

I hope you meant it didn't change docs. Because that won't change the library 💀

royal copper
#

yeah that's what I meant

#

I know how to build sphinx docs

proud mason
#

Ah my bad lol

royal copper
#

no worries

proud mason
#

Because most helpers here don't deal with docs

coral charm
royal copper
#

I don't think they recognized it was a part of the package at first which is understandable

limber urchin
royal copper
coral charm
#

i like your way of cherrypicking a word and refusing to address the main point brought up in my message

#

anyway whatever who cares you're hte helpers anyway

limber urchin
young bone
coral charm
#

fr

limber urchin
silver moat
#

@coral charm @limber urchin could you maybe take this to DMs?

coral charm
#

eh i just wanted to point out that like 2 different helpers saw javascript and instantly told them to screw of before even attempting to figure out where the code came from and if it was relavent

#

i'm done here i dont really care about pycord i dont wnat to continue this conversation anyway

proud mason
#

This is a channel to get help on how to use the library, not how the library was made

cerulean yacht
#

is it possible to edit a message and send paginator?

turbid ginkgo
#

I used the example for the on_message_edit() event in the pycord git and the before.content and after.contect show as an empty string for some reason.

#

I tried to send the message with the tables themselves and it showed correctly with the message, channel and author info

obtuse juncoBOT
#

https://docs.pycord.dev/en/master/intents.html
https://discord.com/developers/docs/topics/gateway#gateway-intents

import discord
from discord.ext import commands

# Get specific intents for fine control
intents = discord.Intents()
intents.emojis = True
intents.guilds = True
intents.messages = True  # Required for prefix commands!
...
# Get all non-priveliged intents; this excludes presences, members and message_content 
intents = discord.Intents.default()

# Set priveliged intents: these must be enabled on dev portal
intents.members = True
intents.presences = True
intents.message_content = True  # Required for prefix commands >= 2.0.0b5

# Get all intents; all intents must be enabled on dev portal.
intents = discord.Intents.all()

# Apply intents when creating your bot
bot = commands.bot(prefix="?", intents=intents)
Discord Developer Portal

Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.

proud mason
#

You need message content intents

#

.rtfm message_content

proud mason
#

1st one

turbid ginkgo
#

I do have message content intents enabled

proud mason
soft girder
#

Now I am writing a bot and I would like to clarify ... If I make 3 buttons in this code, then by clicking on the second one, the first two should turn off and the third one will turn on. Is this possible?

grizzled sentinel
soft girder
#

Ок thanks

uncut current
#

so I got a small problem with a raspberry pi cronjob and I am sure someone here knows what I have to change to fix it.
I got these three lines for cronjobs

00 04 * * * sudo shutdown -r now
@reboot sleep 30; cd "/home/pi/Desktop/Bot V4.0" ; python3 main.py &
@reboot sleep 60; cd "/home/pi/Desktop/MusicDragon"; source venv/bin/activate ; python3 DragonBot.py &

so this night the first bot started but the second didn't start, I'd like to start both, how is this possible?

#

btw its the sudo crontab

proud mason
silver moat
#

No crossposting

soft girder
#

What?

#

Ok ..

sweet wren
#

so applications commands such as slash commands, cant use it own error handler per command? it needs a global? ```py

@CLIENT.event
async def on_application_command_error(ctx, error):```

sweet wren
#

like for example, trying to send an error message stating a user is on cooldown, doesn't work if is like commandname.error

young bone
#

async def test():

@test.error
async def test_error()
#

?

sweet wren
#

but on ly for on_application_command_error

young bone
fervent cradle
#
async def button_callback(interaction:discord.Interaction):
        ticket_category = discord.utils.get(interaction.guild.categories, name='Tickets')
        channel = await ctx.guild.create_text_channel(f"ticket-{format(ticketNum, '04d')}", category=ticket_category)
        await channel.set_permissions(interaction.user, overwrite=overwrite)

        await interaction.response.send_message(f"Created Ticket at {channel.mention}", ephemeral=True)

        embed = discord.Embed(title="Support Ticket Opened!", description="Thank you for contacting support.\nPlease describe your intent for the ticket and wait for a response.", color=BLUE_COLOR)
        embed.set_footer(icon_url=interaction.guild.icon, text="Powered by dragsim.org")
        await channel.send(embed=embed)

    button.callback = button_callback

Error:

In embeds.0.footer.icon_url: Scheme "none" is not supported. Scheme must be one of ('http', 'https').```
#

on the await channel.send()

silver moat
#

An icon isn't a url.

#

.rtfm guild.icon

soft girder
#

Squid can You help me?

grizzled sentinel
soft girder
#

Is it possible to initially make the button unavailable.

true pewter
#

I'm using using the @Option, the problem is that my idea is to make it so that if you select the discord.Member you can't choose the discord.TextChannel. I don't know if I've made myself clear.

fallen cove
#

how can you convert a channel variable to the same as ctx.channel which has the (property) instead of (variable)?

grizzled sentinel
grizzled sentinel
grizzled sentinel
#

Accessing it should work the same

fallen cove
proud mason
#

bro who tf keeps pinging me

#

@waxen whale please find out rooSob

warm cargo
#

am i missing something? this is being done inside a cog if it matters

grizzled sentinel
grizzled sentinel
#

?tag idw

obtuse juncoBOT
#

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.

warm cargo
#

i have waited for 20 minutes for it to update

waxen whale
young bone
#

Ghost ping?

proud mason
proud mason
waxen whale
#

Imma add a ping logger when I’m home

distant roost
#

Does someone know how i use slash commands in an cog? Is it just @commands.slash_command or something different because the command isn’t showing up for me

waxen whale
#

Read the docs

distant roost
#

I think its because of me but i don’t find it there

waxen whale
#

We have various examples and guides

proud mason
mossy holly
#

Hey guys quick question:
I'm using git to keep track of all my development, and I'll soon launch my bot on a public server (it'll be a server specific bot, so only used on this one (and my test server))

So I'm making a development branch (which will be used to try my future features etc. so obviously it'll have a different token)

I have a bash script to launch my bot:
start.sh

#! /usr/bin/bash

day=$(date +"%F")
timestamp=$(date +"%H_%M_%S")

# Creating a day log folder if not already created
mkdir -p logs/$day


# To keep track of the current branch
current_branch=$(git branch --show-current)

# To launch from the stable version of the bot
git checkout master

nohup python3 -u NameOfBot/main.py &> "logs/$day/nohup_$timestamp.out" &
echo $! > pid  # Used in stop.sh to kill the process
echo Starting bot...

# Coming back on our working branch after launching the bot
git checkout $current_branch

My question is: When doing this (i.e switching branch to launch the bot then coming back to the working branch once the bot is launched), will the writes / read to the database be on the good version of the database ? My database is in the git directory but is ignored (in .gitignore)

Or should I put it elsewhere to be sure ? Same question as I have logs and resources folder (both untracked as well)

Thanks if someone can help 😄

proud mason
#

you could have the db files in a folder, and the file name could be the current branch name. then set the current branch in an env var in your bash. use this var to connect to your db

mossy holly
leaden relic
#

how do you dynamically set whitelisted guilds for slash command group's guild_ids using data from database?

alpine kernel
#

mmm like is there a question about doing anything specific? it seems pretty cut and dry:
-have whitelisted guilds in the db
-when using a slashcommand:
--grab whitelisted guilds from db
--check ctx.guild.id is in the whitelist

leaden relic
#

i tried using beanie and it throws me a collection not initialized

#

i fetched the data from the database using async client and asyncio.run and throws me that error

alpine kernel
#

seems like a beanie issue, something that i've never used /shrug

leaden relic
#

my init database is in on_connect event of the main

#

hmmm then i'll try using sync approach for fetching the guild ids

leaden relic
#

yeah i saw that too

#

using sync method it worked

alpine kernel
#

mmm maybe didnt await somewhere? dunno would need a bit of debugging

leaden relic
#

now my problem is the commands are still showing on both servers 🤣

alpine kernel
#

is there a way to check rate limits on a interaction call? trying to determine how often i can safely update channel names, apparently that's pretty restricted

cyan quail
alpine kernel
#

okey, was a weird request from a 'client' but at least i got something to tell them heh

cyan quail
#

generally you can only get the ratelimit from discord if you make the request directly to get the headers, don't think the library stores them elsewhere

alpine kernel
#

is there any reference for rate limits? or you just kinda know that

#

yeah that's fine just need helpful people like y'all to answer that heh

cyan quail
#

some people just found out through testing, discord doesn't have a list of ratelimits because most are dynamic and per-route

alpine kernel
#

yeah i respect that kinda security by obscurity

void abyss
#

hey my commands aren't registering any help?

#
import discord
from discord.ext import commands, bridge

class Verify(commands.cog):
    def __init__(self, bot):
        self.bot = bot
    @bridge.bridge_command()
    async def verify(self, ctx, msgid:int):
        await ctx.fetch_message(msgid)
        embed = discord.Embed(title = f"sent verification to {msgid}")
        embed.add_field(f"[messagelink]({msgid.jump_url})")
        msgid.add_reaction("✅")

        await ctx.respond(embed = embed)
def setup(bot):
    bot.add_cog(Verify(bot))```
#
discord.ext.commands.errors.CommandNotFound: Command "verify" is not found```
alpine kernel
#

havent used bridge commands but maybe try

@bridge.bridge_command(name="verify")

?

void abyss
#

they dont take names as parameters

alpine kernel
#

not a purple name though, so I could be stupid

#

did the error come from using it as slash command or custom prefix command?

void abyss
#

i checked the docs and i cant find anything that suggest name as a parameter infact the guide makes it seems like the opposite

#

also slash commands dont show

#

and prefix commands show the error seen above

alpine kernel
#

hmph, yeah looking at that and looks like everything should be fine

#

oh uh is class Verify(commands.cog): supposed to be capital Cog?

rare ice
#

yes

void abyss
#

OH

rare ice
#

commands.Cog

#

.rtfm commands.Cog

alpine kernel
#

one would think that would throw an error heh, maybe lower case is a base class?

rare ice
#

no

void abyss
#

its the commands.cog

rare ice
#

just use commands.Cog

#

don't overthink it

alpine kernel
#

cant help it

void abyss
#

nah thats def the error thank you

#

nope

#

not the issue

#

even with py commands.Cog i still get the error

alpine kernel
#

might take a few seconds to register the update?

#

I like to put a description on commands like '1' or '2' to see if the client hasnt updated the cache of commands, works for slash commands

void abyss
#

its a prefix command tho

#

bc the slash commands still havent shown

alpine kernel
#

yea, i think it should show as a slash command if everything is right though

#

can try and do ctrl-R to see if refreshing discord client helps

void abyss
#

that didnt work

alpine kernel
#

hmm :T

void abyss
#

this is annoyig

alpine kernel
#

and you saved the doc and restarted the bot script and everything?

void abyss
#

multiple times

alpine kernel
#

yea that's frustrating

void abyss
#

it loads the files so i know its not the command handler

alpine kernel
#

oh well, i see another bug

import discord
from discord.ext import commands, bridge

class Verify(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
    @bridge.bridge_command()
    async def verify(self, ctx, msgid:int):
        await ctx.fetch_message(msgid) # <- this doesnt get stored as a result
        embed = discord.Embed(title = f"sent verification to {msgid}")
        embed.add_field(f"[messagelink]({msgid.jump_url})") #<- this is still an int, and doesnt have a jump_url property
        msgid.add_reaction("✅")

        await ctx.respond(embed = embed)
def setup(bot):
    bot.add_cog(Verify(bot))
#

it doesnt solve not being able to do the command tho :T

void abyss
#

yeah i noticed the jump url thing

alpine kernel
#

can try pasting what you got now i guess

void abyss
#

its the exact same thing

#

just with commands.Cog

alpine kernel
#

can you try not having the msgid parameter? it might need to be a discord.Option

#

maybe it's just not finding it because it expects self.verify(ctx)

void abyss
#

fetch_message takes a int as the argument

#

bc its a id

alpine kernel
#

this is what I mean

async def verify(self, ctx, msgid: discord.Option(int, name="msgid", required=True)):
void abyss
#

oh

#

that

alpine kernel
#

it likely wont 'work' because id's are too big to pass to the javascript client

#

i've always had to take id's as strings then parse them into ints

void abyss
#

i dont think a parameter would keep a whole command from registering tho

alpine kernel
#

yeah not 100% sure about the internals but it's worth a shot

#

unless you get a purple name or that staff guy back here

void abyss
#

i mean

#

it looks like this

silver moat
#

.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)?

wintry wasp
#

So I have a command that looks up emojis via some API. It takes the name as the input. I'm defining an autocomplete method that does the API call and the filtering to return similar emotes. The API is returning a complex object and I eventually also want to get the emote URL from it. Is there a way to pass more data to the caller (command method) without breaking the autocomplete (since it probably wants a list of strings to be returned)?

silver moat
#

@void abyss could we move this to a thread?

void abyss
#

sure

wintry wasp
#

Right now I'm caching the response and redoing it in the caller but it isn't efficient.

#

Code looks something like this

async def trending_autocomplete(self, ctx: discord.commands.AutocompleteContext):
    # API call
    emotes = await self.get_trending_emotes(ctx.options["category"])
    return [emote['name'] for emote in emotes if emote['name'].lower().startswith(ctx.value.lower())]

@emote.command()
@option("category", description="What's the emote category?", autocomplete=category_autocomplete)
@option("name", description="What's the emote name?", autocomplete=trending_autocomplete)
async def find(self, ctx: discord.ApplicationContext, category: str, name: str):
    # Returns cached response
    emotes = await self.get_trending_emotes(category)
    # This is the emote object, not just the name
    selected_emote = [emote for emote in emotes if emote['name'].lower() == name.lower()]
    # Get the url
    ...
silver moat
wintry wasp
#

Oh, so I just have to put the keys as the name and the rest of the emoji object as the value

#

I'll try that, thanks!

silver moat
#

It could also look like this if you want more than just the url:

{
  "sad_face_emoji_name": {
    "url": "https://",
    "foo": "bar",
    "spam": "eggs"
  },
  "second emoji idk": {
  ...
  }
}
wintry wasp
#

Yea, that would be perfect

gaunt junco
#
async def search_options(options: List, ctx: discord.AutocompleteContext):
    return options

@bot.slash_command()
async def choose_food(
    ctx,
    food_type: discord.Option(str, "select your desired delacasy", autocomplete=search_options(["apple", "banana"]))
):
    await ctx.respond(food_type)

how would i go about including an additional parameter in the autocomplete function?
sry i dont entirely get function annotations

silver moat
#

Autocomplete should only be used for dynamic choices that update during runtime or more than 25 choices.

river dove
#

is there a limit on how many commands a bot can have

icy tulip
#

can you remove the buttons on a pagegroup used In a paginator If It only has one embed? nevermind I got It blobpain

gaunt junco
limber urchin
#

.rtfm discord.Option.choices

winter condorBOT
#

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

gaunt junco
#

tysm <3

wintry wasp
gaunt junco
limber urchin
gaunt junco
#

i see

#

thx again!

undone falcon
#

Can you print the traceback of a ApplicationCommandInvokeError ? When I try to do it it does:

Ignoring exception in on_application_command_error
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\rapha\AppData\Local\Programs\Python\Python311\Lib\traceback.py", line 187, in format_exc
    return "".join(format_exception(*sys.exc_info(), limit=limit, chain=chain))
                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\rapha\AppData\Local\Programs\Python\Python311\Lib\traceback.py", line 139, in format_exception
    te = TracebackException(type(value), value, tb, limit=limit, compact=True)
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\rapha\AppData\Local\Programs\Python\Python311\Lib\traceback.py", line 690, in __init__
    self.stack = StackSummary._extract_from_extended_frame_gen(
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\rapha\AppData\Local\Programs\Python\Python311\Lib\traceback.py", line 409, in _extract_from_extended_frame_gen
    if limit >= 0:
       ^^^^^^^^^^
TypeError: '>=' not supported between instances of 'ApplicationCommandInvokeError' and 'int'
#

when running: traceback.format_exc(self.discord_exception)

#

I solved it by doing : ```python
"".join(traceback.format_tb(self.discord_exception.traceback))

rare garnet
#

Does anyone know how to properly process discord.User.public_flags

silver moat
rare garnet
#

I tried doing this

silver moat
#

.rtfm userflags

rare garnet
#

oh

rare garnet
rare garnet
#

for example, in my case, I have the active developer badge and the hype squad balence

#

so 4194304 + 256 = 4194560

silver moat
stuck canopy
#

does Command Groups work with Slash Commands?

limber urchin
#

.tias

winter condorBOT
stuck canopy
#

I am more curious about how you'd implement it though.

errant craneBOT
#

Here's the slash groups example.

stuck canopy
#

Ah okay ty.

#

Actually I am confused about how decorators work

#

o wait no i think i get it.

limber urchin
#

It's a good idea to understand what a decorator is before making a bot with pycord

stuck canopy
#

I mainly write C so Decorators are not sometihng I am familiar wit

gaunt junco
#

is there anyway to simplify this by returning the name of the variable or option?

stuck canopy
#

yeah but I dont tihnk it would save space.

limber urchin
stuck canopy
#

You're just changing the name and value in each of them, you could probably add each field to a list like ['rank', 'gamemode', 'time', 'players'] and then iterate over it and add_field for i I guess.

#

But yeah that's basic without overcomplicating.

gaunt junco
#

is there any way to return the name of a variable that's referenced in a for loop?

for f in [rank, gamemode, time, players]:
  embed.add_field(name=return_name_of_orignal_var(f), value=f, inline=True)
stuck canopy
#

Yeah there is.

#

func.__name__

gaunt junco
#

without using f"{a=}".split("=")[0]

#

oh dam'

#

does name apply to basic types as well

stuck canopy
stuck canopy
gaunt junco
#

is name a valid method for strings as well

stuck canopy
#

yeah it returns the name of a varialbe I think

gaunt junco
#

im just gonna stick with a hashmap

#

generally cleaner

#

thx for the help tho

stuck canopy
#

actually I dont think __name__ is a thing lmao

#

for vars I mean.

gaunt junco
#

it works for functions and methods tho
so
theoretically

def a():
  return "a but the letter"

print(a())
print(a.__name__)

:)

stuck canopy
#

works?

#

Idk I havent checked.

gaunt junco
#

yea

stuck canopy
#

also what does this erorr entail? 'dict' object has no attribute 'cog'

ornate current
#

should i make some sort of cache for gettings prefix from mongodb?

#

reading data directly from mongo would consume alot

stuck canopy
torpid wraith
#

I have this, but it will only print to console if the bot is mentioned. What stupid little thing am I missing? 😅

@commands.Cog.listener()
async def on_message(self, message):
    print(message.content)```
#

Oh, does it need Message Content Intent?

#

im dumb...

young bone
young bone
#

@torpid wraith you should add both message intents

soft girder
#

Is it possible to make the discord bot leave the link to the message written earlier.

#

I need the bot to insert a link into the gray button to the previous message where the green and red buttons are

soft girder
grizzled sentinel
young bone
grizzled sentinel
#

@strong crypt
This the pycord the help server for making discord bots.
I suggest you join the python help server instead for general python questions the server at the bottom of the next message.

obtuse juncoBOT
#

its is very difficult to help you if you don't understand python first.
As it stands, you do not or cannot show that you understand the basic fundamentals of Python. Please continue to learn Python first, as pycord is a Python framework and as such requires that you have a confident grasp on these fundamentals . For now, pause your current project and when you have learned enough Python you can then pick it back up and continue where you left off (if at all possible).** You cannot drive a truck if you do not know how to drive at all.**

cool free resources are
w3school
freecodecamp.org

there are also a lot of python programming tutorials out there a youtube search will give a lot awesome content. If you need help with python there is a python server for that where they will be more that happy to help you with these thing, you can also ask for python help in #881309540639997952.

python server: https://discord.gg/python

gaunt junco
#

is there any method to create an invite in a particular channel given its id
mega small brain question but i cant seem to find it in the documentation

dusty linden
gaunt junco
#

lmao that's it

#

thx man :)

soft girder
#

Is it possible to write a button so that when the administrator clicks on it,then the author of the command is given a certain role.

gaunt junco
#

having some issues integrate the invite into the embed

details = {
    "Rank":rank,
    "Gamemode":gamemode,
    "Time":time,
    "Players":players,
}

if voice_channel:
    details["Voice Channel"] = str(voice_channel.create_invite())

embed = discord.Embed(
    title="The Finals - NA LFG",
    description=f"{ctx.author.name} is looking for a group!",
    color=discord.Color.from_rgb(210, 31, 60)
)

embed.set_thumbnail(url=str(ctx.author.display_avatar.url))

for k, v in details.items():
    embed.add_field(name=k, value=v, inline=True)

await ctx.respond(embed=embed)

do i have to specify await in this instance where im creating an invite?

somber pelican
soft girder
#

Is it possible to write a button so that when the administrator clicks on it,then the author of the command is given a certain role.

soft girder
proud mason
soft girder
proud mason
soft girder
#

Sorry im bigginet

proud mason
#

That would be the equivalent of writing the whole code ngl

#

I'll write a example

young bone
soft girder
#

@young bone I already have code

full basin
#

Just pass the value to the view's init

soft girder
#
class StartRegistrationButton(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)
    
    @discord.ui.button( label="Start registration",custom_id="button-13",emoji="▶",style=discord.ButtonStyle.primary,row=3)
    async def startreg_button_callback(self, button: discord.ui.Button, interaction):
        await interaction.response.edit_message(view=self)

        if interaction.user.guild_permissions.administrator==True:
             if ctx.guild.id == 944934277777326090:
                 guild = bot.get_guild(944934277777326090)
                 role=guild.get_role(1064856142259425350)
                 await author.add_roles(role,reason=None, atomic=True)
             if ctx.guild.id == 769823680695107594:
                 guild = bot.get_guild(769823680695107594)
                 role=guild.get_role(776528911269363775)
                 await author.add_roles(role,reason=None, atomic=True)
        else:
            pass

#
@commands.guild_only()
@bot.slash_command(name='registration', description='Write down command data.',guild_ids=[944934277777326090,769823680695107594])
async def reg(ctx):

    await ctx.send("Smth",view=StartRegistrationButton())


full basin
#

Thats a modal, not a button?

soft girder
#

I thought to put the class in the command

full basin
#

No

full basin
young bone
#

also that ^

full basin
soft girder
full basin
#

What button

#

There's literally no button there

soft girder
#

@full basin ok, I'll give you an example of a button

#

5 minutes

soft girder
#

All I need is some way to save ID author outside command.

#

So that later if the admin clicks on this button, the author will be given a role.

proud mason
#

self.auth_id = ...

#

Accept a parameter for the id in the view init

proud mason
#

While creating the view object in the command, pass the author id to it

soft girder
#

interaction.client is this not the right way?

proud mason
soft girder
#

what wrong i do

#
class RoleButton(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)
    

    @discord.ui.button( label="Registration ended or suspended",custom_id="button-101",emoji="📝",style=discord.ButtonStyle.success,row=1)
    async def reg2_button_callback(self, button: discord.ui.Button, interaction):
        await interaction.response.edit_message(view=self)

        user = self.auth_id

        await interaction.response.send_message(f"{user}")

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


            self.add_item(discord.ui.InputText(label="Team name:",min_length=1,max_length=25,placeholder="Enter team name." ,style=discord.InputTextStyle.long))
            self.add_item(discord.ui.InputText(label="Tag:",max_length=8,placeholder="Enter command tag.", style=discord.InputTextStyle.multiline))
            self.add_item(discord.ui.InputText(label="Players(1-6):",max_length=200,placeholder="P1.Player1\nP2.Player2\nP3.Player3\nP4.Player4\n ", style=discord.InputTextStyle.paragraph))
            self.add_item(discord.ui.InputText(label="Troi spot:",max_length=70,placeholder="Enter TROI spot.", style=discord.InputTextStyle.multiline))
            self.add_item(discord.ui.InputText(label="Erangel spot:",max_length=70,placeholder="Enter ERANGEL spot.", style=discord.InputTextStyle.multiline))

        async def callback(self, interaction: discord.Interaction):

            guild = interaction.guild_id
            author = interaction.user

            self.auth_id=interaction.user

            if self.children[0].value == 'MARIARH':
                await interaction.response.send_message(f"Team banned")
            else:

                team_n = self.children[0].value.replace("'", "`", 1)

                tag_n = self.children[1].value.replace("'", "`", 1)
                
                cursor.execute(f"INSERT INTO teamlist VALUES ('{team_n }','{tag_n}','{author.id}','{guild}',' ')")
                db.commit()
                await interaction.response.send_message(f"{self.children[0].value} | {self.children[1].value} |{author.mention} \nPlayers:\n{self.children[2].value}\nTroi spot:{self.children[3].value}\nErangel spot:{self.children[4].value}",view=RoleButton())
                ```
soft girder
young bone
soft girder
#

But I do not really understand how to transform the idea into reality

young bone
#

You are asking so much stuff here?

soft girder
#

No.

#

I need only one

#

How I can save ID author

#

To class

soft girder
#

Please provide a link to an example.

#

I can explain again what I need.

young bone
soft girder
#

This is the problem that I know. But it is difficult for me to explain myself because I am from Ukraine.

#

It's hard for me to understand you.

#

Okay you can't help me:(

full basin
#

You were indeed helped.

#

You don't understand the answers because you don't know OOP.

blissful hazel
soft girder
#

That's why I'm asking for examples.

#

May small,but ex.

full basin
#

This is an object (class) attribute

dog = Dog()
dog.some_attribute = "hello"```
soft girder
#

Ok ..

limber urchin
#

You've been told before to learn Python before asking questions here