#Basic Pycord Help (Quick Questions Only)

1 messages · Page 63 of 1

flat reef
#

how do I customize the command of the "parent" of a group?

example:
group chat
if I run /chat, does something, if I run /chat delete, it does something else

I tried doing this but raised an error about unique commands:

    chat_group = SlashCommandGroup(
        "chat",
        "Commands about chatting with the bot",
    )

    @discord.slash_command()
    async def chat(self, mensagem: discord.Option(str, description="Message to be sent to the bot")):
        pass```
lone kiln
#

But.. When I do, it tells me that "[\'stuff1\']" can't be resolved to a str '-'

proud mason
#

pretty sure you would need interaction check. views dont go through an event like slash cmds. they use their own internal listener

#

what you can rather do is

#

make a subclass of discord.ui.View that implements the interaction_check. and inherit all your views from this new class instead of discord.ui.View

i hope i explained decently

lone kiln
#

Found out why, can't send a list, had to do return [stuff for stuff in my_list]

proud mason
flat reef
#

ah ok, ty

soft girder
#

Hello everyone. I wanted to know how to implement the system. For example: I write the "registration" command, and the bot answers me "Check your slot number 23 in channel # .." After that, I go to the previously specified channel, and the bot itself changes the message and adds my name to slot 23.

#

I already thought about doing it through @bot.event, but then after reading the API ref I didn’t find what I needed.

#

It is necessary to track this message and its content somehow.

#

I'm not asking you to write code. I'll be glad if you direct me to the right idea.

blissful hazel
#

How do I check if a permission string is a valid permission?

blissful hazel
#

Try using Channel.fetch_message

#

You can also store the channel id's

proud mason
#

or actually, channel id with the message object will make more sense

#

i assume you would have some logic (or random) to determine which channel the user is to be added in

#

then yea, based on that edit the message from that channel

#

Unless...

#

you plan on sending a separate message for each slot, and not edit a single message again an again

#

this would be fairly simple

proud mason
#

not sure but check what Permissions.VALID_FLAGS is

#

you might need an object of Permissions

#

.tias

winter condorBOT
calm plume
#

is there a quick way to check if user has reacted on message beforehand

#

like not emit a event

#

and i want it fast

#

bc i have multiple reactions i need to check

young bone
calm plume
#

the reaction_add and raw_reaction_add

#

but say the bot is offline

#

someone decides to react to a message

#

how would i make it so the bot checks the reactions(we are talking a couple of 10-20) multiplied by 2 which are the amount of reactions

#

u start to see some stuff pilling up

#

also pls do not reccomend me msg.reactions[index].users()

#

i've tried it and takes 11 seconds to get the reactions for all msgs

#

btw to top it all off

#

i need the count

cyan quail
#

fwiw you can just attempt to check them all at startup and let it ratelimit since if it does it'll just queue the rest of the operations

silent meadow
#

Hi i am woking on a stats command but it does not seem to work as I had indented it to work as

#

my server has 200 members but only shows 3 users

#

I have enabled the intents.members

#

but...

limber urchin
#

How are you fetching the member count? And is member intents enabled in the developer portal?

silent meadow
#

server count is just fine

silent meadow
#

one sec

users = sum([len(guild.members) for guild in client.guilds])
silver moat
#

bot.users exists

silent meadow
silver moat
#

sure

limber urchin
#

There is also guild.member_count instead of len(guild.members)

#

but bot.users is probably the best

silent meadow
silent meadow
#

@silver moat shows 0 now ☠️

#
intents = discord.Intents.default()
intents.members = True
intents.guilds = True
intents.message_content = True
intents.voice_states = True
#

are these intents correctly enabled?

limber urchin
#

You might as well do discord.Intents.all() at that point

limber urchin
#

but yes, those should be enough for what you're doing

silent meadow
#

still shows 0

#

:/

silver moat
#

how are you applying your intents?

cerulean yacht
#

what the best way to handle errors?

#

like bad argument or something like that

#

is it better to use a global error handler?

silver moat
#

depends

cerulean yacht
#

should i try it convert it in the code without using try and except then use global error handler

silver moat
#

Will an error like this happen in more than one cog/command?

cerulean yacht
#

yex

silver moat
#

Is your method of handling your error the same or similar regardless of command

cerulean yacht
#

same

silver moat
#

use the global handler then.

cerulean yacht
#

👍

#

thanks

silver moat
#

yw

limber urchin
#

No, how are you adding these intents to your bot?

#

that's just defining them

cerulean yacht
#

when you run it?

limber urchin
#

what?

#

that question was not for you

cerulean yacht
#

🤦 sorry

silver moat
silent meadow
#

like how?

#

i dont understand...

#

there is nothing else I did for intents

limber urchin
#

Just defining a variable called intents won't magically make your bot have those intents facepalm

silent meadow
#

i thought that it was enough

limber urchin
#

You pass them to your bot's init method as a kwarg

silent meadow
#

bro I am living under a rock

#

sheesh

silver moat
#

do you know what a kwarg is?

silent meadow
#

ikik

cerulean yacht
silver moat
#

if isinstance(exception, InvalidId):

cerulean yacht
#

its false 🤔

#

type of exception is discord.errors.ApplicationCommandInvokeError

meager heron
undone falcon
#

I am getting this error and I am not sure why. It happens when I do add_cog() I am following the example slash_cog_groups.py

#

this is the main file

young bone
undone falcon
#

2.4.0

fervent cradle
#

I have a bot that goes trough a list and sends every item as an embed in a message. How many embeds can a single message hold?

undone falcon
young bone
#

Oh yea

young bone
proud mason
fervent cradle
#

ok ty

proud mason
#

You can try it and see

undone falcon
#

but thanks !

ocean pumice
#

Wonders why the bot.process_commands doesnt work for me?

import discord

bot = discord.Bot()
option = discord.Option

@bot.event
async def on_ready():
    print(bot.user)

@bot.event
async def on_message(message):
    # do some extra stuff here

    await bot.process_commands(message)```
```AttributeError: 'Bot' object has no attribute 'process_commands'```
#

What I'm tryna do is to stop the on_message event from preventing slash commands to work

ocean pumice
#

Okey

#

Well it still prevents other slash commands from working

#

Whenever there's smth going on on the listen, as long as it's not finished slash commands won't work

young bone
ocean pumice
young bone
#

do you have anything else installed?

ocean pumice
#

I don't think so, can't find anything else related to discord

proud mason
#

On message will stop prefix cmds from working

#

discord.Bot does not have prefix cmds in it (see ?tag client)

#

That's why it doesn't have a method called process commands

#

In case you want to get a bit more technical-

#

Overriding on interaction will stop Slash cmds from working

#

To overcome that, you will use bot.process_application_commands

ocean pumice
#

I'm definitely not overriding anything, but I'm still getting blocked by the on_message thing

#

I did put a time.sleep in the on_message to behave things i would do in it, and it is preventing slash commands from working

#

Idk if the time.sleep is logical as it's not asyncio but i guess it is as i'm not going to do asynced things in it

ocean pumice
# young bone which slash command?

simple one for the moment ```py
@bot.command(guild_ids=[996922553266360360])
async def test(ctx):
if ctx.author == bot.user:
return

await ctx.respond("test")```
young bone
#

thats why the command doesn´t work

#

a bot cannot use slash commands

ocean pumice
#

I put it here by mistake but i think it wasnt working without it too

#

lemme check

#

Yea see

