#Basic Pycord Help (Quick Questions Only)

1 messages · Page 5 of 1

young ledge
#

u got anyway to fix that?

round rivet
#

?tag message-content

obtuse juncoBOT
#

As of Pycord Beta 5, Discord API v10 requires message content intent to receive message content. This affects the traditional commands. Not enabling this intent will result in the messages' content, embeds, and components being empty.

You will need to enable the intent on the developer portal, as well as in your code:

intents = discord.Intents.default()
intents.message_content = True
bot = discord.Bot(intents=intents)

Docs: https://docs.pycord.dev/en/master/api.html#discord.Intents.message_content

young ledge
#

thank you

tranquil pivot
#

Not sure if you have an answer already or not but you can use "ctx.author"

dawn gyro
#

I made a set prefix command and when ever users set their prefix to " ' " or " it returns an error, Any idea on how I can fix?
prefix set '
await ctx.send(f'I put the prefix as {prefix}'}
ExpectedClosingQuoteError

rare ice
#

?tag lp

obtuse juncoBOT
#
young ledge
#

can i check for a message attachment in a on_message() event?

dawn gyro
rare ice
rare ice
dire spadeBOT
young ledge
#

index*

dawn gyro
rare ice
rare ice
#

Send your code too

young ledge
#

I send an imaege

#
@client.event
async def on_message(ctx):
        if ctx.channel.id == 938540668895244321:
            print(ctx.attachments[0].url)
            await ctx.delete()
#

there

#

I just wanted to print the url to the attachments

dawn gyro
# rare ice Send your updated code
@prefix_group.command(name='set', help='Set command prefix for guild', usage='Syntax: {}prefix set (prefix)$$Example: {}prefix set ,')
async def prefix_set(self, ctx, prefix:str):
  return await ctx.send(f"``{prefix}`` already exists as a **command prefix**")
  return await ctx.send(f"prefix must be under **7 characters**")
           
  return await ctx.send(f"Set ``{prefix}`` as the **command prefix**")
        
  return await ctx.send(f"Added ``{prefix}`` as a **command prefix**")```
young ledge
rare ice
#

b!rtfm pyc discord.on_message

rare ice
#

first one

rare ice
dawn gyro
#

but here

#
@prefix_group.command(name='set', help='Set command prefix for guild', usage='Syntax: {}prefix set (prefix)$$Example: {}prefix set ,')
async def prefix_set(self, ctx, prefix:str):
        if prefix in self.bot.server_cache[ctx.guild.id]["prefixes"]:
            return await ctx.send(f"``{prefix}`` already exists as a **command prefix**")
        if len(prefix) > 7:
            return await ctx.send(f"prefix must be under **7 characters**")
        if len(self.bot.server_cache[ctx.guild.id]["prefixes"]) == 0:
            await self.bot.db.execute('UPDATE guild_config SET prefixes = array_append(prefixes, $1) WHERE guild_id = $2', prefix, ctx.guild.id)
            await self.bot.helper.prepare(self.bot, ctx.guild)
            return await ctx.send(f"Set ``{prefix}`` as the **command prefix**")
        await self.bot.db.execute('UPDATE guild_config SET prefixes = array_append(prefixes, $1) WHERE guild_id = $2', prefix, ctx.guild.id)
        await self.bot.helper.prepare(self.bot, ctx.guild)
        return await ctx.send(f"Added ``{prefix}`` as a **command prefix**")```
rare ice
dawn gyro
rare ice
#

Which line?

dawn gyro
# rare ice Which line?

doesn't mention, It just returns it back to the pycord libary

 argument = view.get_quoted_word()
  File "C:\Users\User\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\view.py", line 152, in get_quoted_word
    raise ExpectedClosingQuoteError(close_quote)
discord.ext.commands.errors.ExpectedClosingQuoteError: Expected closing ".```
rare ice
#

Hmm

#

What version are you using for Pycord?

dawn gyro
#

yeah its 2.0.0

rare ice
#

Odd

#

Could you try uninstalling pycord then installing with the GitHub branch and seeing if that fixes it?

#

!install

civic jayBOT
#

Install pycord:

pip uninstall discord.py
pip install py-cord

Install pycord from git repository: (alpha)

pip uninstall discord.py
pip install git+https://github.com/Pycord-Development/pycord
rare ice
#

2nd part

rare ice
young ledge
dawn gyro
rare ice
rare ice
# dawn gyro same error

Hmm, I don’t know then. Are you sure you updated the code in your bot? Because it shouldn’t be erroring.

rare ice
#

And if that doesn’t work, try printing message.attachments and see where that takes you

young ledge
#

will do so

rare ice
young ledge
rare ice
#

Send your updated code

#

Actually @young ledge, do you have the message content intent enabled? If not, you need to enable it or else it will always return an empty list.

#

?tag message-content

obtuse juncoBOT
#

As of Pycord Beta 5, Discord API v10 requires message content intent to receive message content. This affects the traditional commands. Not enabling this intent will result in the messages' content, embeds, and components being empty.

You will need to enable the intent on the developer portal, as well as in your code:

intents = discord.Intents.default()
intents.message_content = True
bot = discord.Bot(intents=intents)

Docs: https://docs.pycord.dev/en/master/api.html#discord.Intents.message_content

young ledge
#
@client.event
async def on_message(message):
        if message.channel.id == 938540668895244321:
            print(message.attachments)
            await message.delete()
young ledge
rare ice
#

Ok that’s why

#

thought you had it enabled

young ledge
#

i dont lmao

#

alright let me go enable it in the dev portal

#

where do i find it?

rare ice
#

In the Bot tab of your application

#

In the Dev portal

young ledge
#

i need to wait till tomorrow?

rare ice
full basin
#

@rare ice they have a thread

young ledge
rare ice
full basin
#

ItsSolo

young ledge
#

I removed it

rare ice
#

and Jesus I need to go disable it on my public bot

young ledge
young ledge
rare ice
#

Ok that’s not the point. You need to enable it on your bot or else you won’t be able to access .content .attachments .embeds and more if you don’t.

young ledge
#

it works i love you man! @rare ice

rare ice
#

uh ok

#

glad I could help :)

young ledge
#

yeah :)

delicate jolt
#

Anyone got an example of how to get a param when doing slash commands? like /hug user:

fervent cradle
delicate jolt
#

just like

#

Like this but for a user

fervent cradle
#

What do you mean by get a param

#

ik what a param is

delicate jolt
#

Forget that bit

#

Im tired

#

But I just wanna make it so someone can do /hug user

#

yk

smoky forge
#

?tag guide

obtuse juncoBOT
smoky forge
#

go here and navigate over to interactions > application commands > slash commands

delicate jolt
#

Thanks

errant craneBOT
#

Here's the slash options example.

undone girder
#

if i have a bytesio image how can i send it in an embed cuz it only accepts urls

#

i just figured it out

#

lol

delicate jolt
#

What's the best library for music?

#

Like lowest CPU utilisation etc

#

And It streams it doesn't download it

void abyss
#

I'm pretty sure Spotify has a api

rugged lantern
#

why would you want low CPU utilization

amber shale
#

how to give user option to select from?

#

in bridge command

next comet
#

What's the difference between pass and ...

round rivet
next comet
#

practically, there's no difference then

round rivet
#

there is

#

an ellipsis is an actual thing you can use

fading granite
#

Is it possible to change the bots avatar through script

round rivet
#

as say, a default param value

next comet
#

hmm, i see

#

so its like pass, as a variable

round rivet
#

essentially, but they mean two different things

next comet
#

yeh, thanks

round rivet
#

like:

def foo(thing):
    if thing:
        pass
    else:
        ...  # do something here
#

not the greatest example but it makes sense

fading granite
#

Thanks!

next comet
#

ah yeah, i see

#

also
generally, for a boolean for example, would it be better to check
if bool is True / if bool is False / if bool is not True
or
if bool / if not bool

rugged lantern
#
def foo(bar):
    if bar:
        pass
    else:
        ...  # do something here

would be a better example

fervent cradle
#

How can i fix it?

    await interaction.response.edit_message(f'Тикет создан. {ch.mention}')
