#Basic Pycord Help (Quick Questions Only)

1 messages · Page 1 of 1 (latest)

woeful spindle
#
Ignoring exception in on_command_error
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 181, in wrapped
    ret = await coro(*args, **kwargs)
  File "/home/container/cogs/info.py", line 85, in sbanner
    e.set_author(name=f"Here is {n}'s banner:")
TypeError: set_author() missing 1 required positional argument: 'self'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.9/site-packages/discord/client.py", line 382, in _run_event
    await coro(*args, **kwargs)
  File "/home/container/cogs/events.py", line 45, in on_command_error
    raise error
  File "/home/container/.local/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 344, in invoke
    await ctx.command.invoke(ctx)
  File "/home/container/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 927, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/home/container/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 190, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: set_author() missing 1 required positional argument: 'self'
#

This isn’t working for some reason, can anyone help?

full basin
#

Code

woeful spindle
#
@commands.command()
    async def sbanner(self, ctx):
        e = discord.Embed()
        n = ctx.guild.name
        e.set_author(name=f"Here is {n}'s banner:")
        e.set_image(url=ctx.guild.banner)
#

nvm

#

discord.Embed just needed ()

#

apparently the guild object doesn’t have the banner_url attribute, how could I get the guild banner then?

#

tried looking on google but it was useless

fervent cradle
#

Is there an slash command option where you can enter a channel

rough venture
#

yes

#

channel: discord.TextChannel

fervent cradle
full basin
#

banner.url

loud holly
#
        try:
            Reviewing_Menu.add_field(
                name="Snacks",
                value=f"{self.snack_menu.values[0]} | {self.snack_menu.values[1]}",
                inline=False
            )

            for counter in range(2):
                Collected_Price.append(Food_Price[self.snack_menu.values[counter]])

        except:
            Reviewing_Menu.add_field(
                name="Snacks",
                value=f"{self.snack_menu.values[0]}",
                inline=False
            )
            Collected_Price.append(Food_Price[self.snack_menu.values[0]])
        

This is showing an error that it's not in range when I used try and except to do, it was working perfectly fine and decided to break

full basin
loud holly
#

I'm using interaction.edit_message before the try and except, could that be the issue in the code breaking?

woeful spindle
#

no url, but still Ty

hollow vale
dreamy nebula
#

^same, just got it recently/today worked fine before

#

didnt update anything as well

smoky forge
#

discord started using 19 digit snowflakes and that broke the webhook authorization process

#

so you'll have to wait for discord to fix that

loud holly
#

some r telling me its lib issue that they don't allow 19 digit snowflakes

#

whilst others are saying it's discord issue

smoky forge
#

nothing pycord can do since it's discord's backend

#

thats your only answer

cyan quail
#

it's not a lib issue yeah

smoky forge
#

cuz everyone else in the ddevs server are having the same issue and there you have djs devs, dpy devs and more

loud holly
#

so I presume pycord was ahead of time since Discord didn't know time existed and made sure measures were in place if this in case ever happened again

#

in terms of snowflake ID changing

cyan quail
#

well in the first place i don't think any validate the length

smoky forge
#

discord maybe thought it wouldn't have been a big issue

cyan quail
#

pretty much

#

considering just webhooks broke and not the entire api, there probably isn't much issue on their end either

loud holly
#

So what kind of features are affected?

cyan quail
#

defer and followup responses are probably the two big ones

loud holly
#

I see, so only one of my command won't execute, Agony which I'm testing rn too

rare ice
#

try not deferring the response and just doing response.send_message

#

it seems to work for other bots

real compass
#

discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: HTTPException: 401 Unauthorized (error code: 50027): Invalid Webhook Token

#

This error is occuring for each and every commands

#

i've also tried regenerating bot token

cyan quail
#

bruh

#

#discord-api-updates

obtuse juncoBOT
#

Error 403 Forbidden (error code: 50027): Invalid Webhook Token
Discord IDs recently went up to 19 digits, and this has lead to errors in the API involving Webhooks. Some affected methods include followup responses/edits, deferring, and potentially other interactions.
For now, we can only wait for a fix from Discord.

tiny wagon
#

whats happening with discord application commands, can i get a short writeup?

#

or link to it

silver moat
full basin
#

man had the answer above

silver moat
#

¯_(ツ)_/¯

loud holly
vital blade
#

how can i check if a message is a boost message

#

tried everything but still doesnt work

cyan quail
rare ice
cyan quail
vital blade
cyan quail
#

message.type will return the type, which is a discord.MessageType object

#

an example would be message.type == discord.MessageType.premium_guild_subscription

vital blade
#

i tried this and throwed errors somehow

cyan quail
#

what error?

vital blade
#

it said it wasnt a message type or something

cyan quail
#

what code did you run

vital blade
cyan quail
#

to get that error

#

tried earlier and the comparison worked fine

vital blade
#

if message.type = discord.MessageType.premium_guild.subscription

#

then or with the tier one 2 and 3 ones

#

the thing is i dont have access to vps rn. when i get back home ill try then show u if something wrong

cyan quail
vital blade
#

im confused atm i dont even know how i used😭

#

nvm ill see that

rare ice
#

it's an if statement

vital blade
#

yea

#

but i forgot how i used

hollow brook
#

Can someone explain how checks can be used with SlashCommandGroup?

#

i got it

#

easy enough

rare ice
#

For slash command name and description localizations, is this correct? The first key being English and the second being Spanish? I tried looking to see if it updated but it says 'No description provided' for the slash command description. It's a global command so maybe it needs time to update?
@slash_command(name="warn", description_localizations={'en-US': 'Warn a member', 'es-ES': 'Advertir a una miembro'})

silver moat
rare ice
silver moat
#
@slash_command(name="warn", description = "Default description", description_localizations={'en-US': 'Warn a member', 'es-ES': 'Advertir a una miembro'})
#

I meant something like that

rare ice
#

oh i see

#

thanks

silver moat
rare ice
#

ah

#

so do I event need 'en-US': 'Warn a member'?

silver moat
#

if it's wrong blame it on the guide, not me :)

silver moat
rare ice
#

oh i didnt check the guide

#

is default english maybe?

silver moat
#

default should be every localization that you didn't mention, probably

rare ice
#

i restarted my discord too

silver moat
silver moat
#

idk

rare ice
#

maybe i need to change the server's main language for it to work?

silver moat
#

but there's guild_locales?

rare ice
#

maybe I need to wait for a little bit to take affect? like how long slash commands take to appear

#

oh I need to apply a build override since its not fully released

silver moat
#

?tag localization

obtuse juncoBOT
#

dynoError No tag localization found.

silver moat
#

?tag localisation

obtuse juncoBOT
#

dynoError No tag localisation found.

rare ice
#

?tag locale

obtuse juncoBOT
#

dynoError No tag locale found.

rare ice
#

yeah that one

#

i got it working already

obtuse juncoBOT
#

dynoSuccess Tag localization created.

rare ice
#

?tag localization

rare ice
#

good

silver moat
#

would be funny if someone decided to advertise their guild here

rare ice
#

now time to use a lot of Google translate

silver moat
#

with a tag

rare ice
#

lol

#

someone could do that

silver moat
#

?tag myserver

rare ice
#

but wouldnt automod catch it?

obtuse juncoBOT
#

dynoError No tag myserver found.

rare ice
#

yeah

silver moat
rare ice
#

i mean like when creating it

#

?tag create myserver <invite>

silver moat
#

</tag create:824701594749763611>

silver moat
fervent cradle
#

Why i get this error?

    job_queue.run_daily(callback=wetter, time=datetime.time(hour=20, minute=16, second=0, microsecond=0,fold=0, tzinfo=None))
TypeError: unbound method datetime.time() needs an argument

rare ice
silver moat
rare ice
#

hm, i could

silver moat
#

and idk sleep instead of copy paste

#

probably not

quiet tendon
#

Can you envoke a modal after responding to the command(ctx.respond)

cyan quail
quiet tendon
#

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

#

I responde to the command with something, than take in input and envoke the modal

#

but i get this error, so i assume you cannot send_modal after responding

cyan quail
#

not in a nice way; there's no internal list of tasks, but asyncio.all_tasks() will return every loop/task across the bot; you can try filter through that

cyan quail
quiet tendon
cyan quail
#

components

quiet tendon
#

There isn't a input component :/ 😄

cyan quail
#

has to be button/dropdown TowaShrug

quiet tendon
#

Got it, can you envoke modal dialog on normal command(not slash)?

cyan quail
#

no, it has to be via an interaction

#

if your normal command sends a button, then that button could invoke the model

quiet tendon
#

is it only for modals

cyan quail
#

?

quiet tendon
#

nvm

#

Thanks

cyan quail
#

allgood