#
Traceback (most recent call last):
  File "C:\Users\sofia\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 124, in wrapped
    ret = await coro(arg)
  File "C:\Users\sofia\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 982, in _invoke
    await self.callback(ctx, **kwargs)
  File "d:\Programmation\the-killer\main.py", line 29, in test
    await ctx.respond("test")
  File "C:\Users\sofia\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\context.py", line 282, in respond
    return await self.interaction.response.send_message(
  File "C:\Users\sofia\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\interactions.py", line 825, in send_message
    await self._locked_response(
  File "C:\Users\sofia\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\interactions.py", line 1090, in _locked_response
    await coro
  File "C:\Users\sofia\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\webhook\async_.py", line 219, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction

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

Traceback (most recent call last):
  File "C:\Users\sofia\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 1114, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "C:\Users\sofia\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 375, in invoke
    await injected(ctx)
  File "C:\Users\sofia\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 132, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction```
young bone
#

can you show the full pip list

ocean pumice
errant craneBOT
#

discord/cog.py line 561

bot.add_command(command)```
proud mason
proud mason
#

do you have any blocking pieces of code anywhere else in your bot?

proud mason
ocean pumice
#

Now that I’m thinking in it, we shouldn’t use slash commands thaaat much. Like a couple of times a day…. But I still want to prevent the case where it’d not respond

#

I don’t know if I was clear-

timber skiff
#

How would one convert a emoji from it's sting name (ban_hamma, for example) to an emoji object?

proud mason
# ocean pumice I see So eventually what I’m going to do is to read every sing message written ...

it depends on the way you would be checking that. simple stuff like if "abc" in msg.content will be too fast to be blocking. doing that in a loop with 100 iterations probably wont to be noticeable either.
but it does get worse with more and more iterations. and if you have the bot in many high-activity servers, it can sure be bad. using regex patterns can be helpful, but they are a pain in the a**.

proud mason
# ocean pumice Not yet

ah hmm. can you reproduce this error with a very basic bot? that doesnt have anything other than this 1 slash command (and maybe an on ready listener)

#

if that works consistently, i would go on adding the bot's functionality in small chunks till the point it breaks

#

that helps you identify what causes the issue

#

Although i would really suggest setting auto_sync_commands to False

#

as you can get ratelimited

leaden relic
#

if you have multiple servers

and want a button that if you click would allow you to join the other server

how do you do that?

or the only way is for a link button to be attached with the invite link of the other servers or send a message with that link when the button is clicked?

leaden relic
proud mason
calm plume
#

so there is a method like select_user where it selects the user that has reacted by ID

#

and returns a member object

#

bc these are some cases where we quite need it as calling for a list everytime

#

and looping to try and find the author

#

is kinda slow

leaden relic
fervent cradle
#

I randomly get this error: Traceback (most recent call last): File "C:\Users\Pro8\Documents\Programmieren\Python\DC Bot\Testbot\main.py", line 11, in <module> bot = discord.Bot( ^^^^^^^^^^^ AttributeError: module 'discord' has no attribute 'Bot' yesterday everything works fine, but today I get this error. I didn't perform an update and my pycord version is 2.4

#

this is the code in the line py bot = discord.Bot( intents=intents, debug_guilds=[908704558157529098], status=status, activity=activity )

leaden relic
young bone
fervent cradle
#
discord.py==2.2.2
frozenlist==1.3.3
idna==3.4
multidict==6.0.4
py-cord==2.4.0
python-dotenv==1.0.0
validators==0.20.0
yarl==1.8.2
soft girder
young bone
fervent cradle
#
aiosignal==1.3.1
async-timeout==4.0.2
attrs==22.2.0
charset-normalizer==3.0.1
decorator==5.1.1
discord.py==2.2.2
frozenlist==1.3.3
idna==3.4
multidict==6.0.4
py-cord==2.4.0
python-dotenv==1.0.0
validators==0.20.0
yarl==1.8.2
#

here full list

soft girder
#

Hello. I need help. I am extracting a message from the database. It is tedious to extract the data while saving the account. Here is an example

young bone
#

uninstall py-cord and discord.py and reinstall py-cord

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

        await ctx.respond("Done.",ephemeral=True)
        a = ""
        i = 0
        for el in item:
            i+=1
            if i<13:
                a += f"**{i}**. __{el[1]}__ | {el[2]} | <@{el[3]}>\n"    
            elif 12<i<17:
                for el in item2:
                    a += f"**{i}**.:coin: __{el[1]}__ | {el[2]} | <@{el[3]}>\n"
            else:
                a += f"Reserve:red_circle:**{i}**. __{el[1]}__  | {el[2]}  | <@{el[3]}>\n"
        embed1 = discord.Embed(title =f":scroll: TEAM LIST :scroll:",description=f"**:clock1:Time: {time}**\n  \n{a}", colour = discord.Colour.embed_background())
        embed1.set_footer( text =f'To confirm participation, click on :white_check_mark:')
        #await ctx.send(embed = embed1,view=MyView())
        tlist = await ctx.send(embed = embed1)
        await tlist.add_reaction(":white_check_mark:")
        db.commit()
#

here you can see that lines 13-16 are skipped

fervent cradle
soft girder
#

How to do without skipping these lines

proud mason
#

rather, subtract 12 (or 13) from i and get object at that position from item2

#

also, you are adding 1 to i at the beginning of the loop block. this will cause you to skip the element at 0 index

#

dont forget that python list index starts from 0

cyan quail
#

what you're looking for doesn't exist on Discord's API, no matter what you have to iterate through reaction users

#

i guess maybe it'd be slightly more convenient by shortening your code by a line or two, but don't expect it to be any "faster"

proud mason
#

that should cut down the time drastically

astral mist
#
Traceback (most recent call last):
  File "C:\Users\Amin_PC\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\bot.py", line 1114, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "C:\Users\Amin_PC\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 375, in invoke
    await injected(ctx)
  File "C:\Users\Amin_PC\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\core.py", line 132, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: InvalidArgument: activity must derive from BaseActivity.


#

What dose this mean

proud mason
astral mist
proud mason
astral mist
#

await bot.change_presence(status=discord.Status.online, activity="somthing here")

astral mist
proud mason
#

once sec

astral mist
#

wait

proud mason
#

.rtfm bot.change_presence

astral mist
proud mason
#

.rtfm discord.BaseActivity

proud mason
astral mist
proud mason
#

any error?

proud mason
proud mason
astral mist
#
@bot.command(description="Changes the bot status")
async def change_status(ctx, status):
    if ctx.author.id == 764377311595855882:
        await bot.change_presence(status=discord.Status.online, activity=status)
    else:
        await ctx.response("nononoononon ur not the owner")   
#

this

proud mason
proud mason
#

you must pass a class of this

ocean pumice
# proud mason it depends on the way you would be checking that. simple stuff like `if "abc" in...

The bot will only serve in 1 server which has roughly one message every 5 seconds at the most active times, aaand the process for every message shouldn’t exceed 3 seconds I think…. I’ll go like that I guess
I got one last question to try limiting the slash getting timed out. Is it possible de make the wait time longer than 3 seconds? I saw some js bot doing that, I wonder if it’s possible in Python tho

proud mason
#

then you can send a followup within 15 mins

ocean pumice
#

.rtfm defer

ocean pumice
#

I’m afraid that it won’t work in my case, but I will try anyways

#

Thanks!

calm plume
proud mason
#

Although you should be careful of ratelimits

#

not sure about those

green hinge
#

Why don't my entries reduce when I enter a letter?

def get_user(ctx: discord.AutocompleteContext):
    guild = ctx.interaction.guild
    members = guild.members
    return [member.name for member in members]    

@slash_command(description="Erteile einem User die Whitelist")
async def wl(self, ctx, user: Option(str, autocomplete=get_user)):```
limber urchin
#

Because you're always returning all members?

#

And why are you doing that instead of just using discord.Member as the option type?

calm plume
#

the looping tbh is kinda O(n) or O(n^2)

#

it grows with the more input

proud mason
silver moat
#

big-o notation ≠ performance

calm plume
#

i kinda gave an example of how slow it is

proud mason
green hinge
limber urchin
#

And again, why aren't you just using discord.Member as the type for your option? That is quite literally a useless autocomplete

green hinge
limber urchin
#

Okay I'll ask a 3rd time then

#

Why are you not just using the discord.Member type for you option?

green hinge
limber urchin
#

.tias

winter condorBOT
green hinge
limber urchin
#

That happens automatically when you use the type?

green hinge
delicate harbor
cyan quail
#

because it is

simple forum
#
from discord.ext import commands
bot = commands.Bot(command_prefix='?')
@bot.command()
async def test(ctx, arg):
    await ctx.send(arg)


'?test arg' doesn't work and I can't find anywhere how to set up prefixes.

#

oh and ofcourse bot.run(token)

limber urchin
#

Do you have message content intents enabled?

simple forum
limber urchin
#

?tag intents

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.

fervent cradle
#

Why does this happend?

  File "C:\Users\Lorenz\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\bot.py", line 1114, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "C:\Users\Lorenz\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\commands\core.py", line 375, in invoke
    await injected(ctx)
  File "C:\Users\Lorenz\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\commands\core.py", line 132, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction```
limber urchin
#

Impossible to say if you don't show the code associated with it

fervent cradle
# limber urchin Impossible to say if you don't show the code associated with it
    def __init__(self):
        super().__init__(timeout=None)
        self.interaction_id = None
        self.interaction_token = None
        self.playing = False

    def set_interaction(self, interaction_id, interaction_token):
        self.interaction_id = interaction_id
        self.interaction_token = interaction_token

    def check_playing(self):
        if not self.playing:
            for child in self.children:
                child.disabled = True
            return False
        return True

    @discord.ui.button(label="Skip", style=discord.ButtonStyle.primary, emoji="⏭")
    async def skip_callback(self, button, interaction):
        if interaction.response.is_done():
            return
        voice_client = interaction.guild.voice_client
        if not voice_client:
            embed = discord.Embed(
                description=f"🤨 I'm currently not in a voice channel.",
                color=discord.Color.yellow()
            )
            return await interaction.response.send_message(embed=embed)
        embed = discord.Embed(
            description=f"⏩ Song has been skipped!",
            color=discord.Color.blue()
        )
        await interaction.response.send_message(embed=embed)
        voice_client.stop()
        if song_queue:
            next_song = song_queue.pop(0)
            vc = bot.voice_clients[0]
            vc.play(discord.FFmpegPCMAudio(next_song[0]))
            vc.source = discord.PCMVolumeTransformer(vc.source)

    ```
#
    async def pause_callback(self, button, interaction):
        if interaction.response.is_done():
            return
        voice_client = interaction.guild.voice_client
        if not voice_client:
            embed = discord.Embed(
                description=f"🤨 I'm currently not in a voice channel.",
                color=discord.Color.yellow()
            )
            return await interaction.response.send_message(embed=embed)
        embed = discord.Embed(
            description=f"⏸ Song has been paused!",
            color=discord.Color.blue()
        )
        voice_client.pause()
        await interaction.response.send_message(embed=embed)

    @discord.ui.button(label="Resume", style=discord.ButtonStyle.success, emoji="⏩")
    async def resume_callback(self, button, interaction):
        if interaction.response.is_done():
            return
        voice_client = interaction.guild.voice_client
        if not voice_client:
            embed = discord.Embed(
                description=f"🤨 I'm currently not in a voice channel.",
                color=discord.Color.yellow()
            )
            return await interaction.response.send_message(embed=embed)
        embed = discord.Embed(
            description=f"⏭ Song has been resumed!",
            color=discord.Color.blue()
        )
        voice_client.resume()
        await interaction.response.send_message(embed=embed)
#
    async def stop_callback(self, button, interaction):
        if interaction.response.is_done():
            return
        voice_client = interaction.guild.voice_client
        if not voice_client:
            embed = discord.Embed(
                description=f"🤨 I'm currently not in a voice channel.",
                color=discord.Color.yellow()
            )
            return await interaction.response.send_message(embed=embed)
        embed = discord.Embed(
            description=f"⏹ Song has been stopped!",
            color=discord.Color.blue()
        )
        voice_client.stop()
        await interaction.response.send_message(embed=embed)```
limber urchin
#

Yeah, that's your whole class

#

Send the part of your code that causes the error

#

not all of your code

rotund depot
#

any1 can help me w that iont understand the error

young bone
obtuse juncoBOT
#

Use aiohttp.
requests and urllib are blocking. Do not use these libraries within your asynchronous code as they're not asynchronous.
(https://docs.pycord.dev/en/stable/faq.html#what-does-blocking-mean)

Py-cord uses aiohttp, so it should already be installed. An example of code using aiohttp and Py-cord:

async with aiohttp.ClientSession() as cs:
    async with cs.get('https://httpbin.org/json%27') as r:
        res = await r.json()  # returns dict
        await ctx.send(res['slideshow']['author']) 

For more help, see aiohttp's documentation: https://docs.aiohttp.org/en/stable/

obtuse kestrel
#

i get an error saying AttributeError: module 'discord' has no attribute 'Bot'

obtuse kestrel
young bone
obtuse kestrel
#

cause every tutorial on the internet says that, and im planning to add commands to it

#

they just write discord.Bot

obtuse kestrel
#

id say so

young bone
#

do you know basic python?

obtuse kestrel
#

what do you consider basic python

rotund depot
#

basic pyhton

#

the base of python

obtuse kestrel
#

yes

young bone
obtuse kestrel
#

yeah generally i know these things

#

not rly async/await but im familiar with all the other stuff

young bone
#

?tag client

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

you should understand async/await before making a bot

fervent cradle
#

How can I check if member complete onboarding?

limber urchin
#

?rtfm discord.Member.pending

#

.rtfm discord.Member.pending

winter condorBOT
limber urchin
#

pretty sure

fervent cradle
#

I mean new discord thing

rotund depot
young bone
#

and I dont know it it supports asyncio

rotund depot
#

i js never used aiohttps das why

#

and i i got the error function atribute has no attribute 'urlopen'

rotund depot
limber urchin
#

aiohttp.request.urlopen?

#

what is that?

young bone
#

lol

limber urchin
#

You can't just guess attributes and methods. Read the actual documentation and learn how to properly use the library.

young bone
limber urchin
#

That's like typing random words and hoping it makes a sentence.

rotund depot
#

yeah no iknow abt that thats my mistake lmao

#

iont why i tried that

obtuse kestrel
#

ok so i figured my error out

#

but now, when i make like a simple ping command, it doesn't work unless i @ the bot in my message

limber urchin
#

You need message content intents

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

obtuse kestrel
#

thank u!

novel yacht
#

who can help pls)? need work with sql and bot

limber urchin
#

asking who can help is a waste of time

#

this is a help channel, people help here

fervent cradle
# limber urchin Send the part of your code that causes the error
async def play(ctx, *, query):
    voice_client = ctx.voice_client
    if voice_client is not None:
        if voice_client.channel != ctx.author.voice.channel:
            return await ctx.respond("You must be in the same voice channel as the bot!")
    ydl_opts = {
        'format': 'bestaudio/best',
        'postprocessors': [{
            'key': 'FFmpegExtractAudio',
            'preferredcodec': 'mp3',
            'preferredquality': 'bestaudio',
        }],
        'download_archive': 'download_cache.txt',
    }
    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        result = ydl.extract_info(f"ytsearch1:{query}", download=False)
    url = result['entries'][0]['url']
    thumbnail_url = result['entries'][0]['thumbnail']
    voice_channel = ctx.author.voice.channel
    vc = bot.voice_clients
    if vc:
        if vc[0].is_playing() or vc[0].is_paused():
            song_queue.append((url, result['entries'][0]['title'], thumbnail_url))
            await ctx.respond(f"Added {result['entries'][0]['title']} to the queue!")
        else:
            vc[0].play(discord.FFmpegPCMAudio(url))
            vc[0].source = discord.PCMVolumeTransformer(vc[0].source)
            vc[0].source.volume = 0.07
            await ctx.respond(f"Now playing: {result['entries'][0]['title']}")
    else:
        vc = await voice_channel.connect()
        vc.play(discord.FFmpegPCMAudio(url))
        vc.source = discord.PCMVolumeTransformer(vc.source)
        vc.source.volume = 0.07
        
    embed = discord.Embed(title = f":musical_note: LunarBot - New Song Selected", description = f"", color = discord.Color.blue())
    embed.add_field(name = '', value = f"{ctx.author.mention} has selected **{result['entries'][0]['title']}** to play next!", inline = True)
    embed.set_thumbnail(url=f"{thumbnail_url}")
    embed.set_footer(text = f":headphones: Lunar Bot - Music Player")
    await ctx.respond(embed=embed, view=PlayControlsView())```
limber urchin
limber urchin
novel yacht
#

my issue
im trying when user using /userid input discord user
when bot getting id it will be try found id in db and send msg
ephemeral @user >> gamename
and when use /username will try found username and send msg username >> @user

limber urchin
#

and what is your issue?

fervent cradle
limber urchin
novel yacht
#

im dont work with sql and idk how realise

limber urchin
novel yacht
#

-_-

limber urchin
#

I have no idea what you are saying

novel yacht
#

I don't know how to implement it

limber urchin
#

Just take the user as an input and query your database for their id

#

????

novel yacht
#

but small problem id discord in one table and username in another table

limber urchin
#

then join the tables in your query

fervent cradle
limber urchin
#

The only safe way to do it is by only playing royalty-free music from a place that allows streaming publicly.

maiden copper
#

kind of an api question but im using set_thumbnail for my embed and discord is not loading it im giving a URL with extension and the url works fine idk why

limber urchin
#

How does your url look?

maiden copper
#

also, how do i use ButtonStyle.green? is it no logner supported cuz its been a while since i made adiscord bot lol

maiden lake
#

are forum tags still in development/currently broken?

silver moat
maiden lake
cyan quail
#

well hmmm

#

i guess there could be additional conversion to int since we usually do that, but it's not a major issue unless it's affecting the full event's data

zinc cloak
#

Hey so I got an invalid message and got the discord.HTTPException error. With some debugging this is because of the view. How do I debug an invalid view? What are some things that cause a view to be invalid?

#

I know for sure that the view isn't empty. Printing out the view's children doesn't result in an empty list (so the view isn't empty).

proud mason
#

mind sharing the code?

zinc cloak
#

what should I include?

proud mason
#

for starters, you could be editing/deleting/replying to a message that doesnt exist or got deleted

zinc cloak
#

Oh wait I forgot to add the error message

proud mason
zinc cloak
#
In components.0.components.0.options.5: The specified option value is already used```
#

The traceback just sends me to the:

await message.edit_original_response(embed=embed, view=view)```
proud mason
#

at least thats what i can infer

zinc cloak
#

OHHH

#

tysm! That makes sense.

#

Wait no...

#

I don't see any duplicates

#

could there be another reason?

hybrid flower
#

hi, all, if the autocomplete function must use the guild_id, how to achieve?

proud mason
proud mason
#

.rtfm autocomplete

zinc cloak
#

I looked and returned duplicates

#

It seems the same as it was before

#

I'll double check

zinc cloak
#

It doesn't work for this

#

But this works

proud mason
#

Hmm

proud mason
ornate current
#

cannot import tasks from discord.ext

#

what's wrong here???

proud mason
#

?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

proud mason
#

uninstall py-cord dpy and other discord related libraries

#

and reinstall py-cord

ornate current
#

ok

#

thx it worked

patent moth
#

can I record and play audio at the same time using pycord? when I try to do it I get error 'VoiceState' object has no attribute 'connect' (Maybe VoiceChannel object changes to a VoiceState object after record?

ornate current
#

interaction stops after bot restarts, any fixes?

#

on_interaction sometimes gives out unknown interaction

tired goblet
#

whats a good way to display a table?

#

like i have a table, which should be displayed to the user. it is fetched from an sql db, currently im fetching it as a list of lists with each element of the outer list a row in the db

limber urchin
#

There aren't really any good ways to display tables since the screen width of a user can vary a lot which means you're never guaranteed to display it well. The most failsafe way to do it would be to draw the table out on an image and send the image.

tired goblet
#

oh i see

#

trying embeds, but if it doesn't work, gonna generate image

silent meadow
#

discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access

#

what does this mean?

proud mason
strange beacon
strange beacon
strange beacon
silent meadow
ornate current
strange beacon
strange beacon
ornate current
#

Does the discord.ui.role_select makes a dropdown of all roles? (More than 25)

round rivet
#

yes

#

but you can only select a max of 25

zinc cloak
#

ahhhhhhhhhhhhhhhhh

#

I programmed my own backend for a select to get all channels

#

How do I get a select menu with all the channels?

#

I'm looking through the docs and can't seem to find it

patent moth
#

I want to get a VoiceClient object so I can use on it the method "start_recording" but I want to start recording while the bot is already inside the VC. Is there a way for me to get a VoiceClient object without doing: VoiceChannel.connect()?

proud mason
winter condorBOT
proud mason
#

.rtfm guild

proud mason
#

Yea it's there

#

.rtfm context.voice

proud mason
#

There too

zinc cloak
#

why did I...

#

ok thanks!

#

.rtfm channel_select

winter condorBOT
hybrid flower
#

hi, how to check the channel is a private text channel?

strange beacon
blissful hazel
hybrid flower
#

like this

young bone
hybrid flower
cyan quail
#

the "private channel" option only sets permissions, it's not a real property

strange beacon
cyan quail
#

^

#

or whatever role you're checking can/can't view the channel

#

you can get the @ everyone role with guild.default_role

wicked helm
#

Is it alright to ask for help with / commands permissions here? (Using the server Integration settings)

#

My bot is showing, and responding to commands in a channel I disabled it in..

cyan quail
#

you could use the "view server as role" option to see how it looks for regular users

fervent cradle
young bone
fervent cradle
#

like bro it says discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'BridgeExtContext' object has no attribute 'user'

proud mason
#

try ctx.author

young bone
#

^

leaden relic
#

are there any problems on autocomplete options in slash command groups?

when in @bot.slash_command()
all options are sowing

but when i put them in COG
group = slashcommandgroup
@group.command()
some options are not showing even the required options

i tried resync application commands in integrations and still the same and tried both the main.py commands and cogs with group command and still the same

proud mason
proud mason
#

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

leaden relic
#

ohh wait let me try something

#

adding those missing options as @real compasstion did not work

#

nvm found the problem

#

it's self

proud mason
#

ah

#

lol

leaden relic
#

hahahaha i forgot to add it when i copy pasted it 🤣

leaden relic
deft mirage
#

has anyone ever seen the case where an ephemeral response to a permanent button sometimes isn't ephemeral after the bot has been running for some time?

young bone
proud mason
#

^ 15 mins iirc

#

discord does it automatically

deft mirage
#

what i meant is.
I create a button that if pressed will respond with ephemeral=True to a member.

The button works normally for 1-2 hours and after that it stops responding with ephemeral=True and everyone can see the response

wicked helm
cyan quail
cyan quail
#

then that's something wrong with your code

deft mirage
#

but i found the problem. i was using the same custom_id

#

for 2 different buttons

cyan quail
#

rip

deft mirage
#

thanks for your help 🙂

obtuse kestrel
#

so i know this is probably a nooby question but i want to pass in more parameters through a command like this: !command @gusty pastureng parameter parameter

#

how can i acomplish this

proud mason
obtuse kestrel
#

ok, i did that but how can i make it actually get it cause my command is basically !command @ text1 text2

#

how can i make it get the text1 and text2, do i have to use ctx or something

proud mason
#

uhh

#

how did you define the cmd

obtuse kestrel
#
@bot.command()
async def gift(member: discord.Member, ctx, gift, quantity):
#

essentially you write !gift @ gift quantity

proud mason
#

ctx is always the 1 parameter. it goes before member.

proud mason
obtuse kestrel
#

i dont know how to make it seperately get gift and quantity

errant craneBOT
#

Here's the basic bot example.

proud mason
#

see that

obtuse kestrel
#

thanks ill see what i can do with this

proud mason
#

pretty useful

#

.guide

winter condorBOT
proud mason
obtuse kestrel
#

alr thx

#

it works now

proud mason
#

cool

crimson adder
#

Hello there, i'm making a classic moderation bot, and when i wanted to put help command... nothing worked, without error, without anything.

I take the code from the pycord website, and it didn't work, if someone know how to make it work.

bot = commands.Bot(command_prefix='!')


class MyNewHelp(commands.MinimalHelpCommand):
    async def send_pages(self):
        destination = self.get_destination()
        for page in self.paginator.pages:
            emby = discord.Embed(description=page)
            await destination.send(embed=emby)

bot.help_command = MyNewHelp()```
limber urchin
#

You need to explain what you mean by "nothing worked". We don't know what you expect to work.

limber urchin
#

Do you have message content intents enabled?

obtuse kestrel
#

u didnt put @bot.command() i think

crimson adder
#

I just took the tutorial from the pycord website, that's why i'm fucked up. Wiggle

obtuse kestrel
crimson adder
limber urchin
#

?tag intents

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.

obtuse kestrel
#

u could try writing it w/out a class

limber urchin
#

Why would they do it without a class?

obtuse kestrel
limber urchin
obtuse kestrel
#

Alr dude

limber urchin
crimson adder
#

Well, it work but now how it should :

If i don't put any context, it just error.

If i put a command name, it didn't found the slash command i'm searching for.

And when i'm just putting "help" it should send me all the commands like that :

limber urchin
#

what?

crimson adder
#

That's what i take from the guide.

#

That's what i get.

limber urchin
#

The error explains what's wrong. You're missing a context parameter

crimson adder
#

I should not.

limber urchin
#

?

crimson adder
#

What's erroring it's that :


bot = commands.Bot(command_prefix='!')


class MyNewHelp(commands.MinimalHelpCommand):
    async def send_pages(self):
        destination = self.get_destination()
        for page in self.paginator.pages:
            emby = discord.Embed(description=page)
            await destination.send(embed=emby)

bot.help_command = MyNewHelp()```

But when i call that, it should send me that :
limber urchin
#

I know, you already said that

crimson adder
#

Yup.

#

So, i'm asking you why ?

I know there's an error, I know what's the error, but i don't know why there's an error in the guide code and i don't know how to fix it.

novel jay
#

How do bots appear online but don't have a status circle? I have no idea how the hell that works

silver moat
novel jay
#

I'm guessing pycord doesn't offer that?

#

Since it doesn't use websockets i believe?

silver moat
novel jay
#

I didn't think it looked cool lol

silver moat
#

It means you are only limited to interactions. You cannot interact with events and things.

novel jay
#

Oh

obtuse kestrel
#

How can i pass an entire sentence as a parameter? for instance, im trying to make an embed function that needs to take in parameters that can form sentences ```py
@bot.command()
async def embed(ctx, title, description, name, content, rgbColor1: int, rgbColor2: int, rgbColor3: int):
embed = discord.Embed(color=discord.Color.from_rgb(rgbColor1, rgbColor2, rgbColor3), title=title, description=description)
embed.add_field(name=name, value=content)
await ctx.message.delete()
await ctx.send(embed=embed)

#

i need title description name and content to be able to be sentences

silver moat
obtuse kestrel
#

Ok, ill try that

#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Context' object has no attribute 'send_modal'

silver moat
#

Yeah, because it cannot

obtuse kestrel
#

hm

silver moat
#

you should send a button

#

which opens the view

obtuse kestrel
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Context' object has no attribute 'respond'

#

from the docs btw

silver moat
#

what docs

obtuse kestrel
silver moat
#

yeah that's with discord.applicationcontext, not ext.commands.context

obtuse kestrel
#

oh

silver moat
#

it would just be ctx.send

#

.rtfm ext.commands.context

obtuse kestrel
#

Thank you!

#

it works now

silver moat
obtuse kestrel
#

thx for not just etlling me to go learn python or whatever

novel jay
#

Its on_member_join for the member join event correct?

silver moat
#

yes

novel jay
#

Alr good

novel jay
#

How would i make it so a slash command can be removed and readded to a guild (its alright if it has to be a guild-only command instead of a global)
Example:
Say im a server admin and there's some command i wanna disable, instead of having to tell people "sorry this command is disabled" the command itself can disappear so people instantly know instead of having to run it only to be disappointed

My bot is only for 1 server, it doesn't have to scale to different servers

undone falcon
#

I am trying to use the same SlashCommandGroup in 2 different cogs, but it give me the errors discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body In 3: Application command names must be unique

#

I have made sure the names are different for the commands in bot of the cogs

#

Is it possible to have the same SlashCommandGroup in 2 different cogs ?

silver moat
undone falcon
undone falcon
#

I am not sure it is working anymore I just tried 2 of the 3 method listed and it did not work

silver moat
#

¯_(ツ)_/¯

undone falcon
#

do I really need to put all the commands of a same group in one file ...

silver moat
#

yes

undone falcon
#

I hope you wont have to do this in v3 !

silver moat
#

open a feature request then

undone falcon
#

On v2 or v3 ?

silver moat
#

which ever one you want it to be on

#

could be both

#

but I suggest v2 first

#

because v3 is always prone to change

undone falcon
#

I see will try v2 first ! I just found pretty bad to have a class that is 1500 lines of codes

silver moat
#

usually I would have helper functions that would make things have way less files

#

I think I'm being dumb. I mean having way less lines

undone falcon
#

yeah but I mean I cant use the same SlashcommandGroup anywhere else, so I can really put those method in a other class and file 😦

silver moat
#

you could split the commands into smaller sections

undone falcon
#

with like sub-groups ?

silver moat
#

I mean each individual command may have similar/overlapping code

undone falcon
#

oh no they dont, otherwise it would already be in a function

#

The best I could think of is have the commands calling a method in a other file to implements it elsewhere

silver moat
#

1.5k lines isn't something I would worry about

undone falcon
#

yeah it is not the end of the work, but if I add more, which I will, it will because ridiculously big

#

(1.5k is already way to big in my opinion to)

#

makes the code a lot less readable

silver moat
#

It's not that unreadable. As long as it is ordered in a reasonable way and follows PEP styling guidelines, it is ok

#

The point of cogs is group similar commands together. SCG do the same thing

undone falcon
#

It force to put some methods that dont belong with each other in the same class. For exemple, I have a "add" SlashCommandGroup. add can add multiple type of object in the bot. So I would have a class For Object1, Object2 ..., and in each of them I have add, remove, show SlashCommandGroup

silver moat
#

why not just import them?

young bone
#

I saw people with like 3k lines of code in one file

undone falcon
undone falcon
limber urchin
#

The number of lines doesn't really matter that much as long as you can navigate the code

undone falcon
#

well at 3k lines of code in a single file, it is clearly not the best way to navigate the

#

you have to scroll down so much until you find what you want

#

You have a bunch of things that dont belong together

#

This is really bad code quality

silver moat
#

Find exists and Jump to Source exists

limber urchin
#

3k lines of code can definitely be related, sometimes splitting code into multiple files can be more confusing. You can use ctrl + F and ctrl + shift + O in VS Code to navigate very easily.

#

There is also the numbered bookmarks extension which I use a lot in big files

undone falcon
#

As long as the class have a single-responsibility, it is good. Some class are also just a Facade to the main interface, which will be longer for sure

limber urchin
#

But yes, if you can split your code up into smaller modules you should.

undone falcon
#

os.path.exists

silver moat
#

I'm talking about IDE features?

undone falcon
#

ooh I misunderstood what you meant sorry rooMonkaS

inner plank
#

Hello, just found about this Pychord fork, So wondering migrating everything from discord.py to pychord is it worth it? because Pretty much everything I did so far since 3 years is on discord.py 😄. And your documentation and other things seems very beautifully designed !

young bone
#

But the stuff with import discord... is the same

inner plank
#

my query is just that is it better than discord.py to take all those efforts. I dont mind changing stuffs 🙂

tired goblet
#

hi, how can i make the embed that my bot sends non closeable?

#

there's an x mark at the top right of the embeds, is there a way so people can't cross it?

fervent cradle
#

Since when embeds are closeable?

inner plank
proud mason
#

oh wow. left

#

lmao

storm oyster
#

lmao

stark walrus
#

Just testing around this event for the first time, nothing is printing when i change my nickname

#

Is it meant to error or print None when certain attributes are not present

#

I tried printing just entry but it printed nothing

limber urchin
#

There is nothing called on_audit_log_entry in pycord

stark walrus
#

Oh then what is this

limber urchin
#

Huh.. that did not show up when I searched for it. Oh well

stark walrus
#

Hmm

#

Which version of pycord is that doc link for

limber urchin
#

Oh you're not on the stable version, I see

stark walrus
#

It says added in v2.5

limber urchin
#

Well, do you have moderation intents enabled?

stark walrus
#

I have intents.all method

limber urchin
#

Yes, 2.4 is the stable version

stark walrus
#

Oh wait

#

I need to upgrade

#

I am on 2.3.3.dev24+g5e2e28b0

#

Sorry thanks

#

How do I upgrade to v2.5?

#

I tried pip install -U pip install -U git+https://github.com/Pycord-Development/pycord but it got 2.4.1

proud mason
stark walrus
#

Hm then how to try v2.5?

#

How to make slash sub commands like this? (migrating from traditional to slash this year ;p)

errant craneBOT
#

Here's the slash cog groups example.

grizzled sentinel
#

Just note that unlike traditional. Where you could have the base command do something.
!hello
!hello welcome
You cannot do this with slash groups. You have to call the subcommand.

stark walrus
#

Oh is it similar to @bot.group

#

And then @groupname.command

#

I think traditionally that was a thing

#

I'll check the example out thanks!

proud mason
#

the master branch is the latest code

#

it can be released as either 2.4.1 or 2.5.0

#

thats just a versioning number

#

the code it still what is rn in the master branch

proud mason
#

like Bob, Plun, Doru, Lala etc

proud mason
stark walrus
#

Oh okay

grizzled sentinel
#

If you want to exclude them you could use .replace() if you want to find them you could use regex.

#

Yes

atomic wolf
#

How do I send an extra message with interactions after the message has been responded to without editing it?

proud mason
#

if this is in a slash cmd then you can just do ctx.respond again and again

atomic wolf
#

k ty

cyan quail
soft girder
#

Is it possible to make a miscalculation. That is, I write the command 15 times and it changes.

cyan quail
#

Well

#

Depends on your code...?

soft girder
#

For example: 15 times I write a command "/flower" I get "Rose" and then 16 times write "Lily'

limber urchin
#

It is literally impossible for us to help you if you don't show your code

#

"Is it possible to make a miscalculation". Of course it's possible

cyan quail
#

^ at least in this case this is very clearly something in the actual logic

limber urchin
#

It's like asking a mechanic to help fix your car, without bringing your car

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

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

I need to make so that the role was issued 16 times.

limber urchin
#

First of all, don't use f-strings for your SQL queries

soft girder
#

ok

limber urchin
#

?tag sqli

obtuse juncoBOT
#

SQL Injection is a technique used by attackers to interfere with and alter queries that an application makes to its database via input data. A vulnerability to this exploit can lead to attackers being able to read sensitive data, modify existing data (Insert/Update/Delete), perform administrative operations on your database and in some cases even issue commands directly to the operating system of the server.

More information on SQL Injection
https://www.w3schools.com/sql/sql_injection.asp
https://owasp.org/www-community/attacks/SQL_Injection

To avoid SQL Injection vulnerability, you should never directly merge or concatenate data into an SQL query through string operations (f-strings, + operator, string interpolation with %, etc.). Always use the parameterized queries included with the library you are using.

Examples of parameterized queries for popular libraries
psycopg2: https://www.psycopg.org/docs/usage.html#passing-parameters-to-sql-queries
asyncpg: https://magicstack.github.io/asyncpg/current/usage.html
sqlite3: https://docs.python.org/3/library/sqlite3.html#how-to-use-placeholders-to-bind-values-in-sql-queries
mysql: https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html

limber urchin
#

What are you trying to do? Your explanation says nothing

cyan quail
#

I guess the size of their fetchmany result is inconsistent for some reason

soft girder
#

Look.

#

I need to make sure that I write this command 16 times.

#

And at 17 times this command should stop issuing roll

cyan quail
#

Oh so you're gonna run it on discord 16 times

limber urchin
#

You never insert anything to your database? So it's always going to be empty

soft girder
#

Неее.

#

1 сек

#

Sec.

#

Example. Mijorney Bot

#

This bot allows you to use the same command 25 times ,but at 26 times he writes "buy a subscription"

limber urchin
#

Yes, we know what you are trying to do. You already said that.

#

English

soft girder
#

this is the problem. How to track the amount of command usage?

limber urchin
#

You store the usages in a database table and count them

soft girder
#

Hmmm.

atomic wolf
limber urchin
#

.rtfm channel.send

fervent cradle
#

My bot reacts every 100 messages in general chat with a emoji, but everytime it tries to react, it says error 429, too many requests?

limber urchin
#

You're being rate limited

#

Show your code

fervent cradle
#
count  = 0
@bot.event
async def on_message(message):
  global count
  count += 1
  if count % 100 == 0:
    await message.add_reaction(":nerd:")
#

but i dont understand why im being rate limited

#

when im not spamming hundreds of messages or something like that

limber urchin
#

You don't need to specify global count. count is accessible from your event anyways. And keep in mind that 0 % 100 == 0 is true.

fervent cradle
#

alr

#

but why is it being ratelimited

#

and how can i stop the error from occuring and getting it to actually react

limber urchin
#

Somehow you're doing something too quickly. Add a print inside your if statement to see if it's running multiple times for some reason

proud mason
#

ctx.send is a shortcut for it

#

(sry for pong spaxter)

atomic wolf
#

Already saw it, ty anyways

proud mason
shy crow
#

Hi. How can make that the interaction wait until a task is completed? for example:
message is send ephermeral
something is done that takes 10 sec. and then it edit the message...
it timeouts if i select to many users in the selectors

limber urchin
#

.rtfm defer

proud mason
# fervent cradle Just 1

Oh. And can you confirm you have the latest py-cord version, and no other libraries that conflict with the "discord" namespace. Like dpy

fervent cradle
#

Yep

shy crow
proud mason
#

ctx.respond should handle that internally

limber urchin
fervent cradle
#

This is the first time in the code

proud mason
#

A very useful way to debug i have found these days is, can you reproduce it with a basic bot, that has only this feature? I also would use a different bot's token

shy crow
proud mason
#

.rtfm followup

shy crow
#

ah nevermind

#

i have a typo

#

sorry

#

ah i need this selector to be waitable

#

I need that the selector gets removed

#

so that message need to be edited. But with too many users selected, the bot takes some time to process and the menu times out

proud mason
proud mason
shy crow
proud mason
#

Alr that's fine

shy crow
#

would save some time if possible

#

(and requests)

limber urchin
#

You can collect the set_permissions calls into a list of coroutines and use asyncio.gather to run them concurrently.

shy crow
limber urchin
#
coroutines_to_run = []
for x in y:
    coroutines_to_run.append(my_async_method())
await asyncio.gather(coroutines_to_run)

Something like that

shy crow
#

Thanks!

limber urchin
shy crow
limber urchin
#

Uhh.. try await asyncio.gather(*coros_to_run)

shy crow
#

ah it was an await to much

#

Works now!

maiden lake
#

I keep getting a no module discord found when running my bot, uninstalling and reinstalling pycord seems to fix this issue, anyone know what might be happening here?

edit: think I just solved it nevermind

gleaming falcon
#

WARNING:discord.gateway:Can't keep up, shard ID None websocket is 41.3s behind.
That's a new one to me. Anyone familiar with this error and what it might signify?

novel jay
#
AttributeError: 'Interaction' object has no attribute 'author'
```This is in a button view, Is it button.author or something?
#

Nvm its interaction.user thats weird

raw reef
#

Bit confused atm. Are slash commands encouraged to use for most things or are prefix? I've read that prefix commands are being phased out, yet most docs and tutorials I come across use them?

proud mason
#

(Heartbeating is an auto process that is done so discord knows your bot is connected)

#

It happens once every few seconds

#

And is a background process

gleaming falcon
#

Familiar with heartbeats 🙂 I just dono't get what that's about. Is it a transport issue (e.g. sessions) or a network problem?

proud mason
proud mason
#

If you have a long time consuming blocking functions, use asyncio.to_thread to run it

proud mason
#

But not all bots are large and need verification

#

And prefix cmds can give slightly more advanced features (sometimes)

tranquil sandal
#

how do we get the total shard count

errant craneBOT
#
Toolkit

A bot built to help you manage your Discord server as easily as possible.
Use the menu below to view commands.

Server Count

97

User Count

5348

Ping

110.95ms

round rivet
#

.rtfm bot.shard

round rivet
#

@tranquil sandal length of this

proud mason
#

You also have shardinfo

#

.rtfm shardinfo

proud mason
#

Last one

uneven beacon
#

hello
so i have this simple "mute" command

    @commands.slash_command(name="mute", description="Mutes a user")
    async def mute_command(self, ctx, user: discord.Member):
        # Check if the user invoking the command has the necessary permissions
        if not ctx.author.guild_permissions.manage_roles:
            await ctx.send("You do not have permission to mute users.")
            return
        mute_role = discord.utils.get(ctx.guild.roles, name="Muted")
        if not mute_role:
            mute_role = await ctx.guild.create_role(name="Muted", reason="Used for muting users")
            for channel in ctx.guild.channels:
                await channel.set_permissions(mute_role, send_messages=False)
        await user.add_roles(mute_role, reason="Muted by {}".format(ctx.author.name))
        await ctx.send("{} has been muted.".format(user.name))

the command works and mutes a person but discord gives me the "this application did not respond" error every time i use it
how can i fix this?

young bone
uneven beacon
sweet coyote
#

I'm new to async. Why is the bot not listening for any other commands while the first is running.
The first takes a while as it has to pull/update data.
I believe all the functions in the update sequence are awaited.

limber urchin
#

That is impossible to say if you don't show your code

sweet coyote
#

its thousands of lines

limber urchin
#

thousands of lines for one command to fetch data???

sweet coyote
#

well the command isnt but its broken up into several smaller functions across multiple files. It has to establish and pull data from a game api. I might make a post and try and get all the relevant functions

limber urchin
#

And how are you fetching the data from the api?

sweet coyote
#

concurrent futures threadpoolexecutor

limber urchin
#

can you please just show the code to fetch the data from the API?

sweet coyote
#

It was using an open source library from git. Do i have to modify it to await those functions aswell?

limber urchin
#

The library is probably using a blocking method to make the HTTP requests then.

tranquil sandal
sweet coyote
limber urchin
#

Why are you using a library anyways? Just make the requests yourself, that's just overcomplicating something very simple

sweet coyote
#

because it was easier getting started 🤷‍♂️
I almost redid it at the start then was like i will see how far i can get with the generic code provided by the api. I guess i found its limit.

#

anyway. got some fun hours ahead. Thanks for the help

soft girder
#

sorry

#

How in button class import guild id

#
class TlB(discord.ui.View):

    guild = guild.extension

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

    a = ""
    i = 0
    for el in item2:
        i+=1
        if i<4:
            a += f"**{i}**.:coin: __{el[1]}__ | {el[2]} | <@{el[3]}>\n"
    for el in item:
        i+=1
        if 4<i<17:
            a += f"**{i}**. __{el[1]}__ | {el[2]} | <@{el[3]}>\n"    
        if i>16:
            a += f"Reserve🔴**{i}**. __{el[1]}__  | {el[2]}  | <@{el[3]}>\n"
    embed1 = discord.Embed(title =f":scroll: TEAM LIST :scroll:",description=f"**🕐Time: {time}**\n  \n{a}", colour = discord.Colour.embed_background())

    @discord.ui.button( label="Success",emoji="✅",style=discord.ButtonStyle.success)
    async def button_callback(self, button, interaction):
        for child in self.children:
            child.disabled = False
        button.label = 'Уже нажато'
        await interaction.response.edit_message(view=self)
        await tlist.edit(embed=embed1)

limber urchin
soft girder
limber urchin
#

I already told you that as well

#

?tag sqli

obtuse juncoBOT
#

SQL Injection is a technique used by attackers to interfere with and alter queries that an application makes to its database via input data. A vulnerability to this exploit can lead to attackers being able to read sensitive data, modify existing data (Insert/Update/Delete), perform administrative operations on your database and in some cases even issue commands directly to the operating system of the server.

More information on SQL Injection
https://www.w3schools.com/sql/sql_injection.asp
https://owasp.org/www-community/attacks/SQL_Injection

To avoid SQL Injection vulnerability, you should never directly merge or concatenate data into an SQL query through string operations (f-strings, + operator, string interpolation with %, etc.). Always use the parameterized queries included with the library you are using.

Examples of parameterized queries for popular libraries
psycopg2: https://www.psycopg.org/docs/usage.html#passing-parameters-to-sql-queries
asyncpg: https://magicstack.github.io/asyncpg/current/usage.html
sqlite3: https://docs.python.org/3/library/sqlite3.html#how-to-use-placeholders-to-bind-values-in-sql-queries
mysql: https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html

soft girder
#

now i need another problem

limber urchin
#

?

soft girder
#

I need take guild id without command

limber urchin
#

I don't even know what you are doing. Why are you running all that code in the class? Why are you using fetchmany? Why do you have a persistent cursor object?

soft girder
limber urchin
#

what is guild.extension?

limber urchin
soft girder
#

i don`t remeber how it named

#

uhhhh

limber urchin
#

Your code is unreadable, I can't help you

soft girder
limber urchin
soft girder
#

how take guild id without command

limber urchin
#

what does that even mean?

#

what do you mean "without command"?

soft girder
#

ok watch

#

In commands, I get the guild id using ctx But I need to get an id guild outside of command.

limber urchin
#

How are you going to have a guild outside of a command??

soft girder
#

uhhhh

#

They already wrote me a way. But I forgot it.

limber urchin
#

What?

#

Who is "they"?

soft girder
#

Person from this server

limber urchin
#

Then look for that message?

#

Why are we wasting time on a question that has already been answered??

soft girder
#

I don't see this message in history

limber urchin
#

Bro.. use the search feature

#

How hard can it be

leaden relic
#

anyone here has or know a pycord bot with pymongo database? i am doing one and felt like it's messy and want to see an example to see what a clean one would look like

proud mason
leaden relic
#

but i still want an example if you know any

soft girder
#

Whets wrong?

leaden relic
soft girder
#

when "int.... " wrong too

#

uhhh

#

ok

limber urchin
#

Do you know basic OOP? You're just guessing at this point

leaden relic
#

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

#

something like this

proud mason
proud mason
limber urchin
proud mason
#

hmm

leaden relic
limber urchin
limber urchin
leaden relic
limber urchin
leaden relic
leaden relic
limber urchin
#

Yes, of course

young bone
leaden relic
#

do you usually insert every INSERT or insert_once() at every interaction that needs it like the raw code?

#

or using a class?

limber urchin
#

what

leaden relic
leaden relic
# limber urchin what

i mean example db.collection.insert_once({"userId": userId})

or

class User:
    def __init__(self, userId):
        db.collection.insert_once({"userId": userId})
    
User(userId=3216549876132)
proud mason
#

1st one looks right. 2nd one seems redundant. there isnt a need for classes to do that.

limber urchin
proud mason
#

ohh hm

limber urchin
#

I guess it's like writing your own ORM in a way

proud mason
#

just use an ODM (ORM for mongo) at this point ngl. Beanie might be a good choice

limber urchin
#

But there's nothing wrong with using straight up queries in your code without a class, it's just personal preference

leaden relic
leaden relic
#

thanks i'll continue what i was doing then and migrate from pymongo to motor

limber urchin
#

The only downside I can see to using raw queries in your code is that you might have a bunch of duplicate queries everywhere as opposed to just having a class. So if your table structures change or something like that you only need to change one place.

leaden relic
leaden relic
leaden relic
proud mason
leaden relic
#

anyway thanks again to both of you

coarse spire
#

I just reached 100 commands on my bot, and noticed that I can't add anymore. Is there any way to bypass this command limit for slash commands?

atomic wolf
#

How do I set the maximal characters of a modal?

fervent cradle
#

how to send modal in dropdown interaction

#

await interaction.response.send_modal(modal)

#

dont work

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.

fervent cradle
#

error discord.errors.InteractionResponded: This interaction has already been responded to before

silver moat
#

You can only respond once to an interaction. Sending a modal is considered as a response.

cyan talon
#

so im trying to create a bot command with buttons on it on python 3.10 but everytime i try to import discord_components package it's giving me an error that the module doesn't exist and some people told me to downgrade to python 3.9 because it doesn't work on py 3.10 or py below 3.9 only works on 3.9 is that true? (for anyone who have drop-down menus / buttons commands)

proud mason
#

Pycord already has built in components

cyan talon
# proud mason Why are you using discord_components

This is where im getting an error, dont i need to have this imported?:

from discord_slash.utils import manage_components
from discord_slash.model import SlashMessage
from discord_slash.utils.manage_components import create_select_option, create_select_menu, create_actionrow
from discord_slash import SlashCommand, SlashContext, create_option

#

import buttons

proud mason
#

.guide

winter condorBOT
proud mason
#

See that on how to use it

#

Make sure to uninstall all discord libraries and reinstall pycord

#

?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

cyan talon
#

I'm currently using replit for my code, do i install these packages:

#

oh nvm

#

i got it

#

ty

silver moat
#

.replit

#

?tag replit

obtuse juncoBOT
fervent cradle
#

Im getting this error:

Discords.error.httpexception: 429 too many requests (error code: 20028) the write action you are performing on the channel has hit the write rate limit

My code sends a emoji every 100 messages, after like 2 emojis it says this. Why

silver moat
#

What host are you using?

errant craneBOT
#

Here's the persistent example.

soft girder
#

I'm sorry. How to make the buttons have a long expiration date.I need to be able to press buttons for 12 hours

fervent cradle
cyan talon
silver moat
fervent cradle
#

Im using a raspberry pi to host my discord bot

fervent cradle
#

Just running a terminal

#

is await message.add_reaction(":joy:")

#

the correct way? do i need await is that causing the issue

soft girder
cyan talon
# silver moat Yup.

I've done the steps in that website u sent me, now do I add import py-cord or something at the top of my code and delete all other discord related codes?

proud mason
#

Check the guide if you haven't used pycord before

proud mason
proud mason
#

Can you do a fresh install of pycord?

#

Uninstall and reinstall the latest version

#

Also, which python version is installed?

fervent cradle
#

honestly idk all of those let me check

#

Python is 3.9.2

soft girder
#

How to make a similar dropdown list.

fervent cradle
#

Is this latest

errant craneBOT
#

Here's the dropdown example.

#

Here's the slash options example.

silver moat
#

depending on your definition of dropdown

grizzled sentinel