TypeError: InteractionResponse.edit_message() takes 1 positional argument but 2 were given```
alpine helm
tropic vortex
#

how do I disable this default embed length?

#

it's making some of my commands look horrible

fervent cradle
#

how do i make it so not str

#

rn its like this

#

i need it to be requried and type is int

tropic vortex
#

after discord.Option put (int, required=True)

fervent cradle
tropic vortex
#

weird...

fervent cradle
#

hey everyone i am trying to build a function which will send a dm to me but it doesnt seem to work, below are the informations needed

code:

import discord

client = discord.Client

async def notify_owner(message):
    user = await client.fetch_user("1003360317725745153")
    await user.send(message)

now if you see i clearly defined a user id for fetch_user function, but i keep getting this error:

TypeError: Client.fetch_user() missing 1 required positional argument: 'user_id'
#

btw this part of code is in another separate file so i havent defined anything else

rugged lantern
#

don't make it a string

#

remove the ""

fervent cradle
#

i tried with and without strings, but still i get this typeerror

rugged lantern
#

then try user_id=...

fervent cradle
rugged lantern
#

do u have @client.event infront of it?

fervent cradle
#

because i am trying to make this a util for me

rugged lantern
#

so add @client.event above your 'notify owner'

fervent cradle
#

like whenever i want, i import this file, and run this function in my main files

fervent cradle
rugged lantern
#

s

fervent cradle
rugged lantern
#

i'm way too tired for this, hopefully someone more helpful can help u :p

fervent cradle
#

oof

#

alr

topaz rune
#

Hi, just a quick question, can we find the @ of someone with his id?

rugged lantern
#

<@ID>?

outer obsidian
#

?tag ex

fervent cradle
rugged lantern
#

ok and how do u expect it to be executed if not by command?

fluid crystal
#

How i cane install the topggpy lib for pycord?

fervent cradle
# rugged lantern ok and how do u expect it to be executed if not by command?
@commands.slash_command(name="chat", description="start a convo with the bot")
    async def chat(self, ctx, *, text: Option(str, "What is your message?", required=True)):
        await ctx.defer()
        try:
            brainid = os.environ['BRAIN_ID']
            brainapikey = os.environ['BRAIN_API_KEY']
            chat_payload = {'bid': brainid, 'key': brainapikey, 'uid': 84663, 'msg': text}
            chat_rsp = requests.get('http://api.brainshop.ai/get', params=chat_payload).json()['cnt']
            await ctx.respond(chat_rsp)
        except Exception as chat_err:
            await ctx.respond(information.error_message)
            await information.notify_owner("error message here")
#

in the last line this is how i expect to import the function from that file and pass in the message i want to send

outer obsidian
#

and also. fetch_user takes int instead of str

fervent cradle
fervent cradle
# outer obsidian full error pls

the full error
and the code:

import discord

client = discord.Client()

async def notify_owner(message):
    user = await client.fetch_user(1003360317725745153)
    await user.send(message)
outer obsidian
dreamy raft
fervent cradle
# outer obsidian why is it information.notify_owner? is the method in a class?
@commands.slash_command(name="chat", description="start a convo with the bot")
    async def chat(self, ctx, *, text: Option(str, "What is your message?", required=True)):
        await ctx.defer()
        try:
            brainid = os.environ['BRAIN_ID']
            brainapikey = os.environ['BRAIN_API_KEY']
            chat_payload = {'bid': brainid, 'key': brainapikey, 'uid': 84663, 'msg': text}
            chat_rsp = requests.get('http://api.brainshop.ai/get', params=chat_payload).json()['cnt']
            await ctx.respond(chat_rsp)
        except Exception as chat_err:
            await ctx.respond(information.error_message)
            await information.notify_owner("e")
#

this is how i used it, and yes its within a class, since this command is in a cog

fervent cradle
delicate jolt
#

Is there a way to add a command cooldown to slash commands?

young bone
delicate jolt
#

sweet ty

fervent cradle
fresh gust
#

Running bot throws up this error:

  File "c:/Users/Kashyap/Desktop/cord/pycord/button view.py", line 1, in <module>     
    import discord
  File "C:\Users\Kashyap\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\__init__.py", line 23, in <module>  
    from . import abc, opus, sinks, ui, utils
  File "C:\Users\Kashyap\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\abc.py", line 60, in <module>       
    from .voice_client import VoiceClient, 
VoiceProtocol
  File "C:\Users\Kashyap\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\voice_client.py", line 55, in <module>
    from .gateway import *
  File "C:\Users\Kashyap\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\gateway.py", line 37, in <module>   
    import aiohttp
  File "C:\Users\Kashyap\AppData\Local\Programs\Python\Python38-32\lib\site-packages\aiohttp\__init__.py", line 6, in <module>   
    from .client import (
  File "C:\Users\Kashyap\AppData\Local\Programs\Python\Python38-32\lib\site-packages\aiohttp\client.py", line 35, in <module>    
    from . import hdrs, http, payload
  File "C:\Users\Kashyap\AppData\Local\Programs\Python\Python38-32\lib\site-packages\aiohttp\http.py", line 7, in <module>       
    from .http_parser import (
  File "C:\Users\Kashyap\AppData\Local\Programs\Python\Python38-32\lib\site-packages\aiohttp\http_parser.py", line 15, in <module>
    from .helpers import NO_EXTENSIONS, BaseTimerContext
  File "C:\Users\Kashyap\AppData\Local\Programs\Python\Python38-32\lib\site-packages\aiohttp\helpers.py", line 667, in <module>  
    class CeilTimeout(async_timeout.timeout):
TypeError: function() argument 'code' must 
be code, not str```

I cant figure it out, any help is appreciated
#

PLEASE HELP 😭

silver moat
#

if you already made a thread, please commit to that thread

fresh gust
#

i already did 😭😭
no ones been able to help thus far

wicked helm
#

| 2022-08-01 16:50:55,901 | ERROR | [server_button_view.py:106] | 'Button' object has no attribute 'response'

    async def show_page(self, page: int, interaction: discord.Interaction):
        """
        Show the page content
        """
        await self.update(page)
        
        content, embeds, files = await self.get_page(self.pages[page])

        await interaction.response.edit_message(
            content = content,
            embeds = embeds,
            attachments = files or [],
            view = self
        )

    @ui.button(emoji = "➡️", style = discord.ButtonStyle.grey)
    async def next_page(self, interaction, button):
        """
        Previous page
        """
        logger.info("Try Next Page")

        try:
            await self.show_page(self.current_page + 1, interaction)
        except Exception as e:
            logger.error(f"{e} ")
            self.stop()

So - Youtube tutorial, works fine on there. But I get the error Button has not attribute response... Any ideas. Also is this something I should really make a thread for?
Not sure at what point it becomes thread worthy!

silver moat
wicked helm
# silver moat what is the entire traceback?
Traceback (most recent call last):
  File "D:\Visual Code Git Clones\BRVNS-Discord-Bot\src\button_views\server_button_view.py", line 102, in next_page
    await self.show_page(self.current_page + 1, interaction)
  File "D:\Visual Code Git Clones\BRVNS-Discord-Bot\src\button_views\server_button_view.py", line 60, in show_page
    await interaction.response.edit_message(
AttributeError: 'Button' object has no attribute 'response'```
silver moat
wicked helm
silver moat
#

np

opal birch
#

how can I load an extension in slash command

silver moat
#

b!rtfm pyc bot.load_extension

wicked helm
opal birch
#

oh I see my bad was using the wrong thing

silver moat
young ledge
#

How do I get someone's pfp/banner just using their id

young bone
#

client.fetch_user()?

wicked helm
#

think360 Can I have buttons - Inside an embed?

EG, if I wanted to use the paginator to set up a page with a bunch of buttons?

Or a select menu.. think360

young ledge
#

so fetch_user(id)??

tropic hull
#

Hello globalbans cant delete, no error on console

#
import discord
from discord.ext import commands
import sqlite3
import time

class remove_globalban(commands.Cog):

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

    @commands.command()
    @commands.is_owner()
    async def remove_gban(self, ctx, member: discord.Member):
        db = sqlite3.connect("globalbans.db")
        cursor = db.cursor()
        cursor.execute(f"SELECT * FROM globalbans WHERE user_id = {member.id}")
        wynik = cursor.fetchall()
        if wynik:
          for gban in wynik:
            emb=discord.Embed(title=f"![yes](https://cdn.discordapp.com/emojis/881521661092962365.webp?size=128 "yes") {member} Został Globalnie Odbanowany!", description=f"**Administrator:** {ctx.author.mention}", color = discord.Colour.green())
            emb.set_footer(text = f"Wyświetlone dla: {ctx.author} ({ctx.author.id})")
            emb.set_thumbnail(url=member.display_avatar)
            cursor.execute("DELETE FROM globalbans WHERE user_id = ? AND content = ? AND author_name = ? AND time = ?", (gban[0],gban[1],gban[2],gban[3]))
        db.commit()
        cursor.close()
        db.close()
        await ctx.reply(embed=emb, mention_author=False)

def setup(bot):
    bot.add_cog(remove_globalban(bot))```
fresh gust
#

hi, does anyone know a quick way to get a user's spotify ID from their profile? (assuming they've authorised it)