cyan quail
#

eh.... i guess? but you literally just need if message.type == discord.MessageType.premium_guild_subscription

vital blade
#

i want to get the message even if the server reaches level 1, 2 or 3

#

but ill try that

#

idk whatever

cyan quail
#

isee

fervent cradle
#

Hey, i have my error handlers in a cog and they dont seem to be working. Any ideas?

@commands.Cog.listener('on_command_error')
async def on_command_error(self, ctx: discord.ApplicationContext, error):

  if isinstance(error, commands.NoPrivateMessage):
     embed=discord.Embed(title='', color=0xb21a1a)
     embed.set_author(name='Test Bot')
     embed.add_field(name=ctx.author.display_name, value=error, inline=False)
     embed.set_footer(text='')
     await ctx.respond(embed=embed)

Error

Ignoring exception in command addkey:
Traceback (most recent call last):
  File "C:\Users\XeTrinityz\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\bot.py", line 992, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "C:\Users\XeTrinityz\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 355, in invoke
    await self.prepare(ctx)
  File "C:\Users\XeTrinityz\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 277, in prepare
    if not await self.can_run(ctx):
  File "C:\Users\XeTrinityz\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 374, in can_run
    return await async_all(predicate(ctx) for predicate in predicates)  # type: ignore
  File "C:\Users\XeTrinityz\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\utils.py", line 562, in async_all
    for elem in gen:
  File "C:\Users\XeTrinityz\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 374, in <genexpr>
    return await async_all(predicate(ctx) for predicate in predicates)  # type: ignore
  File "C:\Users\XeTrinityz\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 1961, in predicate
    raise NoPrivateMessage()
discord.ext.commands.errors.NoPrivateMessage: This command cannot be used in private messages.
cyan quail
fervent cradle
#

Oh, thank you!

#

is there a way to see what server or channel the command was used

fervent cradle
#

oh yeah i knew that

#

maybe not

wicked helm
#

Heya! I'm being stupid I think...

I have __init__ in my bot class. But when

@bot.event
async def onready(self):
  #Stuff

Is called, or any of the bot commands. I get "missing arg self"

I'm really confused because it worked yesterday 🤣

cyan quail
#

can you show the full code?

fervent cradle
#

How would i check if the channel where the command was used is not a DM with pycord?

This is how i am currently doing it but doesnt seem to work.

async def is_dm(ctx):

    if not isinstance(ctx.channel, discord.channel.DMChannel):

        role = discord.utils.get(ctx.guild.roles, name='MyRole')

        if role in ctx.author.roles:
            return ctx.command

        else:
            embed=discord.Embed(title='', color=0xb21a1a)
            embed.set_author(name='Test Bot')
            embed.add_field(name=ctx.author.display_name, value='This command can only be used in private messages.', inline=False)
            embed.set_footer(text='')
            await ctx.respond(embed=embed)

    else:
        return ctx.command

I made a function that makes commands DM only for everyone but the specified role. However, after moving to pycord it no longer works in the DM

Error

AttributeError: 'NoneType' object has no attribute 'roles'
cyan quail
#

which... typically shouldn't be happening

fervent cradle
#

But it shouldnt even be trying to find the role because its in a DM

wicked helm
# cyan quail can you show the full code?

Of course...

"""
BRVNS Discord Bot Object
"""
from discord import Bot
from src.brvns_bot_logic import BrvnsLogic

class BrvnsBot(Bot):
    """
    BRVNS Discord Bot
    """
    def __init__(self):
        """
        Init
        """
        print("Init the bot")
        self.brvns_logic = BrvnsLogic()
        
    
    bot = Bot()
    
    
    def run(self, token):
        """
        Run the bot
        """
        self.bot.run(token)

    @bot.event
    async def on_ready(self):
        """
        Bot Ready
        """
        print(f"The Bot, {self.bot.name} is ready and online!")

    @bot.command()
    async def sign_up(self, ctx):
        """
        Sign Up string slash command
        """
        author_name: str = ctx.author.name
        await ctx.respond(self.brvns_logic.signup_string(author_name))

    @bot.command()
    async def ping(self, ctx):
        """
        Send bot ping
        """
        await ctx.respond(f"Pong! Latency is {self.bot.latency}")
      

So the errors I get:

Missing self for on_ready
Missing ctx on sign_up and ping

I wanted to also put bot in __init__ but I then got errors with @bot

cyan quail
#

hmmmm

cyan quail
#

yeah...

#

you're subclassing bot then defining another bot inside

cyan quail
silver moat
wicked helm
cyan quail
#

oh it wasn't updated? oops

wicked helm
smoky forge
#

in that case declare the bot outside of the class as well as the commands

silver moat
#

that's not the point of subclassing

smoky forge
#

im saying for the commands

#

so they work

#

since they cant be in the class

silver moat
#

yeah, they can be in class

fervent cradle
#

hi, how do i detect audit log events?

#

for example i want to get audit log events and put them in a channel for easier use

smoky forge
#

i think theres no way to

fervent cradle
#

and automatically update every time a new event is made

cyan quail
#

there's no audit log listener

fervent cradle
#

ah ok, thanks

silver moat
#

but there are individual events for everything

smoky forge
#

youll have to watch for deletes and then check the audut log

cyan quail
#

you'd have to listen to the original event and then query the audit log

smoky forge
#

jinx

silver moat
#

like on_guild_update and on_member_leave

silver moat
#
    async def on_ready(self):
        """
        Bot Ready
        """
        print(f"The Bot, {self.name} is ready and online!")
``` is also how you make an event
wicked helm
silver moat
#

no

#

no decorator for the bot events

wicked helm
#

But it is for the / commands?

Either @bit.slash_command pr @bot.command think360

fervent cradle
#
async def is_dm(ctx):

    if not isinstance(ctx.channel, discord.channel.DMChannel):

        role = discord.utils.get(ctx.guild.roles, name='MyRole')

        if role in ctx.author.roles:
            return ctx.command

        else:
            embed=discord.Embed(title='', color=0xb21a1a)
            embed.set_author(name='Test Bot')
            embed.add_field(name=ctx.author.display_name, value='This command can only be used in private messages.', inline=False)
            embed.set_footer(text='')
            await ctx.respond(embed=embed)

    else:
        return ctx.command

Everything works except when using it in a DM because its trying to check for a role in the dm channel even though i specified it to only check if its not a DM channel.

storm geode
#

Is it possible to make this?

vital blade
smoky forge
#

?tag Timestamps

obtuse juncoBOT
#

To make a timestamp you need a unix timestamp. Then, put your time and date into the converter and copy the "Unix Timestamp" (https://www.unixtimestamp.com/) Then to use the timestamp, follow this syntax: <t:COPIED_TIMESTAMP_HERE:FORMAT>

Where it says FORMAT, you can put a few different things:

R: Relative, says "two weeks ago", or "in 5 years"

D: Date, says "July 4, 2021"

T: Time, "11:28:27 AM"

F: Full, "Monday, July 4, 2021 11:28:27 AM"

Example: (note: 1000190514 is Unix time for 11 September 2001)

<t:1000190514:R> -> says 20 years ago
<t:1000190514:D> -> says 11 September 2001
<t:1000190514:T> -> says 12:11:54
<t:1000190514:F> -> says Tuesday, 11 September 2001 12:11
storm geode
#

thanks

#

<t:1000190514:R>

#

oo nice

quiet tendon
#

anyone?

wicked helm
cyan quail
fervent cradle
#
    @commands.slash_command(name = 'create', description = 'Creates a Spotify account with the provided credentials')
    @commands.check(is_dm)
    async def create(self, ctx: discord.ApplicationContext, email: Option(str, 'Email', required=True), password: Option(str, 'Password', required=True)):

Im adding it as a check on select commands

cyan quail
#

gmmmm

silver moat
#

you realize that typing your password in a slash command is not very smart because everyone can see it right? oh wait it's in DMs

full basin
#

Can't you @commands.guild_only

cyan quail
#

they made a special check to make it guild only unless you have a specific role

full basin
#

Don't mind me then

fervent cradle
#

Its like its ignoring the isinstance

cyan quail
#

but the issue is that ctx.interaction.user is coming up as None

fervent cradle
#

is this related?

cyan quail
#

nope

#

oh wait i see now

#

i was mixing up the error

fervent cradle
#
role = discord.utils.get(ctx.guild.roles, name='MyRole')
AttributeError: 'NoneType' object has no attribute 'roles'
#

thats the error it gives

cyan quail
#

not sure why the isinstance is failing, but you could instead check if ctx.guild:

nova mirage
#

Is there a way to make a !embed command or something?

cyan quail
#

well

#

i don't see why not

nova mirage
#

Oo ok

full basin
#

Won't ctx.guild will be nome if its dms

#

You can switch the isinstance

#

if not ctx.guild:

cyan quail
#

that's the point

fervent cradle
#

Yeah if ctx.guild works

meager heron
#

I have a task. I want it to run every 12 hours, at 0:00 and 12:00. In addition, I want it to run right away when the bot starts up.

So if I start the bot at 16:00, the task will run once, then run again in 8 hours (0:00), then every 12 hours after that.

How can I do this?

errant craneBOT
#

Here's the background task example.

meager heron
#

My first thought is to calculate the next run time every time it runs, then use change_interval(time=...)

errant craneBOT
#

examples/background_task.py lines 28 to 31

@tasks.loop(time=time(3, 0, tzinfo=timezone.utc))  # Task that runs every day at 3 AM UTC
async def time_task(self):
    channel = self.get_channel(1234567)  # Your Channel ID goes here
    await channel.send("It's 3 AM!")```
