#Basic Pycord Help (Quick Questions Only)

1 messages ยท Page 59 of 1

midnight torrent
#

you are missing str before (interaction.user)

loud sail
#

@proud mason
that doesn't work either.

proud mason
#

so try (interaction.user.name + interaction.user.discriminator).lower()...

midnight torrent
#

hashtags cant be used in channel names i do believe

proud mason
#

you can check if a response has been sent before (defer is a valid response)

proud mason
#

.rtfm interactionresponse.is_done

winter condorBOT
proud mason
#

that would return bool based on if a response was sent earlier

midnight torrent
#

i see i see, i normally defer all my commands due to them using FFMPeg and longer processes, in my error handler i also have a defer for if a check fails

#

and it was causing some issues

#

i made a check like this for the actual error response

loud sail
loud sail
midnight torrent
#

error is intended

proud mason
loud sail
proud mason
midnight torrent
loud sail
proud mason
midnight torrent
#

yeah

proud mason
#

yea why not

midnight torrent
#

so i can iterate through them

#

would i just do smth like list[discord.Attachment] ?

proud mason
#

oh no you cant get a list of them

midnight torrent
#

fuuuck

proud mason
#

each option can only be 1 attachment

midnight torrent
#

damn

#

oh well

proud mason
#

yeah ๐Ÿคทโ€โ™‚๏ธ

midnight torrent
#

tbf, everthing is handled in memory so it wouldnt be so good to have a multi file option

proud mason
#

you could make the user send the attachments in a separate message and use bot.wait_for

midnight torrent
#

piping was enough work ill just leave it lol

#

actually, pycord supports reading audio from voice channels correct?

errant craneBOT
#

Here's the audio recording example.

midnight torrent
#

:3, time to implement audio recognition via voice lol

midnight torrent
#

.rtfm start_recording

winter condorBOT
midnight torrent
#

.rtfm get_user_audio

proud mason
midnight torrent
#

oop sorry

stark nebula
#

How would you do a AutocompleteContext for all the users in a server?

proud mason
feral lintel
#

How do you respond to avoid the respond failure error ?

limber urchin
#

.rtfm respond

fervent cradle
#

Question

I am trying to align my buttons im using a class with 2 buttons in, but they are displaying ontop of each other, Is there anyway i can align them to be on the same row side by side without using [button1][button2] in 1 line of code? this is my code :

'''
class MyView(discord.ui.View):
    @discord.ui.button(label="Right", row=0, style=discord.ButtonStyle.green, emoji='โค๏ธ')
    async def first_button_callback(self, button, interaction):
        await interaction.response.send_message("User was notifed")

    @discord.ui.button(label="Left", row=3, style=discord.ButtonStyle.red, emoji="โŒ")
    async def seccond_button_callback(self, button, interaction):
        await interaction.response.send_message("Keep Swiping")

@bot.slash_command()
async def button(ctx):
    await ctx.respond("Left Or Right?", view=MyView())
'''
limber urchin
#

Why are you setting row=0 and row=3?

fervent cradle
#

I was just testing it, its meant to be row=0 and row=1

#

the issue still happens with that set

limber urchin
#

But why? If you want them to appear on the same row why would you set them on different rows?

fervent cradle
#

omg

#

Im such a dumbass

#

Oh god i feel dumb, thank you very much for the help ๐Ÿ˜ญ

#

I dont know how i have my degree

verbal gulch
#

Hellooo, i have a problem. I tried to handle errors globally, however, it does not even check. (I still get the errors in the console).```py
@bot.event
async def on_application_command_error(context: discord.ApplicationContext , exception):
print('a')
embed = discord.Embed(color=colors['fail'])
embed.set_author(name='Command failed. the Tech development responsible has been notified.')
await context.respond(embed=embed)
embed2 = discord.Embed(color=colors['blurple'], description='Error caught! More information below.', fields=[discord.EmbedField(name='Error', value=str(exception)), discord.EmbedField(name='User', value=context.user.mention), discord.EmbedField(name='Command', value=context.command.n)])
await bot.get_channel(1077607429929455757).send(embed=embed2)

@bot.command()
async def raisee(ctx):
ctx.respond('this is gonna be a error as it's not awaited.')

#

Bot is not subclassed

limber urchin
#

Try @bot.event()

verbal gulch
verbal gulch
#

coro*

limber urchin
#

I'm assuming you are actually using application commands and not prefixed commands?

fervent cradle
limber urchin
#

And you do not have any error handlers specifically set on your commands?

verbal gulch
#

No, i don't

limber urchin
#

I honestly don't know, that should work

verbal gulch
#

If anyone knows how to solve it, please ping me.

proud mason
#

maybe raise a fake error yourself

verbal gulch
#

Like what?

proud mason
#

hmm

#

one sec

verbal gulch
#

Maybe a missing permissions could work

proud mason
#

yea try that

plush moat
#

I know discord views don't persist accross bot restarts, but can I post a single view in a channel where people can click the buttons until the next restart? I tried but after a while it stopped responding, idk if that's a setting I need to change or w/e

proud mason
plush moat
# plush moat I know discord views don't persist accross bot restarts, but can I post a single...
async def calchelper(interaction, text, newview=None):
    embed=discord.Embed(title="Price calculator")
    if isinstance(text, str):
        embed.add_field(name="", value=text)
    elif isinstance(text, list):
        for field in text:
            embed.add_field(name="", value=field, inline=False)
    if newview is not None:
        await interaction.response.send_message(embed=embed, ephemeral=True, view=newview)
    else:
        await interaction.response.send_message(embed=embed, ephemeral=True)

This is the methods I call to create my view

proud mason
errant craneBOT
#

Here's the persistent example.

plush moat
#

ahhh the timeout=none, makes sense

verbal gulch
proud mason
#

you realise its value when you go into advanced asyncio

dusky sorrel
#

that doesn't have anything on what im asking

that says how to edit the help command

im asking how to make categories in the help command

like this

frank thistle
#

When setting a URL in a button it says I cant set both custom_id and url

#

Even though i have not set custom_id

#

400 Bad Request (error code: 50035): Invalid Form Body
In components.0.components.0.custom_id: A custom id and url cannot both be specified
In components.0.components.0.url: A custom id and url cannot both be specified

dusky sorrel
#

"A custom id and url cannot both be specified"

frank thistle
#

Thats literally it

#

Im not setting a customid

dusky sorrel
#

wait yeah i see that wtf

young bone
#

you set the url at the view class and not the button

frank thistle
#

Tried setting it to None and it still gives the same error

dusky sorrel
#

ah

frank thistle
#

๐Ÿค”

young bone
#

button(label="", url="")

frank thistle
#

I want to set it outside of the class since I cant pass the 'tornid' to the class can I?

#

Its not a fixed url

#

You can change all the other attributes outside the button class, why not the url

#

How do you add a url to a button thonking

errant craneBOT
#

Here's the link example.

proud mason
#

cant use the decorator

#

cuz there isnt any callback

frank thistle
#

I just tried that

#

TypeError: button() got an unexpected keyword argument 'url'

#

Got that

#

Oh

#

Lowerclass button, monkey brain moment

proud mason
frank thistle
#

Okay got a button added

finite flame
#
Table with a row of words

A = 0
while(Table 1 has more rows){
      Read the first row X in Table 1
      i = 1, B = True
      while(i <= X.LetterCount){
            if(ith letter of X.Word is a vowel){
               B = False
            }
            i = i + 1
      }
      if(B){
         A = A + 1
      }
      Move X to Table 2
}

Number of words with at most one vowel

Number of words with exactly one vowel

Number of words without any vowels

Number of words with at least one vowel
?

frank thistle
#

Im guessing you cant have a button with a url do both something and link them somewhere

#

Like say update the message the button was on

proud mason
#

Unlike normal ones

frank thistle
#

Alright, its a sacrifice then

true panther
#

How do I add logic to parent command? Example:

@commands.group(name="cmd")
async def cmd(self, ctx: Context, user: Member):
  # logic for invocation with user

@cmd.command(name="addrole")
async def addrole(self, ctx: Context, role: Role):
  # logic for subcommand

The problem I am having is that if I use <prefix>cmd addrole @some-role it executes the cmd function passing addrole to it in place of the user arguemnt instead of going through the subcommand. I tried

@commands.group(name="cmd")
async def cmd(self, ctx: Context, user: Member):
  if not ctx.invoked_subcommand is None:
    return

but that doesn't work :(

frank thistle
#

Cant have best of both worlds

proud mason
dusky sorrel
#

๐Ÿ’€

#

how is this similar to skull

proud mason
true panther
blazing tide
#

rtfm colour.embed

#

.rtfm colour.embed

winter condorBOT
crisp swift
#

Hi im pretty much a noob, someone coud help me to make my bot be able use prefix comands

obtuse juncoBOT
#

dynoError No tag clients found.

#

dynoError No tag instances found.

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)
crisp swift
#

Thanks men !!

midnight torrent
#

How can you access the bot instance while inside a View class for UI?

astral mist
#

thought footers can have icon

#
embed.set_footer(text=f"by {ctx.author.avatar.url} {ctx.user.name}")


```\
#