IS THERE EVEN A WAY TO DO SO?
EDIT: lol there isnt my bad :p

white wadi
#

do you know any free hosting for pycord bot? (can be trial) i just need to test some things

fresh gust
white wadi
#

thats ok, i just need it for testing, so thats not a problem for me

fresh gust
#

in that case, heroku would be perferct

white wadi
#

thanks

fervent cradle
#

await self.client.get_channel(_welcome_channel).send(embed=welcome_embed)
_welcome_channel is None for some reason

fervent cradle
#

use channelid

fervent cradle
#

then put in the int not the name

fervent cradle
#

and that shouldn't matter anyways

#

thats right but i can´t see that it´s from a config 😄

#

i see a string and not a int

#

but check if it a int and not a str for some reason

rugged lantern
#

just int lawl

white wadi
#

i cant find it

delicate jolt
#

For on_application_command_error is there anyway I can get the command that was being ran?

fervent cradle
#
import discord
from discord.ui import *
from core import bd, ui
from loguru import logger


b = bd.HFD
logger.add("./main.log", rotation="500 MB")
bt = b.open(self=b)


class Bot(discord.Bot):
    def __init__(self):
        super().__init__(intents=discord.Intents.all(), status=discord.Status.idle, activity = discord.Activity(type=discord.ActivityType.playing, name = 'пальчики бекона'))
        intents = discord.Intents.all()
        intents.message_content = True
        intents.dm_messages = True
        intents.members = True


        self.persistent_views_added = False
    
    async def on_ready(self):
        if not self.persistent_views_added:
            self.add_view(view=ui.PersistentView())
            self.add_view(view=ui.RolesUs())
            self.add_view(view=ui.RolesCst())
            self.add_view(view=ui.RolesBot())
            self.add_view(view=ui.CreateTicket())
            self.add_view(view=ui.CloseTicket())
            self.persistent_views_added = True

        print(f"Logged cog as {self.user} (ID: {self.user.id})")
        print("------")

bot = Bot()

cogs_list = [
    'events',
    'settings',
    'mod',
    'warns',
    'admin',
    'proles',
    'ticket',
    'help',
    'ctm',
    'active'
]

for cog in cogs_list:
    bot.load_extension(f'cogs.{cog}')
    

bot.run('')
#--------------------------------------------------------------#```
silver moat
fervent cradle
#

What does this thing do?

silver moat
fervent cradle
#

now i fix all errors

main flax
#

Hey, is it possible to disable a slashcommands on a particular server but still have it enabled on the other servers. When I say "disable" I mean grayed out or not visible.

silver moat
delicate jolt
#

ty

dreamy mauve
#

how to download image attached with an embed?

tropic hull
#

I like clean code

hushed ledge
#

One message removed from a suspended account.

copper dew
sonic lotus
#

Is there a quick way to delete a lot of PNs of my bot? I might have made a mistake and received 16786 Messages from my bot over the course of 5 hours 😅

wicked helm
#

Is a paginator of discord views possible? think360

wicked helm
cyan quail
#

the Page object has a custom_view attribute that you can use

tidal dagger
#

how do I sync slash commands?

wicked helm
cyan quail
wicked helm
cyan quail
wicked helm
#

Appreciate it! 😄

cyan quail
#

allgood

sonic lotus
# cyan quail do you mean closing DMs?

No, I want to get rid of these 16k messages without deleting the others. I could do this message by message but that would run for about 10 hours or sth

cyan quail
#

you need to erase messages from the server?

#

or did your bot send 16k messages to different members...? sorry, your original question was a bit unclear

#

oh i think i see what you mean

cyan quail
tidal dagger
#

please, can someone tell me how do I sync slash commands?

sonic lotus
cyan quail
tidal dagger
#

now thats odd

cyan quail
#

...i hope that works in dms

#

...apparently not

#

hmmm

#

yeah you might be out of luck, bulk deleting is only possible for guild channels; your only other option is deleting each message individually

sonic lotus
verbal gulch
#
async def ban(ctx, usuario:discord.Option(discord.Member), reason:discord.Option()):
#

'line 14, in <module>
async def ban(ctx, usuario:discord.Option(discord.Member), reason:discord.Option()):
TypeError: ApplicationCommandMixin.slash_command() takes 1 positional argument but 2 were given'

#

what does this error mean?

verbal gulch
#

Hm, i don't think so

#
@bot.slash_command
async def ban(ctx, usuario:discord.Option(discord.Member), reason:discord.Option()):
    embed1 = discord.Embed(
        title='Usuario baneado de pokemania.',
        description= ':kaiban: Moderador: {discord.ApplicationContext.author} \nVíctima: {usuario} \n Razón: {reason}',
        color= discord.Colour.red(),
        footer= '{datetime} · Bye bye',
    )
    await usuario.send('Has sido baneado en pokemania! Moderador: {discord.ApplicationContext.author} \nVíctima: {usuario} \n Razón: {reason}')
    await discord.Guild.ban(usuario, reason=reason)
    await ctx.respond(embed=embed1)
    # Crea un embed, manda un mensaje en el dm, lo banea, y emvia el embed.

    bot.run('private, removed')
cyan quail
#

should be @bot.slash_command()

verbal gulch
#

ohh, i forgot about it

#

thanks

#

i run it and it instantly stop

cyan quail
#

wrong indent for bot.run

verbal gulch
#

yeah, i saw

#

fixed

cyan quail
#

also unrelated but discord.ApplicationContext.author should be ctx.author instead

#

and discord.Guild as ctx.guild

verbal gulch
#

Thanks you so much, i'm new and i'm still learning

cyan quail
#

all good

verbal gulch
#

'the application did not respond'

cyan quail
#

do you have a full error in the console?

verbal gulch
#

ye

#

Embed.init() got an unexpected keyword argument 'footer'

cyan quail
#

ahh right

verbal gulch
#

ahh

#

okie

#

also ban doesn't work

#

what's 'self'

silver moat
#

You are attempting to use f-string syntax in a normal string. An f-string looks like this:

f"hi, I am {name}"
#

?tag oop

obtuse juncoBOT
#

https://www.digitalocean.com/community/tutorials/understanding-class-and-instance-variables-in-python-3
https://docs.python.org/3/tutorial/classes.html

There's a difference between a class and an instance. Think of it like this:

  • A class is like a blueprint, or a concept. It defines what something should have, but it's not the same as actually having it.
  • An instance is the 'realized' version of the class, it contains everything that the class defines should be on it, but you can actually access and interact with these features.

Let's consider the Cat. We know a Cat has a name and an age, but Cat.age won't work, because Cat isn't an actual cat, it just represents the concept of a cat. It's like asking "What is the age of a cat?" - it doesn't make sense, because we need to have an actual cat.

mimi on the other hand is an instance of a Cat - it has everything a Cat should have. Maybe mimi was constructed, like mimi = Cat("Mimi", age=4), or maybe mimi was retrieved from somewhere else, like house.cats[0], but in any case, it has everything we need, and mimi.age will rightfully give us 4.

There are many situations in Object Oriented Programming where you will need an instance instead of a class to perform an operation properly (in fact, you almost always need an instance instead of a class), and these cases will usually be documented.
You should learn a good amount about Object Oriented Programming before working extensively with Pycord.

verbal gulch
#

ok ty

#

still asking for 'self'

#

missing 1 required positional argument: 'self'

silver moat
#

Show full traceback thanks

verbal gulch
#

Ignoring exception in command ban:
Traceback (most recent call last):
File "C:\Users\danie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 127, in wrapped ret = await coro(arg)
File "C:\Users\danie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 881, in _invoke await self.callback(ctx, **kwargs)
File "c:\Users\danie\OneDrive\Documentos\rtc\iworldpc3#Pokemania (2) (1).py", line 23, in ban
await discord.Guild.ban(user=usuario, reason=reason)
TypeError: Guild.ban() missing 1 required positional argument: 'self'

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

Traceback (most recent call last):
File "C:\Users\danie\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\danie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 358, in invoke
await injected(ctx)
File "C:\Users\danie\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\commands\core.py", line 135, in wrapped raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: Guild.ban() missing 1 required positional argument: 'self'