meager heron
#

That runs once every 24 hours

silver moat
#

just have 2 of them then

fervent cradle
#

When trying to sync slash commands to a specific guild i get a 'Missing Access' error. What perms does it need?

fervent cradle
#

Ah thank you

wicked helm
#

Nice - so the bot runs now! Thanks for the help with that ^^

It's in my server, but does not have permission to use the commands think360

meager heron
#

I thought Discord made that implicit now so long as you have the bot scope

cyan quail
#

you still have to reapply it

cyan quail
meager heron
#

Aha, I didn't see it could be a list

loud holly
silver moat
#

</name:id>

loud holly
#

thanks!

loud holly
#

without typing in the command and getting the ID that way

smoky forge
#

you can go to the integrations page and copy the commands id from there

cyan quail
#

it's because tagging @ everyone like that isn't actually tagging @ everyone, but the internal @everyone role that all members have; it doesn't mention anyone

#

for other roles, that method is correct

smoky forge
#

are command mentions released or are they still testing them out?

cyan quail
#

they should be released

#

you can also just make up random ones

#

</likethis:927474839>

smoky forge
#

</i use arch btw:123577324>

cyan quail
#

not sure if spaces are supported... though technically they should be?

#

</wow nice:823824>

#

</i use arch btw:123577324>

#

maybe limited

#

</i use archbtw:123577324>

#

two spaces?

smoky forge
#

</dontcare didntask plusratio:123456789>

waxen whale
cyan quail
#

ahh

fervent cradle
#

hi, i'm awaiting a message in my bot but when i send a message the message content returns blank

#
 msg = await bot.wait_for('message', check = check)
#

my code

#

it literally returns a blank character no matter what i p0ut

#

msg.content returns blank

#

oops

#

i forgot to enable intents

smoky forge
nova mirage
#

Hi, when I tried installing pycord and then ran import discord in the terminal, I get this error.