also how do i do this

midnight torrent
serene spindle
winter condorBOT
midnight torrent
astral mist
#

how do u use Bridge commands as prefix

#

@bot.bridge_command()
async def news(ctx, arg):
    embed = discord.Embed(
    title=(arg),
        
    color=discord.Colour.blurple(), # Pycord provides a class with default colors you can choose from
    )

    embed.set_footer(text=f"by {ctx.user.name}", icon_url=ctx.author.avatar.url) # footers can have icons too

    await ctx.respond(embed=embed) # Send the embed with some text

livid wolf
#

Thats the entire embed

#

60560 comment here

astral mist
#

3 comments

#

but y wont it work

livid wolf
# astral mist 3 comments

Maybe try

@bot.bridge_command()
async def news(ctx, arg):
    embed = discord.Embed(
    title=(arg),
        
    color=discord.Color.red(), # Pycord provides a class with default colors you can choose from
    )
    user = ctx.user.name
    embed.set_footer(text=f"by {user}", icon_url=ctx.author.avatar.url) # footers can have icons too

    await ctx.respond(embed=embed) # Send the embed with some text

Don't know if that will work

#

Wait

#

misread

young bone
livid wolf
#

@astral mist Misread. No idea what a "bridge command" is

livid wolf
#

ok

young bone
astral mist
young bone
astral mist
#

bot = bridge.Bot(command_prefix="!", intents=intents)

young bone
#

which intents?

livid wolf
#

here we go

astral mist
#

intents = discord.Intents()
intents.message_content = True

#

the ones it says in docs

young bone
#

do you have both message intents?

livid wolf
#

Yes?

young bone
#

intents.message_content = True
and
intents.messages = True

#

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

astral mist
#

i used the ones it said

astral mist
young bone
#

yes

unborn wedge
#

Hi, I'm a bit confused on the difference between UserCommand, ApplicationCommand and SlashCommand?

#

How exactly do they differ and when should I use which one?

cyan quail
#

there's also MessageCommand, which is the same as UserCommand but for right clicking messages

unborn wedge
#

Thanks, that makes it a lot clearer!

fervent cradle
#
Traceback (most recent call last):
File "main.py", line 2992, in <module>
bot.run(TOKEN)
File "/opt/venv/lib/python3.8/site-packages/discord/client.py", line 717, in run
return future.result()
File "/opt/venv/lib/python3.8/site-packages/discord/client.py", line 696, in runner
await self.start(*args, **kwargs)
File "/opt/venv/lib/python3.8/site-packages/discord/client.py", line 660, in start
await self.connect(reconnect=reconnect)
File "/opt/venv/lib/python3.8/site-packages/discord/client.py", line 554, in connect
await self.ws.poll_event()
File "/opt/venv/lib/python3.8/site-packages/discord/gateway.py", line 604, in poll_event
await self.received_message(msg.data)
File "/opt/venv/lib/python3.8/site-packages/discord/gateway.py", line 554, in received_message
func(data)
File "/opt/venv/lib/python3.8/site-packages/discord/state.py", line 1354, in parse_guild_audit_log_entry_create
payload = RawAuditLogEntryEvent(data)
File "/opt/venv/lib/python3.8/site-packages/discord/raw_models.py", line 650, in __init__
self.target_id = int(data["target_id"])
TypeError: int() argument must be a string, a bytes-like object or a number, not 'NoneType'

got this error 3 times today, it just happens randomly while the bot is on and i have to re-run the code to restart the bot

grizzled sentinel
#

Try updating pycord

fervent cradle
#

aight

fervent cradle
#

no luck, i just got it again
im using the 2.4.1.dev9+g8a911374 version

#

i added reconnect=True so now it reconnected instead of crashing
the error still appeared /shrug

grizzled sentinel
cyan quail
#

ah

fervent cradle
#

ok ok

cyan quail
#

time to pr another fix...

grizzled sentinel
#

That means you are taking longer than 3 seconds to respond to the interaction.

#

you will need to defer

#

.rtfm InteractionResponse.defer

winter condorBOT
young bone
cyan quail
#

interaction.channel.send should be interaction.response.send_message

#

but if you defer, it should be interaction.followup.send

grizzled sentinel
#

The first line in your callback should be defer if you defer. You need to tell discord asap that you are defering.

cyan quail
#