silver moat
hushed ledge
young ledge
#

How could i make a clear command?

silver moat
#

what is clear

#

what does it do

young ledge
#

its basically clears/deletes the past messages

#

lets say /clear 5 it will delete the 5 message

silver moat
#

b!rtfm pyc textchannel.purge

dire spadeBOT
silver moat
#

this could be what you are looking for

young ledge
#

thank you

verbal gulch
#
bot.slash_command()
async def ban(ctx, usuario:discord.Option(discord.Member), reason:discord.Option()):
    embed1 = discord.Embed(
        title='Usuario baneado de pokemania.',
        description=f':kaiban: Moderador: {ctx.author} \nVíctima: {usuario} \n Razón: {reason}',
        color= discord.Colour.red(),
    )
    embed1.set_footer(text= '{datetime} · Bye bye')

    await usuario.send(f'Has sido baneado en pokemania! Moderador: {ctx.author} \nVíctima: {usuario} \n Razón: {reason}')
    await ban(ctx, usuario, reason=reason )
    await ctx.respond(embed=embed1)
    # Crea un embed, manda un mensaje en el dm, lo banea, y emvia el embed.

#

It doesn't work, but it doesn't send any message to my console

silver moat
#

why did you make it recursive

#

ban is calling itself

verbal gulch
#

ah

#

i just don't understand the guide

silver moat
#

b!rtfm pyc ban

silver moat
#

you can ban a user from a guild with

await ctx.guild.ban(user, reason)
#

ctx.guild returns a Guild object, while discord.Guild is a guild class.

verbal gulch
#

oooh

#

have senseee

#

tyy

#

discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: Guild.ban() takes 2 positional arguments but 3 were given

#
await ctx.Guild.ban(usuario, reason)
silver moat
#

guild in lower case

verbal gulch
#

still not working

#

same error

silver moat
#

user = usuario

verbal gulch
#

and reason = reason

silver moat
#

you can do that

verbal gulch
#

finally!!!!

verbal gulch
#

Hi, how can i make when clicking a button it reply with a private message?

meager heron
#

The guide says to make slash command options using param: Option(...). The examples in the repo, however, show an @option decorator. Which is preferred?

meager heron
silver moat
silver moat
#

?tag Ephemeral

obtuse juncoBOT
#

dynoError No tag Ephemeral found.

silver moat
#

?tag ephemeral

obtuse juncoBOT
#

An 'ephemeral' message is one that's only visible to the person who invoked a command. If you ever got a command error with a blue background, this is an example of one.

To do this, set ephemeral=True when you first use an ApplicationContext. (This includes .defer()ing it; the choice of whether a message is ephemeral or not must be made up front. If you .respond() to a deferred message, setting the ephemeral flag at that time will have no effect.)

This is the equivalent of hidden=True if you're coming from interactions.py

verbal gulch
#

yep that

#

like this? ```py
async def warn(ctx, usuario:discord.Option(discord.Member), reason, ephemeral=True):

#

or in the button class?

silver moat
#

no, like ctx.respond("your things here", ephemeral = True)

verbal gulch
#

alright

young ledge
#

How do i make the bot send a messaege each certain amount of time

#

like each hour or minute

young ledge
#

thanks

verbal gulch
#

So hi again, sorry to bother a lot. How can i make the bot send a message to a message said in the code?

verbal gulch
#

like sending a message to a channel defined in the code.

#

You know what i mean?

fervent cradle
#

fetch the channel and then do
await channel.send()?

#

b!rtfm pyc get_channel

verbal gulch
fervent cradle
#

b!rtfm pyc discord.TextChannel.send

dire spadeBOT
fervent cradle
#

hey does anyone know how to use discord.TextChannel as a discord.Option in slash command?

my code still takes the input as a string...
(i've tried tier.id and tier.mention. both strings...?)

@client.slash_command(
    name='stats',
    description='Graph of your match history',
    guilds_ids=Lounge
)
async def stats(
    ctx: discord.ApplicationContext,
    tier: discord.Option(input_type=discord.TextChannel, description='Choose a channel', required=False)
    ):
    await ctx.defer()
    if tier.mention in TIER_ID_LIST:
        print('yay')
        await ctx.respond('yay!')
    else:
      # do other stuff i didnt paste all the code
fervent cradle
#
@client.slash_command(
    name='stats',
    description='Graph of your match history',
    guilds_ids=Lounge
)
async def stats(
    ctx: discord.ApplicationContext,
    tier: discord.Option(discord.TextChannel, description='Choose a channel', required=False)
    ):
    await ctx.defer()
    if tier.mention in TIER_ID_LIST:
        print('yay')
        await ctx.respond('yay!')
    else:
      # do other stuff i didnt paste all the code```
#

hm

#

is there a way to make the input optional tho?

fervent cradle
#

yea thats fine. its just the #channel-name was coming in as a string.

#

so tier was a string?

#

yea

#

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

#

oh

#

your suggestion worked, but i need it to be optional 🤔

fervent cradle
#

oh what the heck. - i thought i tried this? it works now. 😵‍💫

#

thank you!

fervent cradle
#

yea i must have typod somewhere. so i went to the docs and tried what it told me to lol. little goose chase. i appreciate the help!

#

np

fervent cradle
#

How do you edit an embed thats already defined?

#
embed = discord.Embed(title='Embed 1', description='embed one')
await ctx.send(embed=embed)
# edit embed title
await ctx.send(embed=embed)
proud pagoda
#

!rtfm pyc discord.Embed

civic jayBOT
fervent cradle
proud pagoda
#

yw

quick temple
#

Is it possible to get a list of all users who have a certain role id?

full basin
wicked helm
#

How do I add embeds to a subclassed view?

full basin
#

The same way you do for any response?

wicked helm
#

But will that work with a paginator?

full basin
#

Huh?

wicked helm
#

Nvm

#

I was being dumb!

void fable
#

is it possible to have a dynamic cooldown in a slash command?

quick temple
#

or permission

full basin
#

Members intent

silver moat
void fable
# silver moat yes just slap the dynamic cooldown decorator onto it

oh alright thank you i wasn't sure if it was because i couldn't do it or not but would you be able to help me with how to correctly setup the function for cooldown? in this case i want it to have 0 cooldown if im the user

def custom_cooldown(user):
    if user == 92786442891169792:
        return None
    else:
        return Cooldown(rate = 1, per = 60)