import : The term 'import' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ import discord
+ ~~
    + CategoryInfo          : ObjectNotFound: (import:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException```

Anyone know a fix?
round rivet
#

i recommend #help-rules #1

fervent cradle
#

Anyone know how to use regular commands and slash commands?

rugged lantern
fervent cradle
fervent cradle
obtuse juncoBOT
#
full basin
fervent cradle
full basin
#

Make your bot a commands.Bot instance

smoky forge
#

?tag client

obtuse juncoBOT
#
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
alpine helm
#

How can i disable the buttons for a particular user only.
Like a have an embed with two buttons Smash and Pass, I want multiple users to interact with these buttons. Like if i press Smash, then a message will be sent saying UserA will SMASH and if UserB presses the Pass button a message will be sent saying UserB will PASS.

It works with normal views, but i dont want users to press any of the buttons twice. Like if i press smash, then all the buttons will get disabled for me so that i wont choose anything else.

I tried disabling the buttons in the button callbacks but that disabled the buttons for all users instead of the current user.

Any ideas?

rugged lantern
#

not possible

#

you cannot disable buttons for individual people. other people view the same state of buttons as you do

alpine helm
#

Hmm

rugged lantern
#

you can however add interaction checks and ignore interactions if someone choose something twice; but you cannot make it visually disabled for them after the first iteration

quiet tendon
#

Ill try to do some catching on start but yea

cerulean drum
#

uhh is there any event for unexpected loop close?

#

or should i override .start() ?

proud pagoda
#

How do I guarantee that I get the guild's icon asset and url?

#

Because sometimes guild.icon returns None

#

So if I fetch the guild with an API request will it always return an Asset?

#

Cuz rn Im getting the icon from the guild object passed into the on_guild_join event

marsh moth
#

How can I make slash commands work when joining a new server, because it didnt work when putting them in a function

proud pagoda
quiet tendon
#

My cog doesn't work anymore, i've narrowed it down because of the additional parameter i pass to the method, and im not sure why

It's not raising any errors, when i remove the parameter the cog loads fine.

https://i.imgur.com/Y8nXKee.png

cerulean drum
#

ehh whats your pycord version again?

quiet tendon
cerulean drum
quiet tendon
#

Extension 'cogs.eraffle.cogs_er' raised an error: ValidationError: Command names and options must be lowercase. Received "raffleId"

Well fuck 😄

proud pagoda
#

Enable the message content intent in the dev portal and in your code

proud pagoda
#

You're welcome. Make sure you archive this thread by typing /close now that the problem is solved @fervent cradle

rugged lantern
proud pagoda
#

I'm part of so many help threads I thought this was just another someone opened

fervent cradle
#

i want to make log and get user avatar, but i've got this error
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: 'EmbedProxy' object is not callable

how can i fix it?
code:

ac = discord.Embed(  
        description=f'Участнику {user} (<@{user.id}>) была выдана роль активного',
        color=discord.Color.from_rgb(155, 236, 82)

    )
    ac.add_field(name='Модератор', value=f'{member} (<@{member.id}>)')
    ac.thumbnail(url=user.avatar.url)
    ac.set_footer(icon_url=user.avatar.url, text=f'ID: {user.id}, {lib.nowtime}')
fervent cradle
fervent cradle
#

How can i get category id?

#
@bot.event
async def on_member_join(member: discord.Member):
    print(1)
    roleJoin = member.guild.get_role(863696255224643605)
    await member.add_roles(roleJoin)```

on_member_join doesn't work
graceful plover
#

Why this command isn't responding?[pycord 2.0]

import discord
from discord.ext import commands, tasks

client = commands.Bot(command_prefix="!")

@client.event
async def on_ready():
    print(f"Bot is Ready!")

@client.command()
async def ping(ctx):
    await ctx.send("Pong!")

client.run("abcd")
strange crypt
#

Hello, anyone know how we can have a dynamic select menu ? Because with an decorator I don't see how I can make dynamique options with paramater from the view class :/

cinder pilot
#

uh cogs is not working properly
It loads and on_message event works but commands don't work and it doesn't even show up in help command

graceful plover
#

no error
when i type "!ping", it wont return pong

cinder pilot
#

try

client = commands.Bot(command_prefix="!", intents=discord.intents.all())
#

Works for me

graceful plover
#

wdym?

strange crypt
#

an idea for my problem ? 🙂

cinder pilot
#

idk ¯\_(ツ)_/¯

obtuse juncoBOT
#
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
graceful plover
#

yeah i needintents.message_content = True

smoky forge
#

ah yes

#

sorry im half awake i didnt see the object 😭

graceful plover
cinder pilot
cinder pilot
graceful plover
strange crypt
#

Hello, anyone know how we can have a dynamic select menu ? Because with an decorator I don't see how I can make dynamique options with paramater from the view class :/
for example with button add
I can add categories in an embed
and I have a button modif, when clicked we have a select menue wich each categories
but to create a select menue, options are in a decorator and i don't know how to have a dynamic select menue like that

cinder pilot
#

Just enable the intents you need

graceful plover
#

no the message intent is locked

cinder pilot
#

I enabled all because easier to test

smoky forge
#

and then make them interact with each other

fervent cradle
#
@bot.event
async def on_member_join(member: discord.Member):
    print(1)
    roleJoin = member.guild.get_role(863696255224643605)
    await member.add_roles(roleJoin)

on_member_join doesn't work

smoky forge
#

bruh thats typing it doesn't do anything

#

?

#

not sure why that's to be questioned

#

¯\_(ツ)_/¯

#

fetch the user and then call the banner attribute

bleak goblet
#

discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TclError: unknown option "-url"

#
button = Button(text="downoload", url=f"{member.avatar}")
view = View()
await ctx.send(embed = embed, view=view)```
smoky forge
proud pagoda
fervent cradle
#

in on_ready inside a cog, the functions do not get called.

fervent cradle
fervent cradle
#

How can i send message

File "/Volumes/Danya disk/coding/Py-cord/HFD/main.py", line 69, in on_message
    await message.send('<@&866375824671375371> вышел новый обзор на бота!')
AttributeError: 'Message' object has no attribute 'send'```
smoky forge
proud pagoda
grim canopy
#

what does MessageCommanddoesHmmm

#

same as Command?

#

but I can't add it with Bot.add_command

mental maple
#

how to have a event listener on a cogs

#

i forgor

fervent cradle
#

fixed it anyways

cyan quail
#

The same goes for UserCommands when right-clicking a user

#

both of these are considered application commands (like slash commands); they work on the interaction system, unlike prefix commands.

storm geode
#

is it possible to have gifs inside the embed?
i tried doing
embed.set_image(url="")
but it doesnt work

rugged lantern
#

almost as though image implies an image

storm geode
#

woah really

#

im asking if theres a way to put gifs

cyan quail
storm geode
#

huh

#

its just like a picture for the first frame for me

cyan quail
#

what URL is it

storm geode
cyan quail
#

ehhh

rugged lantern
#

u can send normal gifs in messages, u need the .gif path though

storm geode
#

yeah i was thinking of just downloading it

rugged lantern
#

no u just right click and copy image location

#

and u should get the .gif path of whatever gif u click

storm geode
#

yeah but i need to download the gifs first

cyan quail
#

yeah the direct tenor URL works fine

rugged lantern
#

no u don't

cyan quail
#

idk what you're running into

storm geode
storm geode
cyan quail
#

right click the gif > copy image address

#

and it should end in .gif

smoky forge
#

you'll have to go in the site and download the gif as sd or hd gif

storm geode
#

yeah thats what im saying

#

before i get the location i first have to have the gif

#

no?

rugged lantern
#

that is just not true though

#

right click a gif and copy image address

#

that's all u do

storm geode
#

if i right click it on the site thats all i have

rugged lantern
#

copy image link

cyan quail
#

^

storm geode
cyan quail
#

yes

storm geode
#

ah

nice

#

lol

#

ima test again

#

oh nice now it works

#

thanks

smoky forge
#

you can't get someone's about me cuz its a discord limitation

#

you can get someone's status, you just have to have the statuses intent i think

crimson sundial
#

Is it possible to disable the buttons/components of a message using its ID?

smoky forge
#

get a member object and access the activity or activities method

#

you need the presences intent

cyan quail
# crimson sundial Is it possible to disable the buttons/components of a message using its ID?

a few ways;

  • use await channel.fetch_message(id) to make an API call to grab the message object you want to edit, raises an error if it doesn't exist.
  • use client.get_message(id) to attempt to grab the message you want to edit from the bot's internal cache, returns None if it isn't cached.
  • use channel.get_partial_message(id) to essentially create a dummy message object to edit over. This will not raise an error or return None on its own, but if you attempt to act on the message and it doesn't exist then it will raise the relevant error.
crimson sundial
cyan quail
#

first use view.disable_all_items(), then when editing the message just pass in the view again

#

if you don't have a view object and instead want to get it from an existing message, then you must have the original message object (no partial) and use discord.View.from_message(message)

onyx yacht
#

Hello, Cogs Commands not working

#

Why

rugged lantern
#

how are we supposed to know

wicked helm
#

Do I need to include the ID of the server I want commands to appear in?

Or if left empty should they appear in all servers the bot is in?

vital blade
#

how can i check if an user is timed out

smoky forge
#

if it's None, the member is not timed out

vital blade
#

ty

smoky forge
vital blade
smoky forge
#

Yes

vital blade
#

okay

wicked helm
smoky forge
#

Like an hour methinks

wicked helm
# smoky forge Like an hour methinks

Ahhh - ok.

I was a bit confused as I would create them before and they would update instantly. (When I was hosting the bot locally)

I’ll try again when I get back and wait ^^

smoky forge
#

if you need to test your commands use the bot.debug_guilds attribute

neon raven
#

How can I get the Open DM channels of my bot?

cyan quail
fervent cradle
#

So when I ran my bot in vscode I got this error

smoky forge
#

i think thats not a pycord issue

fervent cradle
#

Oh

#

Well I'm just trying to run my bot

#

and I also get this

rugged lantern
#

and relevant code is all that is in your picture?

fervent cradle
#

wdym

#

My bot wont run

rugged lantern
#

that is not enough info to estimate a solution- provide some relevant code to what you're trying to run

fervent cradle
rugged lantern
fervent cradle
#
import discord
from discord.ext import commands
import os
bot = commands.Bot(command_prefix="c.", intents=discord.Intents.all())

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

@bot.event
async def on_ready():
    print(f"We have logged in as {bot.user}")

bot.run(os.environ["TOKEN"])```
#

I run main.py because it has bot.run in it

cyan quail
#

you have some weird network issues or rules that's preventing connections, i recommend you look into this more yourself because there are so many different causes and factors that we probably can't account for

signal stratus
#

How do I send an error message if the bot has no permissions to a /command?

#

And how can I then also display which permissions are needed?

smoky forge
#

on_application_command_error event

wicked helm
smoky forge
#

did you put the ids in a list?

wicked helm
#

I did yes.. well as I only have one id it was debug_guilds=[id]

wicked helm
# smoky forge did you put the ids in a list?

For what I am doing... (attempting to subclass the bot)

main.py:

Bot: BrvnsBot = BrvnsBot(debug_guilds = [guild_id])
Bot.run(token)

brvns_bot_api.py:

class BrvnsBot(discord.Bot):
    """
    BRVNS Discord Bot
    """
    brvns_logic = BrvnsLogic()


    async def on_ready(self):
        """
        Bot Ready
        """
        print(f"The Bot, {self.user.name}, {self.user.id} is ready and online!")
        print(f"Bot Guilds: {self.guilds}")
        print(f"Debug Guilds: {self.debug_guilds}")

    @discord.slash_command(name = "sign-up", description = "Display the link to the RSI Org Page.")
    async def sign_up(self, ctx):
        """
        Sign Up string slash command
        """
        author_name: str = ctx.author.name
        await ctx.respond(self.brvns_logic.signup_string(author_name))

    @discord.slash_command(name = "ping", description = "Return the bot latency.")
    async def ping(self, ctx):
        """
        Send bot ping
        """
        await ctx.respond(f"Pong! Latency is {self.user.latency}")

For debugging purposes I am printing out the guilds the bot is in, and the debug guilds.

My go to assumption is that I am using the @discord.slash_command incorrectly.. but using @Bot.slash_command or @slash_command gives me errors.

The on ready event works, which is what makes me think I made my commands wrong.

smoky forge
#

try passing the debug guilds inside the classes super().__init__()

fervent cradle
#

How do I make my ban command to where when I ban someone it sends them an invite to the appeal server

signal stratus
#

It prints only the error but not the second one i.e. the error is not an instance of what else is it?

smoky forge
#

it should be discord.Forbidden then

storm geode
signal stratus
storm geode
#

like if the bot trys to kick someone but doesnt have kick perms

#

for permission missing i did
commands.CheckFailure

signal stratus
#

And how can I then display which permission is missing?

fervent cradle
wicked helm
fervent cradle
wicked helm
#

The issue is - it’s not working 😂 so I assume not

fervent cradle
#

Oh

fervent cradle
signal stratus
wicked helm
#

Yeah I will😂

undone falcon
#

Once you do a ctx.respond can you do a fallow up with a other response ?

iron mesa
wicked helm
iron mesa
#

Any way to inject values into a decorator? Trying to create view that are customisable and need a way to change for example max_answers in Select . If not, what would be sensible approach to do it

fervent cradle
wicked helm
#

Solved it, I was editing my poetry packages and got rid of py-cord. Added that back now

fervent cradle
#

Hey can someone help me with something?

waxen whale
#

#help-rules §5

full basin
#

Can't read your mind buddy

fervent cradle
#

Oh

#

Right

#

Let me show the problem

#
async def create_strike(user):
    with open("strikes.json", "r") as f:
        users = json.load(f)

    if str(user.id) in users:
        return False
    else:
        users[str(user.id)] = {}
        users[str(user.id)]["strike"] = 0

async def add_strike(user,admin,reason):
    with open("strikes.json", "r") as f:
        users = json.load(f)

    if str(user.id) in users:
        users[str(user.id)] = {}
        users[str(user.id)]["strike"] += 1``` on the last line ``users[str(user.id)]["strike"] += 1`` it raises a keyerror about ``"strike"``
round rivet
#

well what do you want it to do

#

you removed the strike key and are now trying to increment it

fervent cradle
#

im trying to make it add a extra strike

round rivet
#

and because it doesn't exist it doesn't work

fervent cradle
#

but when i add it back in it resets back to 0

silver moat
#

?tag nojson

obtuse juncoBOT
#

Why you should not use json files for storing data
Using json files on a smaller scale is fine, however it is would be very beneficial to switch to a real database management system;

  • JSON is a data format, not a database.
  • It is easily corrupted as it does not come with any data integrity checks when writing to the file.
  • It is not good at defining or utilizing relationships, making it very hard to store relational data.
  • When the JSON file becomes too large, you will run into performance issues since your program has to read the entire file into memory every time you want to query the data.
  • It does not include any security features that you may get when using a database management system.
fervent cradle
#

this is my error I get Traceback (most recent call last): File "C:\Users\fi\OneDrive\Desktop\Busta Bot\main.py", line 8, in <module> bot.load_extension(f"cogs.{file[:-3]}") File "C:\Users\fi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\cog.py", line 787, in load_extension self._load_from_module_spec(spec, name) File "C:\Users\fi\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\cog.py", line 718, in _load_from_module_spec raise errors.ExtensionFailed(key, e) from e discord.errors.ExtensionFailed: Extension 'cogs.fun' raised an error: AttributeError: 'function' object has no attribute 'Cog'

fervent cradle
fervent cradle
silver moat
#

I meant for the loading the cogs part

fervent cradle
fervent cradle
# silver moat I meant for the loading the cogs part
import discord
from discord.ext import commands
import os
bot = commands.Bot(command_prefix="c.", intents=discord.Intents.all())

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


@bot.event
async def on_ready():
    print(f"We have logged in as {bot.user}")

bot.run(os.environ["TOKEN"])

silver moat
copper dew
#

^

fervent cradle
silver moat
#

I mean get rid of the for loop altogether

fervent cradle
#

@silver moat now im getting an error

wicked helm
#

remove the if as well.. just use

bot.load_extension("cogs", recursive=True)

wicked helm
wicked helm
#

So if you put it above where your bot.run is, it should work

fervent cradle
silver moat
fervent cradle
#

I did

fervent cradle
# wicked helm Yah, mine looks like:
  File "C:\Users\fir\OneDrive\Desktop\Busta Bot\main.py", line 7, in <module>
    bot.load_extension("cogs", recursive=True)
TypeError: CogMixin.load_extension() got an unexpected keyword argument 'recursive'```
smoky forge
#

whats your pycord version

fervent cradle
#

2.0.0.0

wicked helm
wicked helm
#

Might be worth checking if your cogs are set up correctly?

fervent cradle
shrewd dome
#

I assume you mean 2.0.0

near hollow
#
  File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 715, in run
    return future.result()
  File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 694, in runner
    await self.start(*args, **kwargs)
  File "/home/container/.local/lib/python3.10/site-packages/discord/client.py", line 658, in start
    await self.connect(reconnect=reconnect)
  File "/home/container/.local/lib/python3.10/site-packages/discord/shard.py", line 462, in connect
    raise item.error
  File "/home/container/.local/lib/python3.10/site-packages/discord/shard.py", line 185, in worker
    await self.ws.poll_event()
  File "/home/container/.local/lib/python3.10/site-packages/discord/gateway.py", line 589, in poll_event
    await self.received_message(msg.data)
  File "/home/container/.local/lib/python3.10/site-packages/discord/gateway.py", line 539, in received_message
    func(data)
  File "/home/container/.local/lib/python3.10/site-packages/discord/state.py", line 635, in parse_auto_moderation_action_execution
    event = AutoModActionExecutionEvent(self, data)
  File "/home/container/.local/lib/python3.10/site-packages/discord/raw_models.py", line 462, in __init__
    self.content: str = data["content"]
KeyError: 'content'
ERROR:asyncio:Unclosed client session```

Any time the bot errors it spits this out and restarts. Any way to resolve it?
fervent cradle
north tartan
#

code

near hollow
#

Why not just use timestamp=datetime.utcnow()

smoky forge
near hollow
rugged lantern
#

read the rules

wicked helm
# fervent cradle May I see one of you're cogs?
"""
General Slash Cogs
"""
from discord.ext import commands

class SlashGeneral(commands.Cog):
    """
    General Slash Commands
    """

    def __init__(self, bot):
        self.bot: commands.Bot = bot
        print("Init Slash Command Cog.")

    @commands.slash_command(name = "ping", description = "Return the bot latency.")
    async def ping(self, ctx):
        """
        Send bot ping
        """
        await ctx.respond(f"Pong! Latency is {round(self.bot.latency * 100, 2)} ms")
        print("Sent Ping")

def setup(bot):
    """
    Add cog to bot
    """
    bot.add_cog(SlashGeneral(bot))
rugged lantern
#

no reason to have self.bot: commands.Bot = bot

wicked helm
#

I mean yes - but I like it that way

rugged lantern
#

for what purpose do you have it as opposed to just self.bot = bot

wicked helm
#

I'm wanting to strongly type variables.. That's about it

rugged lantern
#

annotations doesn't define the variable type though

fervent cradle
#
@bot.event
async def on_message_delete(message):
    log = bot.get_channel(866224389787222036)
    member = message.author
    ac = discord.Embed(  
    description=f'Сообщение удалено',
    color=discord.Color.from_rgb(255,109,150)
    )
    ac.add_field(name='Автор', value=f'**{member}** (<@{member.id}>)', inline=True)
    ac.add_field(name='Сообщение', value=f'> {message.content}', inline=True)
    ac.set_footer(icon_url=member.avatar.url, text=f'ID: {member.id}')
    await log.send(embed=ac)```
message.content doesn't show content
signal stratus
#

How can i test if bot has permissions?

signal stratus
proud pagoda
signal stratus
torpid wharf
#

It's discord.ButtonStyle

marsh moth
#

How to make slash commands automatically work when the bot joins a new server, because for some reason it doesnt work in a function

graceful plover
marsh moth
#

it is

graceful plover
#

do you put that new server in your debug_guilds list?

marsh moth
#

debug_guilds?

mint sphinx
#

Guys I'm making a welcome system so i have some doubt

I maked a dictionary:-

variables = { "[user]": member.mention, "[userName]": member.name, "[guild]": member.guild.name, "[avatar]": member.display_avatar.url}

and in on message event I'm sending a message that

await channel.send(message_from_guild_db)

So my question is that if guild owner/admin set the welcome message Welcome [user], to [guild] so how to replace both the variables? If anyone can help please and yes i know about .replace but i have more than 10 variables and also i want to replace the variables on embed so is there a way to do it with this dictionary method?

marsh moth
#

@graceful plover if something is added to the guild_ids list will it automatically update?

#

nvm it doesnt

#

so how can I work around that?

graceful plover
#

you can just remove debug_guilds from client
client = discord.AutoShardedBot(intents=intents)
Remember global slash commands can take up to an hour to register

marsh moth
#

I dont want it to be a global slash command

#

thats the thing

#

I want it to be enabled once the owner of server says so, so I was gonna use a function but that doesnt work

#

So how do I have slash commands work if the bot joins a server after running the script

graceful plover
marsh moth
#

what about bot.register_commands?

graceful plover
#

idk

#

try and see DaniSalute

storm geode
#

i have a requestion about ratelimits.

if i have a command like count which does for n in range(20): await ctx.send(n)
and the bot gets ratelimited. will it pause the command until the ratelimit is over and then continue outputting numbers?

marsh moth
#

ty

graceful plover
#

GG

proud pagoda
#

For some reason when I added a new slash command, its not loading on my bot even though the other two are loading

#

nvm found the issue

#

I'm an idiot, i was migrating from prefixed to slash commands, and i forgot to change it from @commands.command to @discord.slash_command

wheat summit
#

Quick question, is anyone having issues adding Option parameters to a slash command?

#

My slash commands are disappearing as soon as I add an option parameter in their definition

grim canopy
#
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In 1: Application command names must be unique

I kept getting this error on message_command

#
@bot.message_command(name="Testing Message Command", guild_ids=[995976950541729793])
async def testing(ctx: discord.ApplicationContext, message:discord.Message):
    await ctx.respond("Test")
#

code

fervent cradle
#
@bot.event
async def on_message_delete(message):
    log = bot.get_channel(866224389787222036)
    member = message.author
    ac = discord.Embed(  
    description=f'Сообщение удалено',
    color=discord.Color.from_rgb(255,109,150)
    )
    ac.add_field(name='Автор', value=f'**{member}** (<@{member.id}>)', inline=True)
    ac.add_field(name='Сообщение', value=f'> {message.content}', inline=True)
    ac.set_footer(icon_url=member.avatar.url, text=f'ID: {member.id}')
    await log.send(embed=ac)```
message.content doesn't show content
fervent cradle
#

This thing for

hello

marsh moth
#

How can I check which application commands are in a guild?

cyan quail
marsh moth
cyan quail
#

any slash command that doesn't have guild_ids set; it's usable in all guilds and DMs (unless guild_only is set)

marsh moth
#

why does it take an hour for it to update if global, is it registered on dicords servers or something?

cyan quail
cyan quail
marsh moth
#

ah, so if its no global its stored on your computer?

cyan quail
#

no, all application commands are stored on discord

marsh moth
#

oh then what is the internal list of commands mean

cyan quail
#

maybe i was unclear; the bot will always have all commands stored. With application commands, their basic data (IDs, name, description etc.) is stored on discord. When someone runs a command, the bot still handles all the command logic.

marsh moth
#

Ohhhhhh ok ty

cyan quail
#

all good

cyan quail
marsh moth
#

I figured it out, thankyou

signal stratus
#

How can I check if the bot has certain permissions via if query?

fervent cradle
#

how do i make it so that when i click one button in that class, it disables ALL the buttons in that class?

dire island
#

im having a problem with on_member_join i doesn't detect the new member when it joins

@bot.event
async def on_member_join(member):
    print(f"{member} has joined the server!")
#

in another bot works fine and i copied the code but doesn't work

torpid wharf
dire island
torpid wharf
#

intents

dire island
#

oh

#

forgot lmao

torpid wharf
dire island
fervent cradle
real compass
#

hi

#

is there any way to fix this issue

#

should i use development version ..?

grizzled sentinel
#

your data dictionary has no key "content"

real compass
real compass
cyan quail
#

what version are you using?

real compass
#

i guess its something issue with the AutoMod

real compass
waxen whale
#

This is an bug from our side

cyan quail
#

yeah looks like lib, should probably use get instead

#

though, what's the full traceback?

waxen whale
#

content is not represented if the message content intent is missing

real compass
cyan quail
#

ahh

waxen whale
#

it was a breaking change we haven't implemented yet

real compass
waxen whale
real compass
#

when will this be fixed?

waxen whale
#

@grizzled sentinel could you pr a fix?

grizzled sentinel
cyan quail
#

maybe just data.get("content", None)?

waxen whale
#

^

grizzled sentinel
#

forgot about that.

cyan quail
#

is the rest safe

     def __init__(self, state: ConnectionState, data: AutoModActionExecution) -> None:
        self.action: AutoModAction = AutoModAction.from_dict(data["action"])
        self.rule_id: int = int(data["rule_id"])
        self.guild_id: int = int(data["guild_id"])
        self.guild: Optional[Guild] = state._get_guild(self.guild_id)
        self.user_id: int = int(data["user_id"])
        self.content: str = data["content"]
        self.matched_keyword: str = data["matched_keyword"]
        self.matched_content: str = data["matched_content"]```
waxen whale
#

matched_content can be null

cyan quail
#

isee

waxen whale
#

In API v10, the MESSAGE_CONTENT (1 << 15) intent is now required to receive non-empty values for the content and matched_content fields

real compass
#

is there an ETA on this fix?

cyan quail
#

uhh can you view package files on heroku? you could just apply the fix yourself

real compass
#

hmmmk leme fork it and ill fix...

cyan quail
grizzled sentinel
cyan quail
#

oh fair enough then

cyan quail
errant craneBOT
real compass
cyan quail
#

that's the pr you want

real compass
#

nice bot...

waxen whale
#

That should do it

real compass
hallow shuttle
#

how would i use the Voice Receive API to passively listen to a channel for voice commands?

#

I see the existing sample code is like manually listening until the user enters the stop command then shows like what users were talking and generated what files

#

I tried like a loop with asyncio sleeps but it causes like "already writing to file" errors and starts killing the processes

fervent cradle
#

hello!!!

#

my cog listener is farting errors.

#

yes im new to py and pycord

#

whenever i add @commands.Cog.listener() to my cog it farts a error

#

Extension 'cogs.Information' raised an error: IndentationError: unexpected indent (Information.py, line 32)

#

yea line 32 is @commands.Cog.listener()

rugged lantern
#

it tells u the error

#

indentation

fervent cradle
#

exactly

#

but why.

#

anyways i fixed that

#

and now Extension 'cogs.Information' raised an error: IndentationError: unexpected unindent (Information.py, line 34)

#

a unindent 💀 why python.

rugged lantern
#

shows the code then

fervent cradle
#

line 34 is

def setup(bot):
    bot.add_cog(InfoCog(bot))
#

the def part

rugged lantern
#

so why did u meantion @commands.Cog...

fervent cradle
#

for my commands to load ofc

signal stratus
#

I have made @command.only_guild() for one command. And I don't want to make a separate error for each command with name.error. So I used on_command_error. It is registered and works. So that with the invalid command. only the problem is that the error does not react there in on_command_error. no idea how I should say that haha but I want in any case that on_command_error reacts when there this error command or is there for it another event?

fervent cradle
#

bird

rugged lantern
#

you're already capturing all errors

fervent cradle
#

LMAO

smoky forge
rugged lantern
#

you're just using 'raise' and therefore see it as an error when it occurs

fervent cradle
rugged lantern
#

@signal stratus

fervent cradle
#
    @commands.command()
    async def ping(self, ctx, bot): 
        await ctx.send(f'Hello, my name is {bot.user} you can use me by using slash commands. Type `/help` to see all of my commands!')
        ```
#

pretty sure this is correct

smoky forge
#

you shouldn't have to put bot as an argument

fervent cradle
#

unless im wrong *

signal stratus
# rugged lantern <@455002904210702359>

But its dont answer with ctx.respond()
And when I removeraise it is still displayed
I meant that the event does not react to the error, even though it is registered.I meant that the event does not react to the error, even though it is registered.

fervent cradle
smoky forge
#

pass the bot into the cog object and call the bot with self.bot

#

again, ReadTheDocs

rugged lantern
fervent cradle
signal stratus
fervent cradle
#

self.bot = bot

#

i read doc ok

smoky forge
#

if you're new i recommend you read the pycord guide

#

?tag guide

obtuse juncoBOT
signal stratus
fervent cradle
#

the bot doesnt reply to ping

    @commands.command()
    async def ping(self, ctx): 
        await ctx.send(f'Hello, my name is {ctx.author} you can use me by using slash commands. Type `/help` to see all of my commands!') #ignore ctx.author
        ```
#

this is correct right

rugged lantern
#

do u have it in ur main?

fervent cradle
#

no

#

, a cog

rugged lantern
#

there's the problem then

fervent cradle
#

w h a t

#

uhh

smoky forge
#

not sure how thats a problem

#

since the syntax seems alright

rugged lantern
#

maybe the indent just looks weird on mobile then

smoky forge
#

is the cog being loaded in the main file?

fervent cradle
#

slash commands in the cogs works

#

the message cmd isnt working

#

Trying to do some stuff with images. How can I get the user image? not the url? Currently: asset = user.avatar_url_as(size = 128)

smoky forge
#

did you specify a command prefix?

#

are you using commands.Bot for your bot?

fervent cradle
#

well yea

fervent cradle
smoky forge
#

theres your problem

fervent cradle
#

but i am using commands.Bot

#

💀

#

i need it without a prefix due..

rugged lantern
#

???

#

command btw?

fervent cradle
#

ye

silver moat
smoky forge
#

commands.Bot is for prefixed commands

#

and that

fervent cradle
silver moat
#

in the code and on dev portal?

fervent cradle
#
intents = discord.Intents.default()
intents.members = True
intents.message_content = True```
fervent cradle
signal stratus
#

Why doesn't that work?
Listener is registered

fervent cradle
signal stratus
silver moat
fervent cradle
rugged lantern
#

then use on_message instead

#

as it is not a command

fervent cradle
#

OHH

#

RIGHT THANKS

#

I TOTALLY FORGOT THAT IT EXISTS

signal stratus
full basin
#

No

signal stratus
#

If no, is there also an event for slash command errors?

full basin
#

on_application_command_error

signal stratus
#

Thx

full basin
signal stratus
#

Had peeked, must have read over it 🤷

hallow shuttle
#
async def finished_callback(sink, channel: discord.TextChannel, *args):
    recorded_users = [f"<@{user_id}>" for user_id, audio in sink.audio_data.items()]
    await sink.vc.disconnect()
    files = [
        discord.File(audio.file, f"{user_id}.{sink.encoding}")
        for user_id, audio in sink.audio_data.items()
    ]
    await channel.send(
        f"Finished! Recorded audio for {', '.join(recorded_users)}.", files=files
    )

I see this code from the voice receive API - how would I get the actual wav file from this? It seems like it isn't like actually saved on the file system, and the audio content is actually just binary data and not formatted

#
ValueError: Audio file could not be read as PCM WAV, AIFF/AIFF-C, or Native FLAC; check if file is corrupted or in another format
fervent cradle
#

How can i make button works one time for one user

obtuse juncoBOT
dreamy raft
#

Is there a way to check a message's reply

robust raptor
#

If I have my bot send a message using webhook.send() then use get_message() on that message, will I be able to edit it?

dreamy raft
#

you're a different author than the webhook

robust raptor
# dreamy raft no

So if I want to be able to edit the messages I will have to have the webhook send method return the message object and then somehow store the objects with something like pickle?

dreamy raft
#

first, fetch the webhook, then you use await webhook.edit_message("message id", *args)

wicked helm
#

Just to check, the method def setup in cogs that is outside the class. Is that SUPPOSED to be outside the class, or can it be put in a class somewhere?

I thought it had to be outside because that's just how pycord rolls

cyan quail
wicked helm
#

Gotcha! Thanks ^^

hallow shuttle
#

Who wrote the pycord voice client?

cyan quail
hallow shuttle
#

does he do open discussion or office hours or anything? i'm looking to get the voice client to just passively listen to a voice channel and pass through that audio data to a voice recognizer from say the Speech Recognition library

#

i mean surely discord already does this on the backend otherwise i wouldn't get advertising about things i talk about in voice

cyan quail
#

Hmmm he started work on dpy v2 so im not sure if he'd be available to, well, review whatever iterations the pycord devs have made over the client. You could try making a thread here for someone to assist you with that, though it'll ultimately depend on if anyone's familiar enough with using it

hallow shuttle
#

yeah i have low confidence in the latter thing there based on my messages and replies so far

cyan quail
#

looking through the history, i think mainly @\VincentRPS wrote that

hallow shuttle
#

looks roughly the same

cyan quail
#

yeah, was primarily just changing some references for WaveSink

hallow shuttle
#
    for _, audio in sink.audio_data.items():
        # wavio.write('recording.wav', audio.file, rate=48000, sampwidth=2)
        with open('recording.wav', mode='wb') as f:
            audio.file.seek(0)
            f.write(audio.file.read())

anyone know why this wouldn't work? there's no frame data in the resulting wav file

#

i can play the file on the file system but if i try to load it in frame data is just b''

woeful spindle
#

how do i get all command names from a cog?

cyan quail
cyan quail
#

if you want to include subcommands, you should use cog.walk_commands() instead... though im not sure if this includes application subcommands

cyan quail
#

so if i had to guess he's probably one of the most experienced here on the subject

dreamy raft
runic spruce
#

how i can install wavelink

woeful spindle
#
class MyView(discord.ui.View):
    @discord.ui.select( # the decorator that lets you specify the properties of the select menu
        placeholder = "idk what this is", # the placeholder text that will be displayed if nothing is selected
        min_values = 1, # the minimum number of values that must be selected by the users
        max_values = 1, # the maxmimum number of values that can be selected by the users
        options = [ # the list of options from which users can choose, a required field
            discord.SelectOption(
                label="Owner",
                description="placeholder"
            ),
            discord.SelectOption(
                label="Moderation",
                description="placeholder"
            ),
            discord.SelectOption(
                label="Fun",
                description="placeholder"
            )
        ]
    )
    async def select_callback(self, select, interaction): # the function called when the user is done selecting options
        await interaction.response.send_message("test")

Ok so I have this but how I make it author only when clicking interactions?

rugged lantern
#

author only when clicking what does this mean

woeful spindle
#

like when u press one of the select menu options, only the author can

rugged lantern
#

by adding async def interaction_check(self, interaction):

rugged lantern
#
class MyView(discord.ui.View):
    def __init__(self, author=None):
        self.author = author

    @discord.ui.select( # the decorator that lets you specify the properties of the select menu
        placeholder = "idk what this is", # the placeholder text that will be displayed if nothing is selected
        min_values = 1, # the minimum number of values that must be selected by the users
        max_values = 1, # the maxmimum number of values that can be selected by the users
        options = [ # the list of options from which users can choose, a required field
            discord.SelectOption(
                label="Owner",
                description="placeholder"
            ),
            discord.SelectOption(
                label="Moderation",
                description="placeholder"
            ),
            discord.SelectOption(
                label="Fun",
                description="placeholder"
            )
        ]
    )
    async def select_callback(self, select, interaction): # the function called when the user is done selecting options
        await interaction.response.send_message("test")

    async def interaction_check(self, interaction) -> bool:
        if interaction.user.id != self.author:
          return False
        else:
          return True
#

should work

#

then to send it

#
view = MyView()
view.author = ctx.author.id
await ctx.send(view=view)
runic spruce
#

where i get nodes for wavelink

woeful spindle
# rugged lantern should work
Ignoring exception in on_command_error
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 181, in wrapped
    ret = await coro(*args, **kwargs)
  File "/home/container/main.py", line 62, in help
    await ctx.send("testssssssssssss",view=MyView())
  File "/home/container/.local/lib/python3.9/site-packages/discord/abc.py", line 1469, in send
    components = view.to_components()
  File "/home/container/.local/lib/python3.9/site-packages/discord/ui/view.py", line 209, in to_components
    children = sorted(self.children, key=key)
AttributeError: 'MyView' object has no attribute 'children'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.9/site-packages/discord/client.py", line 382, in _run_event
    await coro(*args, **kwargs)
  File "/home/container/cogs/events.py", line 45, in on_command_error
    raise error
  File "/home/container/.local/lib/python3.9/site-packages/discord/ext/commands/bot.py", line 344, in invoke
    await ctx.command.invoke(ctx)
  File "/home/container/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 927, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/home/container/.local/lib/python3.9/site-packages/discord/ext/commands/core.py", line 190, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'MyView' object has no attribute 'children'
#

here’s my current code:

#
class MyView(discord.ui.View):
    def __init__(self, author=None):
        self.author = author

    @discord.ui.select( # the decorator that lets you specify the properties of the select menu
        placeholder = "idk what this is", # the placeholder text that will be displayed if nothing is selected
        min_values = 1, # the minimum number of values that must be selected by the users
        max_values = 1, # the maxmimum number of values that can be selected by the users
        options = [ # the list of options from which users can choose, a required field
            discord.SelectOption(
                label="Owner",
                description="placeholder"
            ),
            discord.SelectOption(
                label="Moderation",
                description="placeholder"
            ),
            discord.SelectOption(
                label="Fun",
                description="placeholder"
            )
        ]
    )
    async def select_callback(self, select, interaction): # the function called when the user is done selecting options
        await interaction.response.send_message("test")

    async def interaction_check(self, interaction) -> bool:
        if interaction.user.id != self.author:
            await ctx.send(f"<@{interaction.user.id}>, this command was not executed by you.")
        else:
            view = MyView()
            view.author = ctx.author.id
            await ctx.send(view=view)
rugged lantern
#

i forgot

woeful spindle
#
@bot.command()
async def help(ctx):
    await ctx.send("testssssssssssss",view=MyView())
rugged lantern
#
class MyView(discord.ui.View):
    def __init__(self, author=None):
        super().__init__()
        self.author = author

    @discord.ui.select( # the decorator that lets you specify the properties of the select menu
        placeholder = "idk what this is", # the placeholder text that will be displayed if nothing is selected
        min_values = 1, # the minimum number of values that must be selected by the users
        max_values = 1, # the maxmimum number of values that can be selected by the users
        options = [ # the list of options from which users can choose, a required field
            discord.SelectOption(
                label="Owner",
                description="placeholder"
            ),
            discord.SelectOption(
                label="Moderation",
                description="placeholder"
            ),
            discord.SelectOption(
                label="Fun",
                description="placeholder"
            )
        ]
    )
    async def select_callback(self, select, interaction): # the function called when the user is done selecting options
        await interaction.response.send_message("test")

    async def interaction_check(self, interaction) -> bool:
        if interaction.user.id != self.author:
            await ctx.send(f"<@{interaction.user.id}>, this command was not executed by you.")
            return False
        else:
            return True
#

try that but when you do the

#

command, do this instead:

@bot.command()
async def help(ctx):
    await ctx.send("testssssssssssss",view=MyView(author = ctx.author.id))
woeful spindle
#

oh okay

#

so for my author only err message where it says "this command was not executed by you", where I used await ctx.send, it said ctx is not defined

#

so I added ctx to def interaction_check(ctx and the other stuff) but now it says interaction_check() is missing ctx argument

#

so I’m confused

rugged lantern
#

show your code

woeful spindle
#
Ignoring exception in view <MyView timeout=180.0 children=1> for item <Select placeholder='idk what this is' min_values=1 max_values=1 options=[<SelectOption label='Owner' value='Owner' description='placeholder' emoji=None default=False>, <SelectOption label='Moderation' value='Moderation' description='placeholder' emoji=None default=False>, <SelectOption label='Fun' value='Fun' description='placeholder' emoji=None default=False>] disabled=False>:
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.9/site-packages/discord/ui/view.py", line 367, in _scheduled_task
    allow = await self.interaction_check(interaction)
TypeError: interaction_check() missing 1 required positional argument: 'ctx'
#

that’s the err

#

one sec let me get the code

#
class MyView(discord.ui.View):
    def __init__(self, author=None):
        super().__init__()
        self.author = author

    @discord.ui.select( # the decorator that lets you specify the properties of the select menu
        placeholder = "idk what this is", # the placeholder text that will be displayed if nothing is selected
        min_values = 1, # the minimum number of values that must be selected by the users
        max_values = 1, # the maxmimum number of values that can be selected by the users
        options = [ # the list of options from which users can choose, a required field
            discord.SelectOption(
                label="Owner",
                description="placeholder"
            ),
            discord.SelectOption(
                label="Moderation",
                description="placeholder"
            ),
            discord.SelectOption(
                label="Fun",
                description="placeholder"
            )
        ]
    )
    async def select_callback(self, select, interaction): # the function called when the user is done selecting options
        await interaction.response.send_message("test")

    async def interaction_check(self, interaction, ctx) -> bool:
        if interaction.user.id != self.author:
            await ctx.send(f"<@{interaction.user.id}>, this command was not executed by you.")
            return False
        else:
            return True
rugged lantern
#

you don't put ctx in interaction check

woeful spindle
#

but the it says ctx isn’t defined

rugged lantern
#

what do you use to prompt the command

woeful spindle
#

!help

rugged lantern
#

code

woeful spindle
#
@bot.command()
async def help(ctx):
    await ctx.send("testssssssssssss",view=MyView(author = ctx.author.id))
rugged lantern
#

oh

#

you're trying to ctx.send in an interaction

#

use await interaction.response.send_message instead

woeful spindle
#

oh okay

round rivet
rugged lantern
round rivet
#

that's not how that works

#

when you click a button interaction_check is called with that interaction

#

nothing else

#

(other than self)

woeful spindle
round rivet
#

remove the ctx parameter

woeful spindle
#

oh yeah

#

whoops

#

it works, ty you both very much :))