(why don't we have interaction.respond??)

grizzled sentinel
cyan quail
#

no ignore me

#

it's because you're doing if/else

#

you have to respond once

#

yeah pretty much

fervent cradle
#

Hey im probably just being hella dumb and its probably my ass python knowledge. But how can I ctx.send this function outcome? here is my function:

def profile_Embed(message_About, message_Age):
    embed=discord.Embed(title="Here is LeeT's profile", color=0xbc7ba5)
    embed.set_author(name="Bailey", url="https://", icon_url="https://i.")
    embed.set_thumbnail(url="https://i.imgur")
    embed.set_image(url="https://medi-ng.jpg?s=612x612&w=0&k=20&c=1Ws_LSzWjYvegGxHYQkkgVytdpDcnmK0upJyGOzEPcg=")
    embed.add_field(name="About Me?", value=message_About.content, inline=True)
    embed.add_field(name="Age?", value=message_Age.content, inline=False)
    embed.add_field(name="Where From?", value="Lorem ipsum dolor sit amet", inline=True)
    embed.set_footer(text="Bi v0.01 - LeeT#4281")

    #i want this to straight send it once the function is ran within the async
    return (ctx.send(embed=embed))

profile_Embed(message_About, message_Age)

silver moat
#

await it

fervent cradle
#

Throws an error the await needs to be in a async

#

ive already tried that

silver moat
fervent cradle
#

The function is placed outside of the async, but im calling the function within the async

#

But if i place my function within the async, theres no point in having a function/subroutine

silver moat
#

I mean to await profile_Embed

#

Also, the Python convention is to use snake_case for function, variable, parameter, etc. names.

fervent cradle
#

discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: NameError: name 'ctx' is not defined

young bone
#

...

#

return embed

fervent cradle
#

well not error

fervent cradle
young bone
#

embed=profile_Embed()

#

basic python

fervent cradle
#

Yeah i did that

silver moat
silver moat
fervent cradle
#

Im still stuck with camelCase idk why i always naturally go towards that, and ill try passing the ctx in now

#

i mix snakecase and camel

silver moat
#

giraffe

fervent cradle
#

is that whats its called?

silver moat
#

that's what I call it

#

I don't think any language uses it tho

fervent cradle
#

Haha yeah i mean all my code is self taught since my college is still stuck on shitty pandas and matplotlib

silver moat
#

:/

silver ice
#

No?????

#

๐Ÿ˜ฎ

fervent cradle
# silver moat :/

anyways thank you very much with your help, sorry if im brain dead, we all start somewhere ๐Ÿ˜ญ

limber urchin
#

Pretty much all coding is self taught, school only gets you started. If you actually want to learn programming you need to do it yourself.

full basin
#

Why are you deffering before sending the response

#

You defer at the start of your callback

#

It's just pointless

sterile hinge
#

How to make an optional option in slash-command?

errant craneBOT
#

Here's the slash options example.

sterile hinge
#

Oh, thx

proud mason
#

do you have multiple instances of the bot running?

ornate current
#

how can i get the user that boosted the server? i am using message to check if its a premium subscription type

sand beacon
#

how do I make a slash command that only the bot owner can run?

crisp swift
#

somone knows how to make prefixed commands

#

or help me fix my brocken code

proud mason
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
#

.rtfm is_owner

crisp swift
proud mason
#

.guide

winter condorBOT
icy tulip
#

how would you attach a custom value/variable to a command? like the "usage" or "description" parameter for commands

proud mason
#

.rtfm commands.command

proud mason
#

check the Command class to see what all it accepts

proud mason
#

that stuff is used by the help command

icy tulip
#

yeah I'm wondering If there's something you can do to add your own, not literally but some alternative or equivalent. or maybe that's a general python question

proud mason
#

it shouldnt have slots defined, so you can add new attributes

icy tulip
cold hamlet
#

For some reason, bot.close() is taking a seemingly infinite amount of time to do anything (the bot does close the WS connection, but the function never returns)
How would I go about debugging this? My version is 2.4.0 on 3.11.0

#
2023-02-23 10:17:49,284:DEBUG:discord.gateway: Received WSMessage(type=<WSMsgType.CLOSING: 256>, data=None, extra=None)
2023-02-23 10:17:49,284:INFO:discord.gateway: Websocket closed with 1000, cannot reconnect.
2023-02-23 10:17:49,285:DEBUG:discord.client: Dispatching event disconnect
2023-02-23 10:17:49,286:INFO:discord.client: Cleaning up tasks.
2023-02-23 10:17:49,286:INFO:discord.client: Cleaning up after 6 tasks.

This is the end of the debug log

crisp swift
#

?tag

obtuse juncoBOT
#
**Command:** ?tag

Description: Get or create a tag
Cooldown: 5 seconds
Usage:
?tag [tag name]
Example:
?tag how2invite

crisp swift
#

?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)
proud mason
crisp swift
#

srry

crisp swift
#

ive spend like 1,5 h trying to figure out whats rong here and i cannot see it if someone coud explain why it woud be nice thx ๐Ÿ™‚

#

i know that i have already asked about this but i cannot find anything in the docs

proud mason
#

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

crisp swift
#

aok srry

#

the thing is that prefix commands dont work

#

i dont know exactly why

#

also this error pops up

proud mason
#

use commands.Bot (B caps)

fossil mulch
#

Hii, somehow i broke my send embed function and i dont even know what happened because i didnt touched it

        notification_channel = self.bot.get_channel(
           int(self.bot.config["notification_channel"])
        )
...

                await notification_channel.send(embed=embed)

This is the Part i think is most relevant, because error tells me there is no .send method for NoneType - but why is my notification_channel NoneType. This exact snippet is currently working on my main bot instance

File "/Users/***/PycharmProjects/Mako/mako/cogs/twitch_notifier.py", line 78, in send_notification_when_live
await notification_channel.send(embed=embed)
AttributeError: 'NoneType' object has no attribute 'send'

crisp swift
#

Traceback (most recent call last):
File "c:\Users\Hoshi\Desktop\PROJECTOS\VSCODE\Python\projects\HoshiBot\main.py", line 13, in <module>
bot = discord.bot(command_prefix="!", intents=intents)
TypeError: 'module' object is not callable

proud mason
#

use partial objects

#

.partial

winter condorBOT
#

Partial Objects

These can be used to make API calls when you have channel id and/or message id, and you don't want to rely on the cache to have their objects.

Methods which can be used on them are -

Example Usage:

async def star_message(channel_id: int, message_id: int):

    # Get Partial Messageable object. Docs-
    # https://docs.pycord.dev/en/stable/ext/commands/api.html#discord.ext.commands.Bot.get_partial_messageable
    partial_channel = bot.get_partial_messageable(channel_id)

    # Get Partial Message. Docs-
    # https://docs.pycord.dev/en/stable/api/models.html#discord.PartialMessageable.get_partial_message
    partial_message = partial_channel.get_partial_message(message_id)

    # Add a reaction
    await partial_message.add_reaction(":star:")
proud mason
fossil mulch
#

Ok, thanks - will have a look at it

#

Any thoughts on why this worked before and suddenly stopped working?

cold hamlet
proud mason
cold hamlet
#

I subclass, but I don't overwrite any functions other than on_ready

proud mason
fossil mulch
#

double checked the id is correct and bot is part of the guild so it's probably the cache part - thanks m8 =)

proud mason
fossil mulch
cold hamlet
#

I've checked and its the self.http.close() call within bot.close() that's hanging

proud mason
cold hamlet
#

I'll try later. I know its the same issue on another device because it happens on both my dev env and my VPS

crisp swift
#

Thanks The om Nom Nom you have helped me so much i rrly apreciate

proud mason
#

Np lol

sinful pivot
#

How do I check how many times a command has been ran throughout the bots time?

#

Do I need to save it in a database/make a counter for it myself or is there a pycord function that does it for me

proud mason
#

.rtfm command_completion

winter condorBOT
proud mason
#

uh there is supposed to be on_command_completion prefix cmds too