@commands.dynamic_cooldown(custom_cooldown(), commands.BucketType.user)```
#

idk if im not looking hard enough but i couldn't find an example of the function on the docs?

silver moat
#

wait interactions don't have messages

void fable
silver moat
#

probably

#

maybe use a print(type(user)) to first find out what type user is?

void fable
#

alrighty, on a related note to cooldowns, can i have the cooldown reset inside the command if they mess up something along the way?

#

for example this is for a rpg bot im making and if the player dies, they are free to try again but if they win cooldown is triggered

silver moat
#

I don't see why not.

#

Also, just a side-note. Atom and all repositories under Atom will be archived on December 15, 2022

void fable
#

what the

#

rip 😔

silver moat
#

ig they want to stop maintaining three IDEs and just simplify it to two.

void fable
#

i just like how it looked

silver moat
#

the layout specifically or the color scheme? Because most text editors and IDEs have themes/plugins to change the color scheme.

void fable
#

the layout

#

little clutter

void fable
#

was checking the atom thing but where would i be printing this in, inside of my command to see what it is when i run it?

silver moat
#

yeah

#

inside the dynamic cooldown func

void fable
#

also in @commands.dynamic_cooldown(custom_cooldown(), commands.BucketType.user) wouldn't i need to put in user for custom_cooldown

silver moat
void fable
#

oh really

silver moat
#

I also think it's without the parentheses @commands.dynamic_cooldown(custom_cooldown, commands.BucketType.user)

void fable
#

but don't i need them since its a function

#

or is this another assumption the library does

silver moat
void fable
#
def custom_cooldown(user):
    if user == 92786442891169792:
        return None
    else:
        return discord.ext.commands.Cooldown(rate = 1, per = 60)

@bot.slash_command(description = "cooldown test")
@commands.dynamic_cooldown(custom_cooldown, commands.BucketType.user)
async def poopingtest(ctx):
    print(type(user))
#

unless you meant the custom_cooldown function

silver moat
#

no, in
def custom_cooldown(user):

#

sorry for being unclear

void fable
#

no its ok i appreciate you helping me

white wadi
#

Hi, i am being rate limited with my discord bot. Is there a way to see how long will it take before i can turn the bot again?

void fable
#
def custom_cooldown(user):
    print(type(user))
    if user == 92786442891169792:
        return None
    else:
        return discord.ext.commands.Cooldown(rate = 1, per = 60)

returns <class 'discord.commands.context.ApplicationContext'>

white wadi
silver moat
silver moat
silver moat
void fable
#
def custom_cooldown(ctx):
    if ctx.author == 92786442891169792:
        return None
    else:
        return discord.ext.commands.Cooldown(rate = 1, per = 60)
silver moat
void fable
#

oops ye

silver moat
#

right

void fable
#

can it get the context this way?

silver moat
white wadi
#

i just found that the rate limit is only on one ip, so vpn ez

silver moat
#

gj

void fable
#

discord.ext.commands.Cooldown?

silver moat
#

ctx.command.reset_cooldown(ctx)

#

b!rtfm reset_cooldown

dire spadeBOT
# silver moat b!rtfm reset_cooldown

I couldn't find a documentation with the name reset_cooldown! Maybe you used to command wrong? Correct Usage: <prefix>rtfm <docs> [<term>] (eg. b!rtfm py cool)
List of Documentations you can search:
python
pycord
discord.py
yarsaw
nextcord
disnake

silver moat
#

b!rtfm pyc reset_cooldown

silver moat
#

yeah

void fable
#

o alright, thank you for the help!

silver moat
#

np

near hollow
#

Is it possible to use await bot.sync_commands() to sync slash commands in cogs?

undone falcon
#

Does the bot load all members from all the bot servers at the bot starts ? Like if I do bot.guild after start, do I have the most up to date information ?

silver moat
#

The cache also updates when things update.

undone falcon
silver moat
undone falcon
#

I see thank you !

fervent cradle
#

ive been setting up pycord on a diff pc and i got everything ready but when i do import discord, it throws a modulenotfound error even tho i did pip install py-cord

silver moat
#

virtual env?

fervent cradle
#
        log.debug(welcome_channel)
        _welcome_channel = self.client.get_channel(welcome_channel)
        log.debug(_welcome_channel)
DEBUG    | 960196760565841941
DEBUG    | welcome

what the hell

graceful plover
#
Banned members - {len(await guild.bans())}
TypeError: object BanIterator can't be used in 'await' expression
#

help

golden cairn
#

Hey guys
i startet using pycord.wavelink and after i setup my lavalink system and i want to connet with lavalink trough wavelink im gettings this error

Connection Failure: Cannot connect to host 0.0.0.0:2333 ssl:default [The format of the specified network name is invalid].

Connect Code

    async def connect_nodes(self):
        await self.bot.wait_until_ready()
        await wavelink.NodePool.create_node(
            bot=self.bot,
            host='0.0.0.0',
            port=2333,
            region='eu',
            password='xxx',
        )
vital blade
#

can i check if a bot is verified or not? and if i can how

amber shale
#

how to use paginator in slash command?

young bone
median ridge
#

How do I use permissions?

#

Like if I want slash commands only for myself?

young bone
median ridge
#

?

young bone
#

commands.is_owner()

median ridge
#

that doesn't work when my bot is under a dev team though

#

let's say I want to limit the command to only you and me

verbal gulch
#

Traceback (most recent call last):
File "C:\Users\danie\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 196, in _run_module_as_main
return _run_code(code, main_globals, None,
File "C:\Users\danie\AppData\Local\Programs\Python\Python310\lib\runpy.py", line 86, in run_code
exec(code, run_globals)
File "c:\Users\danie.vscode\extensions\ms-python.python-2022.10.1\pythonFiles\lib\python\debugpy_main
.py", line 39, in <module>
cli.main()
File "c:\Users\danie.vscode\extensions\ms-python.python-2022.10.1\pythonFiles\lib\python\debugpy/..\debugpy\server\cli.py", line 430, in main
run()
File "c:\Users\danie.vscode\extensions\ms-python.python-2022.10.1\pythonFiles\lib\python\debugpy/..\debugpy\server\cli.py", line 284, in run_file
runpy.run_path(target, run_name="main")
File "c:\Users\danie.vscode\extensions\ms-python.python-2022.10.1\pythonFiles\lib\python\debugpy_vendored\pydevd_pydevd_bundle\pydevd_runpy.py", line 321, in run_path
return _run_module_code(code, init_globals, run_name,
File "c:\Users\danie.vscode\extensions\ms-python.python-2022.10.1\pythonFiles\lib\python\debugpy_vendored\pydevd_pydevd_bundle\pydevd_runpy.py", line 135, in _run_module_code
_run_code(code, mod_globals, init_globals,
File "c:\Users\danie.vscode\extensions\ms-python.python-2022.10.1\pythonFiles\lib\python\debugpy_vendored\pydevd_pydevd_bundle\pydevd_runpy.py", line 124, in _run_code
exec(code, run_globals)
File "c:\Users\danie\OneDrive\Documentos\rtc\iworldpc3#Pokemania (2) (1).py", line 102, in <module>
async def marcar_sugerencia(ctx, Marca: discord.OptionChoice['Aprovar', 'denegar', 'considerar'], Comentario, sugerencia, id_mensaje):
TypeError: 'type' object is not subscriptable

median ridge
#

...

verbal gulch
#

what does this error mean

median ridge
#

please format it, and use pastebin

#

?tag pastebin

obtuse juncoBOT
#

dynoError No tag pastebin found.

young bone
#

or only send the Error....

verbal gulch
#
async def marcar_sugerencia(ctx, Marca: discord.OptionChoice['Aprovar', 'denegar', 'considerar'], Comentario, sugerencia, id_mensaje):
    approve=discord.Embed(
        title= 'Sugerencia nueva',
        description=f'**Sugerencia recibida de {ctx.author}:** \n __{sugerencia}__ \n\n :kaicorrect: Sugerencia aprovada \n\n Comentario de {ctx.author}: \n {Comentario},',
        color=discord.Colour.blurple(),
    )
    deny=discord.Embed(
        title= 'Sugerencia nueva',
        description=f'**Sugerencia recibida de {ctx.author}:** \n __{sugerencia}__ \n\n :kaiwrong: Sugerencia denegada \n\nComentario de {ctx.author}: \n{Comentario},',
        color=discord.Colour.blurple(),
    )
    consider=discord.Embed(
        title= 'Sugerencia nueva',
        description=f'**Sugerencia recibida de {ctx.author}:** \n __{sugerencia}__ \n\n:kaiConsider: Sugerencia considerada \n\nComentario de {ctx.author}: \n{Comentario},',
        color=discord.Colour.blurple(),
    )
    if Marca == 'Aprovar':
        discord.Message.edit(self=id_mensaje, embed=approve)
        await ctx.respond('Sugerencia marcada como aprovada.')
    if Marca == 'denegar':
        discord.Message.edit(self=id_mensaje, embed=deny)
        await ctx.respond('Sugerencia marcada como denegada.')
    if Marca == 'considerar':
        discord.Message.edit(self=id_mensaje, embed=approve)
        await ctx.respond('Sugerencia marcada como coonsiderada.')

#

this is the code

median ridge
#

better

fervent cradle
#

how do i get the user that clicked a button?

#

interaction.author right

young bone
#

yes

full basin
#

No

#

interaction.user

#

b!rtfm pyc discord.Interaction

full basin
amber shale
fervent cradle
#

Hello how do i put a custom emoji in a button, emoji="id"?

fervent cradle
#

yep

#

custom emoji from a server, like modshield

young bone
#
emoji="<:emoji_name:emoji_id>"
fervent cradle
#

that does not work

#

@discord.ui.button(label=" ", emoji=":music_pause:", style=discord.ButtonStyle.gray, custom_id="music_playpause")

young bone
#

you need the <

fervent cradle
#

oh wait it didnt send properly

#

it gives In components.1.components.2.emoji.id: Invalid emoji

young bone
fervent cradle
young bone
#

you do rightclick and press ID right?

fervent cradle
fervent cradle
young bone
#

it should be the one in the link

fervent cradle
#

wtf

#

whats the backslash ID then?

young bone
fervent cradle
young bone
fervent cradle
#

@young bone bro all my new ids are the exact same to old ones

fervent cradle
#

yep

#

all are the same
ill use a emoji for example ReadTheDocs
id from my way : !ReadTheDocs

young bone
#

Weird

fervent cradle
#

yep, do you want the full code?

young bone
#

No

fervent cradle
#

ah kk

young bone
#

Does the Button works with a label?

fervent cradle
#

is there a way to keep an empty label?

wicked helm
#

think360 interaction.response.edit_message() isn't working when I am using it on a button in a paginator

full basin
#

discord.Option(str, "Select an option", choices=["aprobar", "denegar", "considerar"])

fervent cradle
#

is there a way to use an image url for discord.File

full basin
#

As it takes a file itself, not urls

fervent cradle
# full basin Don't think so.

this is my code, and i am totally fine with it, but the problem is if the user hovers to the image on a pc they can see the url of the image exposing the api i am using, i want that url to be converted to cdn.discord one but i am not able to understand how to do that

panik_payload = {'panik': panik_text, 'kalm': kalm_text, 'panik2': panik2_text}
panik_img = requests.get('https://luminabot.xyz/api/image/panik-kalm-panik', params=panik_payload)
panik_embed = discord.Embed(title="Damn you so panik bro")
panik_embed.set_image(url=panik_img.url)
await ctx.respond(embed=panik_embed)
#

so i thought i should use discord.File for this task, but it sadly doesnt take image urls

full basin
#

Ah

#

What does panik_image returns. Without .url

fervent cradle
#

like this
<Response [201]>

proud pagoda
#

Since aiohttp is async while requests will be blocking

fervent cradle
proud pagoda
#

Don't embeds accept image urls?

fervent cradle
proud pagoda
#

Then you have to dump the image to some other site

#

And then use the url they give you

fervent cradle
#

oh

proud pagoda
#

Tbh it would just be easier to save to disk, dump the image to a channel, and then retrieve the url from there and send that url

#

And then remove from disk

#

Thats what I usually do

fervent cradle
#

isnt it directly possible to convert the url to cdn.discordapp ones somehow?

proud pagoda
#

I'm pretty sure it has to be sent on Discord first

fervent cradle
proud pagoda
#

Won't heroku give you at least like 10 mb of space though?

fervent cradle
#

github + heroku

proud pagoda
#

If you just delete the image directly after, then you should be fine

proud pagoda
fervent cradle
proud pagoda
#

By the way, do you have a credit card?

fervent cradle
proud pagoda
#

Oh alright

#

Well in a few months, Railway is going to make it possible for students to get verified without a credit card, so you could do that since Railway is a pretty good host

fervent cradle
#

hopefully if they dont demand a github student acc for that

proud pagoda
#

Yeah, cuz now they've made it so that you need to verify urself if you want to host for more than 20 days

proud pagoda
#

But don't you have a student ID?

fervent cradle
#

so its useless

proud pagoda
#

Yeah but I'm pretty sure that it should still work if you have a valid student ID card

fervent cradle
proud pagoda
#

You're welcome

hybrid raft
#

discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: InvalidArgument: Invalid permissions given to keyword arguments.
How to set see channel perm?

fervent cradle
#

Hey how can I sent a button without any label but with an emoji?

hybrid raft
tribal bough
#

how to edit defer message?

fervent cradle
hybrid raft
fervent cradle
#

i had it like

fervent cradle
hybrid raft
fervent cradle
#

i want a custom emoji tho, like from a server

hybrid raft
fervent cradle
#

or are those some kind of default emojis I'm unable tto find

hybrid raft
fervent cradle
#

wdym

delicate jolt
#

Could anyone help please?

hybrid raft
delicate jolt
#
Ignoring exception in on_application_command_error
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.8/site-packages/discord/commands/core.py", line 127, in wrapped
    ret = await coro(arg)
  File "/home/container/.local/lib/python3.8/site-packages/discord/commands/core.py", line 877, in _invoke
    await self.callback(self.cog, ctx, **kwargs)
  File "/home/container/cogs/economy.py", line 60, in search
    await ctx.respond(embed=em, view=SearchView())
TypeError: __init__() missing 1 required positional argument: 'bot'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.8/site-packages/discord/client.py", line 382, in _run_event
    await coro(*args, **kwargs)
  File "/home/container/cogs/economy.py", line 71, in on_application_command_error
    raise error
  File "/home/container/.local/lib/python3.8/site-packages/discord/bot.py", line 992, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "/home/container/.local/lib/python3.8/site-packages/discord/commands/core.py", line 358, in invoke
    await injected(ctx)
  File "/home/container/.local/lib/python3.8/site-packages/discord/commands/core.py", line 135, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: __init__() missing 1 required positional argument: 'bot'```