#

how do i get the guild id using message object? sorry this is completely different to my other issue but I just got an error for one of my cmds lol

#

message.guild.id returns NoneType

rugged lantern
#

depends on where you put it

woeful spindle
#

it’s an if condition on my @bot.listen(on_message) event

rugged lantern
round rivet
#

interaction_check does not take a ctx parameter

rugged lantern
#
class MyView(discord.ui.View):
    def __init__(self, author=None, ctx=None):
        super().__init__()
        self.author = author
        self.ctx = ctx

    @discord.ui.select( # the decorator that lets you specify the properties of the select menu
        placeholder = "idk what this is", # the placeholder text that will be displayed if nothing is selected
        min_values = 1, # the minimum number of values that must be selected by the users
        max_values = 1, # the maxmimum number of values that can be selected by the users
        options = [ # the list of options from which users can choose, a required field
            discord.SelectOption(
                label="Owner",
                description="placeholder"
            ),
            discord.SelectOption(
                label="Moderation",
                description="placeholder"
            ),
            discord.SelectOption(
                label="Fun",
                description="placeholder"
            )
        ]
    )

    async def select_callback(self, select, interaction): # the function called when the user is done selecting options
        await interaction.response.defer()
        await self.ctx.send("OK")

    async def interaction_check(self, interaction) -> bool:
        if interaction.user.id != self.author:
            await self.ctx.send(f"<@{interaction.user.id}>, this command was not executed by you.")
            return False
        else:
            return True