#

not sure why it didnt show up in the tag

sinful pivot
#

I don't need prefix cmds, I use slash commands

proud mason
#

ah

proud mason
sinful pivot
#

Anyways, I suppose I use this for #1078304324066746478 aswell right?

#

Cause it's basically the same thing

proud mason
sinful pivot
#

Yeah I know

proud mason
#

cool

sinful pivot
#

application_command will run when the command is ran, if a check returns False and it returns it'll still pop up in that event
in the completion one, when all checks have passed and the command completes without any errors, that's when the completion event is trigered

#

Right?

proud mason
#

yep perfect

sinful pivot
#

big brain

proud mason
proud mason
sinful pivot
#

Yeah can do that

#

or I can have a db table which has entries for tutorials & just check if there's an entry for the user that ran the command or not

#

Which one would be better in your opinion?

proud mason
high jay
#

This is my visual studios code
and when i click on run the whole code just goes away and it gives me "invalid syntax" even though i don't see any problems with the code
im sorry im new to vscode

#

while the same code works perfectly fine here

true panther
#

Did you save the file?

young bone
#

^

wary rover
#

Hey!
Someone know how to upload a file inside a slash command option?

#
file: discord.Option(discord.File, description="Sound to upload")

This doesn't work

wary rover
crisp swift
#

hey i don't know exactly why but the dotenv package dont work

full basin
#

Did you install it?

crisp swift
#

this was the command "python -m pip install python-dotenv"

#

yes

#

i also tried to uninstall it and reinstalling it wit a flag called "--no-cache-dir" so it wont reuse what was previously installed in case that there were corrupted files

proud mason
#

(for me, just closing and opening the file works. but restarting the editor is the safest way)

proud mason
crisp swift
#

coud be a problem with VS-Code

#

??

#

omg im dum

#

i think i misspled inpir

#

import

#

no, false alarm its not the case

cyan quail
wary rover
#

Hey!
Do you think it works? I don't, any idea of the error?

groupSoundPlay = discordCommands.SlashCommandGroup("soundplay", "Various commands to play sounds", parent=None)
groupDeleteElement = discordCommands.SlashCommandGroup("delete", "Various commands to delete sounds or folders", parent=groupSoundPlay)
proud mason
#

windows mac or linux?

crisp swift
#

Windows

#

coud be because i recently installed 3.11

wary rover
#

3.11 supported now?

proud mason
proud mason
cyan quail
#

3.11's been supported for a while

wary rover
#

Oh, my bad, im outdated

crisp swift
#

the "..." has to be in the command ?

cyan quail
#

no ... is just a placeholder

crisp swift
#

ok

cyan quail
#

also i didn't even know -e was a thing, you can shorten it to python -3.11

solid agate
#

Did something change in discord.ui.Select in 2.4? Im getting _underlying isnt found on my Select thingy when I call the command for it.

proud mason
cyan quail
#

show code

proud mason
#

i forgot to specify that

high jay
crisp swift
#

ok

cyan quail
#

oh actually i'm slightly off, python -e -3.11 would shorten to py -3.11

crisp swift
#

i succsessfully installed pip 23.0.1

high jay
crisp swift
solid agate
#

thanks mate!

cyan quail
#

tbf if it worked before then i can see why, but that technically shouldn't have worked in the first place

#

all good

solid agate
#

so it used old code.

proud mason
crisp swift
#

in the gear?

proud mason
#

check you dont have any other 3.11 installed

crisp swift
#

ah isee

#

in works !!!!

#

thanks mate :))

proud mason
#

cool

crisp swift
#

what free host you recomend for your bot

#

maybe firebase?

proud mason
winter condorBOT
crisp swift
#

nice thx

young bone
#

if the internet is stable

crisp swift
#

oh thats also a good option

young bone
#

I use one for my bots

crisp swift
young bone
crisp swift
#

ok thanks

serene silo
#

Does anyone knows, how to make a 2th acc tracker?

blissful hazel
green hinge
#

Do I need to set the timeout in the view class? Or where would be the right place?

timeout=None
class GewaesserView(discord.ui.View):
    async def __new__(cls, *args, **kwargs):
        obj = super().__new__(cls)
        await obj.__init__(*args, **kwargs)
        return obj
    
    async def __init__(self, bot: discord.Bot):
        self.bot = bot
        super().__init__(await Gewaesser(self.bot))


class Gewaesser(discord.ui.Select):
    async def __new__(cls, *args, **kwargs):
        obj = super().__new__(cls)
        await obj.__init__(*args, **kwargs)
        return obj
    
    async def __init__(self, bot: discord.Bot):
        self.bot = bot
        options = [discord.SelectOption(label=water) for water in bot.waters]
        super().__init__(
            placeholder="Wรคhle das Gewรคsser aus",
            min_values=1,
            max_values=1,
            options=options,
        )
        
    async def callback(self, interaction: discord.Interaction):```
young bone
serene silo
green hinge
# young bone why?

Call a function in the init that retrieves data from the database, that's why.

#

Can I set the timeout like this?

class GewaesserView(discord.ui.View):
    async def __new__(cls, *args, **kwargs):
        obj = super().__new__(cls)
        await obj.__init__(*args, **kwargs)
        return obj
    
    async def __init__(self, bot: discord.Bot):
        self.bot = bot
        super().__init__(timeout=None, await Gewaesser(self.bot))


class Gewaesser(discord.ui.Select):
    async def __new__(cls, *args, **kwargs):
        obj = super().__new__(cls)
        await obj.__init__(*args, **kwargs)
        return obj
    
    async def __init__(self, bot: discord.Bot):
        self.bot = bot
        options = [discord.SelectOption(label=water) for water in bot.waters]
        super().__init__(
            placeholder="Wรคhle das Gewรคsser aus",
            min_values=1,
            max_values=1,
            options=options,
        )
        
    async def callback(self, interaction: discord.Interaction):```
blissful hazel
# serene silo So that you can track a 2th Account from Someone

There is no way too know for sure if an account is an alt, you can try looking at their connections on their profile, or reverse searching their pfp.
Source: https://www.swipetips.com/how-can-you-tell-if-a-discord-account-is-an-alt/
You can probably find more by googling

Swipe Tips

Alts are a part of life on Discord. Some people use them so they can have different personas while others use them to sidestep bans. Iโ€™m sure there are other reasons to have alts on the platform that I

green hinge
#

Can I save the ID of an ephemeral message that is generated when a user clicks on a button in order to delete this message again?

blissful hazel
# green hinge Can I save the ID of an ephemeral message that is generated when a user clicks o...