errant craneBOT
fervent cradle
#

and not like the img i shared

delicate jolt
#

You can use custom emojis

#

Just find an icon website

fervent cradle
#

wdym?

delicate jolt
#

In the buttons

fervent cradle
#

by custom emojis i mean emojis from a discord server

delicate jolt
#

Yes

#

You can

fervent cradle
#

where do i put that?

fervent cradle
delicate jolt
#

I can't remember how you do it

#

But there's the guide

tribal bough
#

how can i edit interaction.response.defer() message

delicate jolt
#

await interaction.edit_original_message("Message" or embed=embed, view=view())

tribal bough
delicate jolt
#

Should do i think atleast... It's what I used

tribal bough
#

oki

fervent cradle
#
class Dropdown(discord.ui.Select):
    def __init__(self, bot_: discord.Bot):
        self.bot = bot_
        options = [
            discord.SelectOption(label="Red",
                                 description="Your favourite colour is red",
                                 emoji="🟥"),
            discord.SelectOption(label="Green",
                                 description="Your favourite colour is green",
                                 emoji="🟩"),
            discord.SelectOption(label="Blue",
                                 description="Your favourite colour is blue",
                                 emoji="🟦"),
        ]
        super().__init__(
            placeholder="Choose your favourite colour...",
            min_values=1,
            max_values=1,
            options=options,
        )

    async def callback(self, interaction: discord.Interaction):
        await interaction.response.send_message(
            f"Your favourite colour is {self.values[0]}")

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


      
        view2 = Dropdown(self.bot)
        self.add_item(view2)

        

@bot.slash_command(guilds=guilds)
async def colour(ctx: discord.ApplicationContext):

    view = DropdownView(bot)
    await ctx.respond("Pick your favourite colour:", view=view)

How would I send the selected colour in the slash command?

silver moat
fervent cradle
#

Not sure how that would make it work

silver moat
fervent cradle
#

Yeah but it can only get it once and not when you change it

silver moat
fervent cradle
silver moat
fervent cradle
silver moat
#

How will you know that you received an interaction to that dropdown?

fervent cradle
silver moat
fervent cradle
silver moat
#

example```py

def check(interaction):
return interaction.user == ctx.author

try:
await bot.wait_for("interaction", check = check, timeout = 60.0)
#do something here
except asyncio.TimeoutError:
print("Timeout!")

fervent cradle
silver moat
fervent cradle
fervent cradle
#

@silver moat I've been having trouble trying to make the condition to only the dropdown interaction but I cant find an attribute to do this

fervent cradle
silver moat
#

pretty sure it is in data

fervent cradle
silver moat
#

if that's what you are asking for

fervent cradle
#

view.children[0].custom_id == interaction.data['custom_id']

#

This works

silver moat
#

ic you mean the one in the view

fervent cradle
#

Yes

#

Ok thank you for all the help!

silver moat
#

?tag ephemeral

obtuse juncoBOT
#

An 'ephemeral' message is one that's only visible to the person who invoked a command. If you ever got a command error with a blue background, this is an example of one.

To do this, set ephemeral=True when you first use an ApplicationContext. (This includes .defer()ing it; the choice of whether a message is ephemeral or not must be made up front. If you .respond() to a deferred message, setting the ephemeral flag at that time will have no effect.)

This is the equivalent of hidden=True if you're coming from interactions.py

meager heron
#

How does one trigger a bulk message delete event?

#

And will on_message_delete still get called if a message was deleted as part of a bulk delete?

silver moat
gleaming falcon
#

Anyone know if interactions in ephemeral messages are explicitly limited to 15 mins, or am I doing something wrong?

rare ice
fervent cradle
#

I have a command that sends an aiohttp request. How would I make it retry the whole command if the response is an error?

violet adder
#

how can i edit the message instead of sending a new one with drop down menu?

copper pasture
#

Can i edit a persistent view after a restart?

dawn gyro
#

Any idea why on_presence_update rechecks the same user? even when they haven't changed their presence

silver moat
tranquil pivot
#

Can bots have both buttons and dropdowns on the same embed?

silver moat
#

a message can have 5 rows. each rows can have 5 components at max. dropdowns take an entire row while 5 button are required to fill a row completely

tranquil pivot
#

That sounds like plenty thanks

silver moat
#

np

gleaming falcon
cyan quail
#

same with interaction tokens

gleaming falcon
violet adder
#

followed a tutorial for dropdown menu but i get this error NameError: name 'MySelectView' is not defined

proud pagoda
#

Also the error is saying that you haven't declared the class MySelectView

violet adder
errant craneBOT
full basin
#

Define your view outside your cog class

violet adder
#

sad tysm

near hollow
# silver moat yes
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In 7: Application command names must be unique```
#