...

@commands.command()
async def example(self, ctx):
    msg = MyView(author = ctx.author.id, ctx=ctx)
    await ctx.send(view=msg)
#

that would make it work with ctx.

woeful spindle
#

how do I return the guild id using message object

#

message.guild_id?

rugged lantern
woeful spindle
#

I’m using

elif message.guild.id == my guild is is here:
                 # do stuff
#

and it returns this err:

AttributeError: 'NoneType' object has no attribute 'id'

rugged lantern
#

and what's the entire code of your on_message

woeful spindle
#

I’m using a listen event

spiral sail
#

Got a problem with my bridge command not registering. Hope someone can help.

rugged lantern
spiral sail
#

But for some odd reason it looks like it isn't registering at all.

proud pagoda
woeful spindle
#

I’ll be back in a few mins 😂

spiral sail
proud pagoda
spiral sail
#

Both of them don't seem to work. Just says "not found"

#

Is there ways to pick up errors of it not registering at startup?

proud pagoda
spiral sail
#

Because no errors spit out in the connsole

proud pagoda
spiral sail
#

There's too many things to log

proud pagoda
#

I'm not rlly familiar with bridge commands so I don't think I'll be of much help

proud pagoda
spiral sail
#

Then what do you suggest I do?

proud pagoda
#