If the button is on the message you want to delete, you can just get the message from the interaction of the button callback (https://docs.pycord.dev/en/master/api/models.html#discord.Interaction.message, idk how to use the bot). if not you have to save it in a db

green hinge
#

I want my interaction.response.send_message in a list. But when I do that I always get an error message.
How can I fix the problem?

self.spotdaten['channel_interaction'] = channel_interaction
TypeError: list indices must be integers or slices, not str
crisp swift
#

im trying to make a "!Clear" command and i dont know why its failing

#

it prints the error: discord.errors.ClientException: Callback for clear command is missing "ctx" parameter.

#

i serched and i did not found any args for the ctx parameter

meager mica
#

so i want to edit a message when you submit a modal but i dont want to respond is there a way i can do the besides responding to it then deleting message

#

if i dont respond it says it fails or whatever

sand forum
#

How can I upload an image along along with an embed? I know it's possible to pass an image link to embed.set_image(), but is there some way to use an image that hasn't been uploaded elsewhere?

sand forum
crisp swift
#

ahh ok thx

sand forum
#

Np

sand forum
green hinge
crisp swift
#

what is the correct argument for the parameter "ctx"

#

discord.TextChannel.purge(self=discord.TextChannel, ctx=)

sand forum
crisp swift
#

@client.command()
async def clear(self, ctx):
await discord.TextChannel.purge(self=discord.TextChannel, ctx=)

sand forum
crisp swift
#

thx

icy tulip
#

how can you use pages.Paginator In help commands? specifically with get_destination() nvm loul

icy tulip
#

can the help command be removed from none "none" you just skip over It In an Iteration? I put my help command In Its own cog, so using "help" by Itself lists It twice when listing commands

craggy ibex
#

Does anyone know if Discord changed anything with webhooks recently?

My global chat bot is no longer working because all webhook names get updated whenever they change, instead of leaving it as it was before.

silver moat
craggy ibex
craggy ibex
silver moat
#

np

tribal bough
#

how can i make \n work?

limber urchin
#

Replace it with an actual \n in your string

civic jayBOT
#

"red" is not a valid color. Please enter a color in the #ffffff format. (hex)

crisp swift
#

im trying to make a clear command and i dont know why isn't working at all:

#

@bot.command()
@commands.has_permissions(administrator=True)
@commands.cooldown(1, 3, commands.BucketType.user)
async def clear(ctx, limit = 100):
await discord.TextChannel.purge(ctx , limit=100, check=int(discord.User))
await print("Mensajes eliminados correctamente")

grizzled sentinel
crisp swift
#

Thanks!!

green hinge
#

Can I have empty messages sent as placeholders to be able to edit this message later?

waxen whale
#

๐Ÿ‘€

pale quest
#

i want help

actually when someone uses a command bot stops responding untill the command gets processed.

#

and its an chat bot model.

#

so it takes 2-4 sometimes 20 seconds to process a request.

#

i am using await. i tried making another fucntion and then starting as thread

#

but does not work it says use await.

#

i want the that if a user uses a command and then bot should start a background process.

#

and continue the work. so that i do not makes much delay.

young bone
pale quest
young bone
#

for the request

pale quest
#

my code is like

young bone
#

....

#

which library...

pale quest
pale quest
#

pytorch

young bone
#

?tag requests

obtuse juncoBOT
#

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

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

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

waxen whale
#

oh dear, here we go again

pale quest
#

`def sjjsjsj(msg):
#done some processing
return request

#on_message:

if 'tag' in message.content:
await message.channel.send(sjjsjsj(msg))`

#

its something like this

#

i want that

#

if 'tag' in message.content: startbackgroun()

waxen whale
#

It seems to me that you are trying something that is above your skill level at the moment. hides

pale quest
#

i trued it with user bot

#

tried.

#

and i used threading.Thread

young bone
#

....

proud mason
#

use asyncio.to_thread to call blocking functions

still helm
young bone
still helm
#

yes

rapid geode
#
Ignoring exception in on_guild_remove
Traceback (most recent call last):
File "/opt/venv/lib/python3.9/site-packages/discord/client.py", line 382, in _run_event
await coro(*args, **kwargs)
File "/app/main.py", line 50, in on_guild_remove
em.add_field(name="Member Count:", value=f"{guild.member_count}", inline=False)
File "/opt/venv/lib/python3.9/site-packages/discord/guild.py", line 990, in member_count
return self._member_count
AttributeError: _member_count
Ignoring exception in on_guild_remove
Traceback (most recent call last):
File "/opt/venv/lib/python3.9/site-packages/discord/client.py", line 382, in _run_event
await coro(*args, **kwargs)
File "/app/main.py", line 50, in on_guild_remove
em.add_field(name="Member Count:", value=f"{guild.member_count}", inline=False)
File "/opt/venv/lib/python3.9/site-packages/discord/guild.py", line 990, in member_count
return self._member_count
AttributeError: _member_count
#

code:

@bot.event
async def on_guild_remove(guild):
    em = discord.Embed(title=f"Guild Removed", description=f"**Name**: {guild.name}\n" ,color=0xE74C3C, timestamp=guild.created_at)
    em.add_field(name=f"Guild ID:", value=f"`{guild.id}`", inline=False)
    em.add_field(name="Member Count:", value=f"{guild.member_count}", inline=False)
    em.add_field(name=f"Owner:", value=f"{guild.owner} (`{guild.owner_id}`)", inline=False)
    try:
        em.set_thumbnail(url=f"{guild.icon.url}")
    except:
        em.set_thumbnail(url=f"https://cdn.discordapp.com/avatars/902555662964359228/a8db71b81cbaed7567d996551bd0f56f.png")
    em.set_footer(text=f"Guild Created At")
    await bot.get_channel(912006221182152725).send(embed=em)
proud mason
still helm
#

uhhh i am trying it ๐Ÿ™‚

#

thanks !

proud mason
#

np

proud mason
#

also show pip list

rapid geode
rapid geode
proud mason
#

does the error remain after updating to 2.4.0?

feral lintel
#

a quickie : How does self.bot.wait_for (ctx.bot.wait_for('')) actually works?

proud mason
#

it uses Futures to deal with stuff and uses asyncio.wait_for on the future

rapid geode
proud mason
#

this person seems to have a similar error
#998272089343668364 message

#

you and that person are both on python 3.9 ๐Ÿค”

proud mason
feral lintel
proud mason
#

why would you use that to fetch a member tho?

#

use bot.get_user or bot.fetch_user or guild.get_member or guild.fetch_member

feral lintel
proud mason
#

i believe the docs has an example for that

#

.rtfm wait_for

feral lintel
true panther
#

How would one go about detecting emojis in a message? I tried a simple regex r":\w+:" but it seems to not match thunk5

true panther
proud mason
#

you can get the name and id separate using that regex

#

as it has groups

true panther
#

Not needed but maybe will be useful for the future, thanks again.

rough venture
#

hey uh, how do I make "choices" in discord.Option work with discord objects

as shown in the image

#

please ping me on responce

calm plume
#

is it possible to delete the discord thing for This message is pinned when i pin a message?

#

and delete that on the command function(not having to use events and all that stuff)

proud mason
#

I'm not sure what the check would be

calm plume
#

doesn't make sense

proud mason
proud mason
#

Pin a message, wait for the system message, delete the system message

#

Looks right to me

calm plume
#

but like im doing the pin from the bot

#

and i wanna delete it immediately

proud mason
#

Yea so

errant craneBOT
#

Here's the wait for event example.

proud mason
#

See how that works

#

You would be waiting for a message event for the system message after pinning

calm plume
#

But i am telling u

#

i am using the bot

#

and don't want events

proud mason
#

How does a bot function without events....

calm plume
#

like

await message.pin()
calm plume
#

but

proud mason
calm plume
proud mason
#

Pin the message, use bot.wait_for to wait for the system message event to come to your bot, then delete that message

calm plume
#

ok give me an example

proud mason
proud mason
calm plume
#

but the problem is it will probably block the code as it will wait for the message

#

like

#
# stuff
def check():
  # ...
pin_msg = bot.wait_for(check = check)
await pin_msg.delete() # this won't probably execute as it has to wait for a new pin message
proud mason
#
await msg.pin()
sys_msg = await bot.wait_for('message', check=check)
await sys_message.delete()

Figure out check on your own. Hint - it's related to msg.type

calm plume
#

tbh what im trying to tell u

proud mason
calm plume
calm plume
#

ur executing msg.pin() first

#

then bot.wait_for

proud mason
#

Yes i agree there is a very tiny time lag

#

You could use asyncio.gather to launch 2 tasks simultaneously

calm plume
#

this could work

proud mason
#

Yea you would need to structure your code a bit differently ofc

calm plume
#

i get it

fervent kindle
#

I need help with this

wind cairn
#

How hard would it be convert a discord bot which was written in older discord.py to the current version?

fervent kindle
#

I be struggling

proud mason
#

Cool

proud mason
#

Find and replace can come in handy

wind cairn
#

oh I have issues with loading other commands..

proud mason
#

Check the migrating to V2 page on the docs

wind cairn
#

My bot only sees 2 commands which are specified in main.py, but others are in the commands folder in different .py files loaded by python for file in os.listdir("./commands"): if file.endswith(".py"): name = file[:-3] bot.load_extension(f"commands.{name}") but it doesn't work

proud mason
#

Try using bot.load_extentions and pass the folder name

#

The library should load files inside recursively

#

Also, any error?

wind cairn
#

Nope

proud mason
#

And can you show pip list

wind cairn
#

When I try to use any of the commands it just shows command not found in the terminal

proud mason
#

Hmm

#

Mind sharing your code?

wind cairn
wind cairn
proud mason
proud mason
wind cairn
#
from discord.errors import Forbidden
from always_active import keep_alive
from discord.ext import commands
from commons import Error
import discord
import dotenv
import os

version = "0.2.1"

#Only run keep_alive if ran on replit
if [k for k in os.environ.keys() if 'REPL_' in k] != []:
    keep_alive()

dotenv.load_dotenv()
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)