When I try to reload a cog then resync slash commands

#

The name is unique I am 100% positive

silver moat
#

sync 0 commands then sync all commands

near hollow
#

so await bot.sync_commands(commands=0)?

#

Tried doing commands=None but same error

cyan quail
#

commands=[]?

near hollow
#

Ah alright

near hollow
#
    await bot.sync_commands(commands=[])
    await bot.sync_commands()
waxen whale
calm plume
#

Quick Question

#

is this folder setup good for storing members and guilds

#
Guild DBs
   Server1
       Members.db
       Guild.db
   Server2
       Members.db
       Guild.db
#

if it isn't how may i improve it?

#

i wanna keep it very organised

#

that can hold over millions of servers

#

im also not asking for help in sql but more in organisation of the data

#

i also know i asked a similar question in the past but making 2 database files members.db or guilds.db will make it very messy and can't be tracked a lot

rugged lantern
#

yes i'm sure your bot will be added to 10%+ of the total amount of servers there are on discord

calm plume
#

i wanna organise it so it doesn't hurt performances, is easy to navigate through, doens't make a bunch of files

rugged lantern
#

why would you have a separate db for each server

#

tables/rows/columns exist for a reason

#

assuming it is sql

calm plume
#

with some custom data

storm geode
#

my solution : json

calm plume
#

but any way to organise

calm plume
#

but il use it still

#

not tho often

unkempt owl
grizzled sentinel
calm plume
#

but this doesn't make it organised and u basically have to use filters and stuff to search through

grizzled sentinel
#

Yes, but the filters are quite simple. It is far better than having a different table for even 100 servers.

Its kind of like how in coding you use a function instead of repeating code a bunch of times. You should use the same table instead of storing the same format of information in a bunch of different places.

calm plume
#

ik that tho the filters are simple

#

bc its the search bar really

#

il try ur method

solid agate
#

I know there is an event that gets triggered on a ban on_member_ban
Is there a similar event for timeouts?

rocky stump
#

When making a cog, is it possible to pass through a parameter when I use load_extension into the setup function of the cog?

#

or does that not make sense?

#

As a work around I've been placing custom attributes in my bot using bot.whatever and accessing the .whatever in my cog that way

gleaming falcon
#

Slightly advanced, but is anyone familiar with the default_member_permissions that is passable to SlashCommandGroup? Not entirely sure what syntax goes here..

SlashCommandGroup("mygroup", "My Group", default_member_permissions=discord.Permissions(moderate_members=True)
``` ?

Or is this completely not working until perms v2 is released?
vestal raven
#
Ignoring exception in command userinfo:
Traceback (most recent call last):
  File "C:\Users\Kulkarni\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\commands\core.py", line 127, in wrapped
    ret = await coro(arg)
  File "C:\Users\Kulkarni\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\commands\core.py", line 877, in _invoke
    await self.callback(self.cog, ctx, **kwargs)
  File "F:\Coding related files\Discord Bot\night_sky_cogs\info_commands.py", line 133, in slash_userinfo
    permissions = dict(user.guild_permissions)
  File "C:\Users\Kulkarni\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\member.py", line 632, in guild_permissions
    base.value |= r.permissions.value
AttributeError: 'NoneType' object has no attribute 'permissions'

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

Traceback (most recent call last):
  File "C:\Users\Kulkarni\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\bot.py", line 992, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "C:\Users\Kulkarni\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\commands\core.py", line 358, in invoke
    await injected(ctx)
  File "C:\Users\Kulkarni\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\commands\core.py", line 135, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: 'NoneType' object has no attribute 'permissions'

I tried reading it, but couldn't understand where exactly the error is

cyan quail
cyan quail
vestal raven
#

give me a website for sending code through. 😅

cyan quail
#

you can just paste it here by wrapping it in ```py
```py
code here
```

or discord will turn it into a file if it's too long
vestal raven
#

ohk wait

silver moat
#

?tag codeblock

obtuse juncoBOT
#

Please put your code in a code block:
```py
Here is your Code
```

That makes reading code in Discord a lot easier:

print("This is an example.")
cyan quail
#

close enough

vestal raven
#
@commands.slash_command(name="userinfo", description="Get information on a user", guild_only=True)
@commands.cooldown(1, 10, commands.BucketType.member)
async def slash_userinfo(
    self,
    ctx:discord.ApplicationContext,
    user: discord.Option(discord.Member or int, "Enter the user to get the info about", default=None)
):
    if user is None:
        user = ctx.author
    if isinstance(user, int):
        try:
            user = await self.bot.fetch_user(user)
        except: return await ctx.respond("provide a proper user id", ephemeral=True)
    
    permissions = dict(user.guild_permissions)
    key_perms = []
    voice_perms = []
    other = []

    all_perms = []
    for i in permissions:
        if permissions[i] is True:
            all_perms.append(i)

    for i in all_perms:
        try:
            if i in self.key_permissions:
                key_perms.append(self.permission_values[i])
            elif i in self.voice_channel_permissions:
                voice_perms.append(self.permission_values[i])
            else:
                other.append(self.permission_values[i])
        except: None
    
    joined_at = f"{discord.utils.format_dt(user.joined_at, 'F')} ({discord.utils.format_dt(user.joined_at, 'R')})"        
    created_at = f"{discord.utils.format_dt(user.created_at, 'F')} ({discord.utils.format_dt(user.created_at, 'R')})"
    
    embed = discord.Embed(title=f"Info about {user}", color=discord.Color.blurple())
    embed.add_field(name="Joined Server at", value=joined_at, inline=False)
    embed.add_field(name="Account Created at", value=created_at, inline=False)
    
    if len(key_perms) != 0: embed.add_field(name="Key Permissions", value=", ".join(key_perms), inline=False)
    
    if len(voice_perms) != 0:embed.add_field(name="Voice Permissions", value=", ".join(voice_perms), inline=False)
    
    
    embed.add_field(name="Other Permissions", value=", ".join(other), inline=False)
    try: embed.add_field(name="Avatar", value=user.avatar.url) ; embed.set_thumbnail(url=user.avatar.url)
    except: None
    

    await ctx.respond(embed=embed)
cyan quail
silver moat
#

wouldn't entering an int let discord/pycord convert it to a user/member object?

#

if the type-hinted is a user.

cyan quail
#

it should but they've done something weird with their option type and they have the code there anyway

#

pretty sure that'll break it on discord's end and force it to string if that actually goes through

#

wait no it'll just ignore int, ignore me

vestal raven
cyan quail
#

hm for some reason you have NoneTypes in the member's roles... what version are you on?

cyan quail
#

is it still broken after restarts?

vestal raven
vestal raven
cyan quail
#

what happens if you print user.roles before that line

vestal raven
#

wait

gleaming falcon
cyan quail
#

correct, this is a discord limitation

vestal raven
#

I removed the or int from Option as well, still no difference

cyan quail
#

uhhh you sure? there's definitely something there

#

i think i know the issue but just need to check what the roles are

silver moat
vestal raven
cyan quail
#

the option is technically fine anyway since it'll only parse member with the syntax you used

cyan quail
vestal raven
#

I'll try something ig wait

gleaming falcon
cyan quail
#

that's how yes

#

just comment out the @slash_command decorator

#

oh ok

silver moat
#

ig not loading that cog should also work

cyan quail
#

hmmm last i checked options did update automatically but i guess i never bothered to upgrade to 2.0

gleaming falcon
#

Sweet, there we go. I had to de-register the command to get the default_member_permissions to work. Thanks all.
Hopefully some inline way of updating them will come.

cyan quail
#

did they by chance have 0 roles?

vestal raven
#

This time, tested with my account which had 3 roles

#

Also, I printed the new lines between the [None] and error by myself

cyan quail
#

did you override intents?

vestal raven
#

Wait, there is an intent for the roles of the user?

cyan quail
#

well the related intent would be on by default

#

...or i guess member intent

#

which is priveliged

vestal raven
#

well, I have this in the main file


intents = discord.Intents()
intents.guild_messages = True
intents.guild_reactions = True
intents.message_content = True
intents.members = True
intents.voice_states = True
cyan quail
#

ah that's the problem

vestal raven
#

uhh

cyan quail
#

i hope anyway

#

try py intents = discord.Intents.all() intents.presences = False

lusty minnow
#

yo has anyone gotten the voice record to actually work?

lusty minnow
#

been trying for a week and it keeps doing this

#

infinite loop

cyan quail
#

nice

vestal raven
#

thanks 👍

gleaming falcon
#

What's the best/most elegant way to determine if a context-passed channel (i.e. the channel a user invoked a command from) is a Thread or not? I don't see any direct helpers.

There's instanceof, of course, but was also thinking of testing whether channel.parent existed. Curious if there's something even easier I'm not considering.

silver moat
#

ghost unread?

gleaming falcon
cyan quail
#

you could just check if "thread" is in str(channel.type) since there's 3 different thread types

silver moat
#

b!rtfm channeltype

dire spadeBOT
# silver moat b!rtfm channeltype

I couldn't find a documentation with the name channeltype! Maybe you used to command wrong? Correct Usage: <prefix>rtfm <docs> [<term>] (eg. b!rtfm py cool)
List of Documentations you can search:
python
pycord
discord.py
yarsaw
nextcord
disnake

silver moat
#

b!rtfm pyc channeltype

drifting current
#

hey, whats a fast way to update my discord.py bot to pycord without changing too much code?
As it has about 10k lines :/

#

however it doesn’t work without changing stuff it seems

silver moat
#

what errors are there?

drifting current
#

I can’t even find where the error comes from but once I start the program the bot starts running and my event loops also start running but I repeatedly get the error that „List index is out of range“
like every second

#

I know this error means that it has to do with my code but it didn’t happen with discord py

#

so I guess I am missing something?

#

It doesn’t say in which line the error is as it prints it as a string and not Exception

#

Is it possible that somewhere, where I try to get a list of members for example that pycord can’t do that or I need to change stuff so it can?

silver moat
drifting current
#

I use many discord py libraries but all of them are in pycord I assume?

#

cuz I uninstalled discord py

#

and installed pycord

#

and didn’t get any import errors

silver moat
#

like discord-components etc.

drifting current
#

discord-webhooks

silver moat
#

just that?

drifting current
#

umm gimme a sec I’ll go trough the files

drifting current
#

and discord.utils and .ext but that not what u mean ig

silver moat
#

could you send the whole error?

drifting current
#

it’s literally only

#

Error: List index out of range

#

wait maybe..

silver moat
#

is that part of an except clause?

drifting current
#

yes

#

it seems

#

maybe it’s in msg.embeds[0]

#

is that possible? cuz I read smth about embdeds from messages

#

yeah it’s the only place where I use index of a list

#

so it has issues getting the embed of a message

silver moat
drifting current
#

just got another Exception that ClientUsee has no attribute avatar_url

drifting current
silver moat
drifting current
#

oh…

#

I always did

silver moat
#

?tag intents

obtuse juncoBOT
#
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)
drifting current
#