I'm not too sure tbh im assuming the issue is probably with the way you declared the command

proud pagoda
spiral sail
proud pagoda
#

By the way do you have the message content intent enabled?

#

And have you set the debug_guilds?

spiral sail
#

Nothing happened, did not make a difference.

spiral sail
proud pagoda
spiral sail
#

Where?

proud pagoda
#

In the bot constructor

#

Bot = bridge.bot(debug_guilds=[...])

#

And supply the guild id

spiral sail
#

Alrighty, just set and restarted

proud pagoda
#

What version of pycord are u on btw?

spiral sail
#

2.0.0

#

(Latest)

proud pagoda
#

Ok

proud pagoda
spiral sail
#

Will do now

spiral sail
#

Still same thing

graceful nebula
#

Is any commands that use auto complete limited to desktop only?

spiral sail
#

dies

silver moat
dire spadeBOT
spiral sail
#

F

silver moat
silver moat
#

I'm dumb

#

classes shouldn't be plural

#

:\

woeful spindle
#

How do I make it so in my drop-down menu, if you click for example the "Owner Commands" option, a certain embed is sent, however if you click the "Moderation Commands" options, a different embed is sent, and so on?

woeful spindle
#

???

rare ice
#

I’d recommend using that, then using page groups for selects then just pass in one embed for pages to show.