for file in os.listdir("./commands"):
    if file.endswith(".py"):
        name = file[:-3]
        bot.load_extension(f"commands.{name}")


class CustomHelp(commands.MinimalHelpCommand):
    async def send_pages(self):
        destination = self.get_destination()
        for page in self.paginator.pages:
            emby = discord.Embed(description=page,
                                 color=discord.Colour.blurple())
            try:
                await destination.send(embed=emby)
            except Forbidden:
                await destination.send(
                    Error.bot_missing_permission("Embed Links"))


bot.help_command = CustomHelp()


@bot.command()
async def about(ctx):
    embed = discord.Embed(title=f"Remade by AloneER0",
                          color=discord.Color.green())
    embed.add_field(
        name="About",
        value=
        f"{len(bot.guilds)} servers\n\n[Bot Invite](https://discord.com/api/oauth2/authorize?client_id=858122253488095233&permissions=274881185986&scope=bot)"
    )

    embed.set_footer(text=f"{bot.user.name} Version {version}")
    await ctx.send(embed=embed)


async def presence():
    await bot.change_presence(activity=discord.Streaming(
        name=f"{bot.command_prefix}help | {len(bot.guilds)} servers",
        url="https://www.twitch.tv/lol"))


@bot.event
async def on_ready():
    await presence()


@bot.event
async def on_guild_join(guild):
    await presence()