ah I need to activate all of them??

silver moat
#

if you need them

drifting current
#

cuz in the past I did discord.Intents.default()

#

and everything worked

#

ig I need to do everything separately now

silver moat
#

what does your bot do?

drifting current
#

the issues is when it gets a message by its id and tries to split its content and embed

silver moat
#

which is None i think

drifting current
#

yeah it doesn’t return the message content

#

bc of the issue with the intents u addressed I assume

silver moat
#

intents are a required field in the discord api. before it was optional.

drifting current
#

does it have any disadvantages if I just activate all?

#

also the ones I don’t need

silver moat
#

yeah, because some events will be dispatched that you don't need like on_typing

drifting current
#

oh

silver moat
#

enable which ever ones you need

drifting current
#

what does this enforced mean?

silver moat
drifting current
#

ah alright no issue then

#

ty very much

silver moat
#

np

drifting current
#

what is this again :/

silver moat
#

enable the switch

drifting current
#

I have all enable on discord dev portal

silver moat
#

wait a bit then try again

#

and click save changes

#

:)

drifting current
#

just needs some patience I assume xD

#

btw can I combine prefix commands and / commands in the same code?

silver moat
#

sure, bridge commands

drifting current
#

cuz I saw that u need to assign a different value to client

#

when u wanna use / commands

silver moat
rugged lantern
#

client in 2022 lawl

silver moat
#

this should be helpful

drifting current
#

oke will read

silver moat
drifting current
#

the issue is with this intent:
intents.message_content = True

#

this causes the error

#

and my bot is in 2 servers in total so thats not the issue

cyan quail
drifting current
#

python 3.9
pycord 2.0

fervent cradle
#

Hi I have a string (#cbe053)
how can I create a role with that color?
role = await ctx.guild.create_role(name="Eigene Farbe", color=the_string_above, mentionable=False)
I tried this, does not work

cyan quail
drifting current
#

yep

fervent cradle
cyan quail
fervent cradle
#

and without the #?

cyan quail
#

yes

fervent cradle
#

ok ima replace it then

cyan quail
drifting current
#

wym exactly

cyan quail
#

i guess the lines involved in defining your bot

drifting current
# cyan quail i guess the lines involved in defining your bot

intents = discord.Intents()
intents.guilds = True
intents.members = True
intents.messages = True
intents.guild_messages = True
intents.reactions = True
intents.guild_reactions = True
intents.message_content = True



client = commands.Bot(command_prefix="%", intents=intents)

..
..

client.run(token)
fervent cradle
drifting current
#

I removed the last intent (intents.message_content = True) and it worked

cyan quail
#

for one i'd recommend shortening it to py intents = discord.Intents.default() intents.members = True intents.message_content = True
but hmmm

#

you definitely enabled it on the portal for the correct bot right?

drifting current
cyan quail
#

hmmm

#

i don't think it's meant to take additional time but maybe check back in an hour? For now i'd leave message_content = False in the code, but keep it enabled on portal

drifting current
#

alright will try

silver moat
solid agate
#

I figured as much, just wanted to make sure.

#

It wouldn't be the first, nor the last time, I would've missed something obvious 😛

drifting current
cyan quail
#

strange, idk maybe check with discord support...? I can't see any reason the intent wouldn't work
for now, if you do want message content to work without then try discord.http.API_VERSION = 9 after importing

#

but if im not mistaken this would be blocked next month?

drifting current
cyan quail
#

well that's in general yeah, but api v9 currently lets you use message content without specifying it in code; im not sure if this will still apply after the changes

silver moat
silver moat
#

Are you sure it's being enabled on the correct bot?

drifting current
#

yep 100%

#

Could it be bc the bot is quarantined

silver moat
#

is the bot quarantined?

drifting current
#

yeah

#

for no reason tho

silver moat
drifting current
#

I asked them to review it

#

no reply in 2 months

cyan quail
#

well yeah that's exactly the problem

#

if it's only in two servers then why not just move to a new app

drifting current
#

well true :` || laziness ||

silver moat
#

literally 8 button clicks :p

cyan quail
#

you can just copy the permissions over with some loops

drifting current
#

nah the only issue is to go into my host and change it there xD

#

thx anyways tho will do it

celest lichen
#

anyone know why i might be getting this warning? i have pycord installed

#

the import below is asyncio btw

silver moat
#

py-cord?

rugged lantern
drifting current
celest lichen
silver moat
#

did you pip install py-cord?

celest lichen
#

oh, no i did pip install pycord. is that a different library?? damn

silver moat
#

the namespace is still discord

celest lichen
#

odd, installed py-cord and it's still there

silver moat
#

restart code editor :)

celest lichen
#

perfect!! thank you

silver moat
#

yw

drifting current
#

Well the intents work

#

but

#
AttributeError: 'ClientUser' object has no attribute 'avatar_url'
#

why does it not have avatar_url anymore :`

cyan quail
#

yeah if you're moving from dpy then best read the entire migrating page

silver moat
#

I forgot to cover intents in that migration thing...

cyan quail
#

oops

drifting current
#

Do i get compensation for it not being there?

#

damn thats so many changes that (if u wanna use / commands) it is more worthwhile to make a new bot and host both on the same token and keep the old one on discord py

cyan quail
#

eh migrating is relatively straightforward as long as you go through your code carefully

#

not nearly as many changes as the v1 jump anyway

drifting current
#

there is no way I can go trough all that

#

I dont understand what are the reasons for some changes

silver moat
#

half of them aren't even applicable