#

@woeful spindle

woeful spindle
#

Isn’t that buttons and not a select / drop-down menu?

rare ice
signal stratus
#

I'm getting desperate here haha, can anyone help?

rugged lantern
#

what is your voted.json()

signal stratus
rugged lantern
#

why do you use .json if that's the direct link

signal stratus
#

What else should I use?

rugged lantern
#

your variable voted is already the json

#

so just voted()

signal stratus
#

Is that what you mean?

rugged lantern
#

nvm- no clue. u probably need to use .json after all. i've never used requests so nvm!

cyan quail
# signal stratus

pretty sure it's because you aren't authorized, try printing voted

#

...on that note, please read the docs for whatever services/libraries you use

signal stratus
#

Did not work

cyan quail
#

what error

signal stratus
cyan quail
#

then print voted without converting to json, what does it say

cyan quail
#

you got ratelimited

signal stratus
#

What can I do about it?

fallen cove
#

can you autocomplete a member field in slash commands?

cyan quail
fallen cove
cyan quail
#

hm

#

slash autocompletes are only string based, but there's nothing stopping you from iterating through guild.members and returning the list of str(member)

fallen cove
#

hmm okie thank you

undone falcon
#

Is there a way to make that bot work with autocomplete in VScode ?

#

bot: discord.ext.commands.Bot = discord.ext.commands.Bot()

#

when I do discord.Bot it work fine

#

but not for that one

next comet
#

anyone know why im randomly getting this error

Exception in callback _ProactorBasePipeTransport._call_connection_lost(None)
handle: <Handle _ProactorBasePipeTransport._call_connection_lost(None)>
Traceback (most recent call last):
  File "C:\Users\Username\AppData\Local\Programs\Python\Python310\lib\asyncio\events.py", line 80, in _run
    self._context.run(self._callback, *self._args)
  File "C:\Users\Username\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 162, in _call_connection_lost
    self._sock.shutdown(socket.SHUT_RDWR)
OSError: [WinError 10038] An operation was attempted on something that is not a socket
fervent cradle
undone falcon
#

I do

#

the code is runnign without any problem

#

it is just the autocomplete not working for the discord.ext.commands.Bot

fading granite
#

is it possible to call another command using a command?

gleaming falcon
next comet
#

but why wahh

fervent cradle
#

How do I run 3 background functions inside a cog? I try to get them running on on_ready but only the first one runs and blocks whatever is left in on_ready

proud pagoda
#

Check GitHub and the docs for examples and documentation

fervent cradle
#

the 3 async functions need to be run only once.

#

they have while True: in them and will run in the backround