# Unable to get token
bot.run('TOKEN)```
proud mason
#

Looks all right

wind cairn
#

I can try something!

proud mason
#

Possible to show one of the cog files which doesn't load?

proud mason
#

You could add a few print lines in the cog

#

Like in the init

wind cairn
#

ah yes ERROR: Could not install packages due to an OSError: [Errno 30] Read-only file system: '/nix/store/0pyymzxf7n0fzpaqnvwv92ab72v3jq8d-python3-3.10.9/lib/python3.10/site-packages/charset_normalizer-3.0.1.dist-info'

proud mason
#

And setup function

#

To see if the cog actually loads

wind cairn
proud mason
#

So setup function isn't even called?

wind cairn
#

Nope

proud mason
#

Don't forget the s at the end

#

If that doesn't work, show your file structure

wind cairn
#

Let me try

#

AttributeError: 'Bot' object has no attribute 'load_extensions'. Did you mean: 'load_extension'?

fervent cradle
#

hey, my IDE warns me that "import discord" is not in my requirements, i did see that 'discord' is the pycord wrapper, so what should i add at my requirements at last

novel jay
#

Not really pycord related but in its my pycord project so i thought I'd ask, the lib i use for SQLite is async, but you obviously can't use an async function in an autocomplete (right?) so i was wondering how i could, since im trying to get values from the DB
Please ping when responding!

novel jay
silver moat
fervent cradle
errant craneBOT
#

Here's the slash autocomplete example.

novel jay
#
C:\Users\Brand\Documents\GitHub\sqlbot>py main.py
  File "C:\Users\MYPCNAME\Documents\GitHub\sqlbot\main.py", line 40
    async def remove(ctx, message: Option(autocomplete=await get_messages)):
                                                       ^^^^^^^^^^^^^^^^^^
SyntaxError: 'await' outside function
#

am i dumb or something

silver moat
#

the autocomplete example shows an implementation that allows you to use async funcs

novel jay
#

ohhh hold on

meager mica
full basin
#

add_field has an inline kwarg

#

.rtfm Embed.add_field

winter condorBOT
full basin
#

Pass it as False

meager mica
#

ok thanks

young bone
#

why do you use ```py
async def

#

also read the rules #help-rules

limber urchin
#

A discord bot should not be your first Python project

fervent cradle
#

Hey quick question, Do discord bots come under much SQL injection when using an SQL database

spare juniper
#

if your sql database is insecure it can be attacked

grizzled sentinel
#

Yeah, very high risk

spare juniper
#

now will people want to attack your sql database? maybe

#

although if you mess up it wont be hard to hack it

always assume the user is a hacker

fervent cradle
#

so a 20 minute db job just turned into a good 2 hour ๐Ÿ˜ญ Okay cheers thanks for the help

grizzled sentinel
#

Any user input is a risk.

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

fervent cradle
#

even then its still prone to attacks

limber urchin
#

SQL injections are always a risk if you're lazy

#

Use parameterized queries

spare juniper
#

and what are these attacks

grizzled sentinel
#

I use asyncpg as my connecter lib and they say that they protect against SQL injection if you use arguments in the SQL and not directly insert it.

limber urchin
#

^^ aka parameterized query

spare juniper
#

if i sanitize inputs and use secure sql libs i should be fine right

#

or is there another attack i need to worry about

fervent cradle
#
    mycursor.execute(f"INSERT INTO `Profile` (`User_Id`, `Name`, `About`, `Age`, `Gender`, `Location`) VALUES ('{user}', '{name}', '{about}', '{age}', '{gender}', '{location}')")

So smth like this would be shit? its just basic as fuck, so i need to parametrize it?

and im using PostgreSQL

limber urchin
limber urchin
spare juniper
#

alright

fervent cradle
#

See this is the shit they dont teach you in college man, thanks for the help guys <3

proud mason
#

.rtfm load_extensions

undone mulch
#
member = message.author
await member.edit(reason="Timeout", mute=True)```
#

How do I add durations to timeouts?

#

I wanna time them out for 3 seconds

storm oyster
#

And the until parameter takes in a datetime.datetime object

#

Wait actually use timeout_for instead as it takes in datetime.timedelta

tired goblet
#

hi guys, how can my bot ping someone on discord?

#

i think i know we can use their user id and wrap it in <> with @

#

but is there a way to just use plain text?

#

like for me, could the bot do @Boa Constructor ?

proud mason
#

Although you can do a few workarounds

#

use utils.get to find a member with that name

tired goblet
#

oh i see

proud mason
#

and then do member.mention

tired goblet
#

okay

#

can i explain my context a bit more here?

#

or does that require a new post of its own

proud mason
tired goblet
#

okay thanks

olive marsh
#

Hi. Is there a way to take input from a mentioned user?

fervent cradle
#

any idea why my

@bot.event
async def on_member_join(member):```
is not being triggered, also on_member_remove does not trigger ๐Ÿค”, used to work before i switched to pycord
proud mason
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.

olive marsh
proud mason
olive marsh
fervent cradle
proud mason
#

?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)
fervent cradle
#

do i have to remoevthis from requirements?

proud mason
proud mason
olive marsh
fervent cradle
#

oke tnx

proud mason
#

and you should uninstall and reinstall py-cord after you do that

fervent cradle
#

okay, will try to do it, but after that, is my on_member_join event going to automatically trigger or do i have to do anything else?

proud mason
#

you need member intents for it

#

other than that, it should work

olive marsh
#

Can you send a link? I can't seem to find it

proud mason
#

yea one sec

fervent cradle
#

yea it works now, tnx โ˜•

proud mason
#

.rtfm wait_for

proud mason
#

that has it

olive marsh
#

Thank you

proud mason
#

np

olive marsh
#

I'm trying to make a Rock Paper Scissors command, where you can play with other users. I'm almost 2 hours on this and it says Member has no attribute lower. It can't work. What am I doing wrong?

#

I'm 100% sure I screwed up but I don't know where and how I did

olive marsh
#

๐Ÿฅฒ

proud mason
olive marsh
#

I just wanna take mentioned user input ๐Ÿฅฒ

olive marsh
proud mason
#

and bot.wait_for doesnt work that way. what are you trying to do

olive marsh
proud mason
#

so use checks

#

and event should be "message"

olive marsh
#

Would that be waiting for author input?

proud mason
#

.rtfm wait_for

olive marsh
proud mason
#

that has an example

olive marsh
#

I want it to wait for mentioned user input

proud mason
#

you can have check like msg.author == member

olive marsh
proud mason
#

so maybe define a function inside a cmd, or use lambda if you wanna keep stuff simple

olive marsh
#

Let me try

#

.rtfm wait_for

proud mason
# olive marsh Let me try

oh and btw, wait_for will return the message, so take the content from that message and set it to member_value

olive marsh
#

await allowed only within async function

#

what?

#

I just want to take input from the mentioned user ๐Ÿ˜ฃ

#

I'm so confused

#

And frustrated

proud mason
#

can you show the updated code?

olive marsh
#

It's inside a command with async function

proud mason
#

full error?

olive marsh
#

Maybe I should just quit

#

Easier

proud mason
#

no no you are very close

olive marsh
#

Bullcrap :/

proud mason
olive marsh
#

Give me a sec

proud mason
#

if you wanna which ones, 78 and 83 (if you use lambda)

olive marsh
#

How do I even start with this? I'm confused

proud mason
olive marsh
#

oh

proud mason
#

i also recommended checking message channel is same as ctx.channel

olive marsh
#

so, def check(message: discord.Message):
return message.author == member and message.channel == ctx.channel
?

olive marsh
#

and next I need to fix the try lines, right?

#

so await bot.wait_for('message' OR message?

proud mason
proud mason
olive marsh
#

and now how do I store the reply to a variable? Oh wait dumb question

#

I can just put the message variable to if statements, right?

olive marsh
#

Awesome

proud mason
#

message.content would have the content

olive marsh
proud mason
olive marsh
#

My god thank you

#

if statements should be inside the check function?

proud mason
olive marsh
#

it says message is not defined

proud mason
#

can you show updated code?

#

and the error

olive marsh
#

should I define it outside of the check function too?

proud mason
#

you will get the message object from wait_for

olive marsh
#

What?

#

oh

#

Now it seems ok

#

let me put the right variable in the if statements now and I'll try to run it

#

all my friends are offline rn jesus

#

I can't even test it ๐Ÿ˜‚

young bone
#

Create an alt?

olive marsh
young bone
# olive marsh Oh right

And you can just use the new Discord login to switch really fast without entering the Password

olive marsh
#

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

#

That's the whole code for this command

proud mason
#

at line 80

olive marsh
#

oh

proud mason
#

(or you could defer but then it would look in a weird order)

#

you can even send an ephemeral response at the beginning saying smth like "game started". and then use ctx.send everywhere else in the code

olive marsh
#

So close

proud mason
#

๐Ÿ‘€

olive marsh
#

I think I know the problem

#

I think

#

Oh

#

Oh no I don't

#

I think I know what to do

#

Instead of trying to use a variable for the final ctx respond, I'll just add await ctx.respond to every if statement

#

Because it has issues with the variable

proud mason
olive marsh
#

It doesnt highlight it on message.content. Will it still work?

#

message.content.lower()

#

or I could put message.content to a variable, right?

#

example: member_value = message.content

#

still not highlighted...

#

Oh my god

#

It's working

#

@proud mason you saved me โค๏ธ

#

I owe you a coffee man..

proud mason
olive marsh
#

I was about to cry for real

calm plume
#

is there any way to speed up fetch message

#

or nah

limber urchin
#

Depends on how you're doing it

#

if you mean literally the function, no, it runs as it is. It depends a lot on your network speed and how close your host is to the Discord API servers.

#

But you should always do a get_message first, because if the message is in the bot's cache, it will be almost instant instead of fetching through Discord API.

calm plume
#

ok

#

another quick question

#

can i make this line faster?

if msg.author in await msg.reactions[0].users().flatten(): val += 1
if msg.author in await msg.reactions[1].users().flatten(): val += 1
limber urchin
#

Use asyncio.gather to run the coroutines concurrently.

proud mason
calm plume
#

and i found its slower

proud mason
#

How did you do those?

limber urchin
#

They will probably be slower if you use them incorrectly

calm plume
#
results = await asyncio.gather(msg.reactions[0].users().flatten(), msg.reactions[1].users().flatten(), return_exceptions=True)
limber urchin
#

And that was slower? How did you measure that?

calm plume
#

with the time

#

i got start = time_perf_counter()

#

and yknow

proud mason
#

Why not use async iterator? It will break the loop when you find the member and should save you some time

calm plume
#

like async for?

proud mason
#

Yes

calm plume
#

ik il try

#

doesn't seem like it

took 0.31s to update
took 1.52s to update theme reactions
took 2.49s to update theme reactions
took 1.65s to update theme reactions
took 1.43s to update theme reactions
#

compared to original

#

oh wait nvm

#

original is quite unbalanced

#

sometimes it takes 1 second, other times 22 seconds

limber urchin
#

What is your bot's latency to the Discord API?

#

That might be due to rate limits then

calm plume
calm plume
limber urchin
#

or whatever your client var is called

#

.rtfm latency

calm plume
#

it says 0.16324486599999988 seconds when i do it on the event @on_ready

limber urchin
#

So that'd be 163ms

#

not that bad

calm plume
#

so its the code that causes it

limber urchin
#

Eh, could be a lot of things. Since it's so inconsistent it's probably not the code

#

Well not the code itself at least

proud mason
#

It also largely depends on the number of reactions on the message

#

But not 22 seconds ofc

limber urchin
#

Are you using any hosting platform? Or just from home?

calm plume
#

from home

#

i didn't host it yet

#

u want to examine the code or nah?

limber urchin
#

Well my guess is that you're being ratelimited somehow. That would probably cause a pretty long wait time on some API calls

calm plume
#

here it is if u want to view it

async def reaction_change(payload):
    start = time.perf_counter()
    msg: discord.Message = await most_used["theme_vote"].fetch_message(payload.message_id)
    db = sqlite3.connect("./DB/Main.db")
    cursor = db.cursor()
    theme_msg = cursor.execute("SELECT Author_ID FROM theme_msgs WHERE MSG_ID = ?", [payload.message_id]).fetchall()
    db.close()
    try:
        if theme_msg[0][0] == payload.user_id:
            return
    except IndexError: pass
    val = 0
    results = await asyncio.gather(msg.reactions[0].users().flatten(), msg.reactions[1].users().flatten(), return_exceptions=True)
    for i in range(0, 1):
        if msg.author in await msg.reactions[i].users().flatten(): val += 1
    await theme_reaction_update(msg, val) # doesn't take much seconds only like 0.1 or even 0.0s in some cases
    with open ( "./Main.json", "r" ) as f :
        data = json.load (f)
        await update_leaderboard(data["jams"][leaderboard_index]["name"], most_used, columns) # same doesn't take too many seconds but does take โ‰ˆ 0.4s
    print(f"took {time.perf_counter() - start:.2f}s to update theme reactions")
#

i wrote comments to describe some functions how much time they take

#

and they aren't the problem

limber urchin
#

I assume that's an event listener?

calm plume
#

it listens to both add_reaction and remove_reaction

limber urchin
#

And how often does that event fire? Because if it's very often you're definitely going to be rate limited.

calm plume
#

well depends if the users are reacting to the messages on that time

#

if i spam it occurs(which i assume is the rate limit)

#

if i take it more "gentle"

#

it doesn't show the issue

limber urchin
#

Well yeah, spamming is going to cause a rate limit. So that's why you're getting really long wait times sometimes

calm plume
#

and yeh i wanna update it in real time

limber urchin
#

There's no way to get around the rate limit. So you'll need to find a workaround, or just deal with the long wait times.

calm plume
#

any workarounds u suggest to take into account?

limber urchin
#

One thing you should do is not use fetch_message on every event. Use get_message, if that returns None, try fetch_message

limber urchin
#

And I would also not use a json file to store any frequently read data. Read the file into a variable that can be accessed from that function and refer to that.

calm plume
#
AttributeError: 'TextChannel' object has no attribute 'get_message'
#

i don't use it often

#

nvm

#

its bot.get_message()

limber urchin
#

But even then, caching is better if it's frequently accessed

calm plume
#

but i might provide in the future some more arguments

#

and json isn't a main issue

tired goblet
#

bot = discord.Bot(intents = discord.Intents.all())

@bot.event
async def on_ready():
  print(f"{bot.user} is ready and online!")

  for member in bot.get_all_members():
    if member.display_name == 'TheRuminator':
      print(member.id)``` why does this print my id twice?
silver moat
tired goblet
#

oh okay

#

so the get all members gets them from a cache?

silver moat
#

In pycord, get refers to cache while fetch refers to API requests

tired goblet
#

okay

#

so i can just replace get with fetch then?

silver moat
#

i donโ€™t think there exists a method

tired goblet
#

ah okay that method doesnt exist

silver moat
#

.rtfm fetch_all

winter condorBOT
#

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

limber urchin
#

To actually get all members you would have to loop over the bot's guilds and fetch the members from each guild

tired goblet
#

oh okay

#

hmm, i think its safe to get them from get if i face problems, i'll try looking for a fetch method

wind cairn
young bone
#

can you not get really fast a rate limit if you use fetch?

cyan quail
#

You don't need to fetch in that case because it was already done for you

cyan quail
vale heath
#

A quick question can a option in slash cmd can be dependent on other options ?

If yes then upto what extent?

proud mason
silver moat
#

You can change the choices of options.

proud mason
#

Autocomplete would be more recommend

proud mason
#

Because there is no other way to dynamically adjust options or thier values

vale heath
vale heath
#

Do u have an example or guide link to check that out ?

errant craneBOT
#

Here's the slash autocomplete example.

silver moat
#

doesnโ€™t do exactly what you want, but it is a starting point

#

also use docs

#

.rtfm autocompletecontext

vale heath
#

Ok thanks ok_fidget

proud mason
#

ctx.options should have what you are looking for

pallid magnet
#

I am try to create few button using for loop, however when I click the button, the interaction is not work

#
class Neve(View):
    def __init__(self):
        super().__init__(timeout=None)
        self.event_list = ["Apex", "LOL", "PUBG"]
        for i, event in enumerate(self.event_list):
            button = Button(style=discord.ButtonStyle.primary, label=f"{i+1}: {event}")
            button.callback = self.create_callback(i)
            self.add_item(button)

    def create_callback(self, index):
        async def callback(button, interaction):
            if bot.event_variables[index].find(str(interaction.user))<0:
                bot.event_variables[index] = bot.event_variables[index] + str(interaction.user) + "\n"
            await interaction.response.edit_message(
                content=f"List:\n1.Apex:\n{bot.event_variables[0]}\n2.LOL:\n{bot.event_variables[1]}\n3.PUBG:\n{bot.event_variables[2]}\nPlease select ",
                view=self
            )
        return callback
proud mason
#

You need to subclass button

proud mason
pallid magnet
#

When the database is update, it will send/edit a update embed, list and button for polling

wind cairn
#

Now to figure out how to properly import those commands

proud mason
wind cairn
#

Then now I'm on the latest one

proud mason
#

That way you can just refer your db to check if the member has added a reaction or not

wind cairn
#
bot.load_extensions(*names, recursive=True, store=False)``` not sure what to exactly put in names
calm plume
wind cairn
#

like when I tried to put the folder it showed a Syntax error

calm plume
#

things like MongoDB do tho

proud mason