#Basic Pycord Help

1 messages · Page 42 of 1

warm linden
#

async-timeout 4.0.3
discord-webhook 1.3.0
dnspython 2.6.1
jishaku 2.5.2
py-cord 2.5.0
pymongo 4.7.3
typing_extensions 4.12.2

#

thing is thats true tbh

#

i'll prob end up removing that

#

i used to make it send something every couple mins now its hours

#

so i might jus change it tbh

sage tendon
#

you can just do that with a task

warm linden
#

yeah

#

i'll edit it soon need to switch all my cmds to slash rn

warm linden
sage tendon
#

no idea what that is

warm linden
#

i think it was you that told me bout this

#

do i just simply do await interaction.defer() in order to not get the application failed to respond error?

sage tendon
#

in a command, its ctx.defer()

warm linden
sage tendon
#

yea

#

then that

warm linden
lapis dock
sage tendon
#

show your button code

warm linden
warm linden
rugged lodgeBOT
sage tendon
#

its interaction.response.defer

warm linden
#

ohh appreciate it

warm linden
#

AttributeError: module 'discord' has no attribute 'Bot'

#

what am i doing wrong?

warm linden
#

pip list ^

weary meteor
#

for the Option type, how can i make the autocomplete grab all the roles in a discord server? like Option(discord.Guild.roles) or something like that

fresh sierra
#

Use only
input_type = discord.Role

lofty parcel
fresh sierra
fresh sierra
lapis dock
shell radish
dapper hamlet
#

can you use an emoji as a thumbnail in an embed or nah?

sage tendon
#

if you have an image of it :)

warm linden
fresh sierra
#

with pleasure

mystic token
#

Any way to make select menus remember selection after editing message?

fresh sierra
mystic token
#

it reverts to placeholder but i would like it to retain what the user selected

fresh sierra
#

ooo

#

so no its not possible if you edit the view / response to the interaction

#

but why do you want to do that

#

there is maybe another solution

mystic token
#

i know i can do it by selecting a default value when making a new select menu

#

but i wanted a simpler way lol

#

anyways thanks 👍

pliant shell
#

I may have run into a strange problem... i'm trying to get the bot to connect to the same vc i'm in, but it doesn't and also there's no error in console?

voice = ctx.author.voice
vc = await voice.channel.connect()

it get's the voice object as i can print it and see the channel i'm in, but it just doesn't connect! I have all intents turned on, it has the permissions to join, but nothing happens... Can someone give me a fresh perspective on this?

errant trout
#

what pycord version

pliant shell
#

2.5.0

fresh sierra
#

do you have pycnl

pliant shell
#

Oh crap i think i know the problem now xD If i recall correctly you used to have to download additional voice package? I haven't coded for some time and also had a fresh reinstall. Is it still the case?

fresh sierra
#

PyNaCl

pliant shell
#

Yep it works now! Thanks Luma!

fresh sierra
#

with pleasure

pliant shell
#

Now to just get it to play mp3 files xD fun

warm linden
#

can someone help me please - i can't get my head around on how to do this:

            category = discord.utils.get(interaction.guild.categories, id=1249341737973846036)
            cito = discord.utils.get(category.text_channels, name=f"application-{interaction.user.name}")

            if cito != None:
                return await interaction.response.send_message("You already have a **Staff Application** ticket open!", ephemeral=True)
#

it doesn't work - no erros

errant trout
warm linden
#

wrong thing

#

one sec

#

there

fresh sierra
#

If it’s None then it’s normal

warm linden
#

but thing is there is a channel

errant trout
#

Why don't you just use find on guild.text_channels

#

Or do you have to limit category

#

(Also this would break immediately if a user changes their name)

warm linden
#

tbh i dont have to limit

warm linden
#

but for some reason it didn't want to work when i used a db for it

errant trout
#

Idk but in the long run you basically need a db for ticket systems

warm linden
#

yeah i do

warm linden
#

i do understand the error but i can't figure out a way to check if ther user is in the db

errant trout
#

so just print the result and figure out what to do instead

warm linden
errant trout
#

nice

quartz umbra
#

Hi, can someone help me out with the error: py 404 - Unknown Interaction

#

i know its caused by my bot taking too long to respond

#

so I tried out some code to immediately reply with a temporary message, then edit that response later, though the later edit is not working, it appears

#

Here's the relevant code:```py

Respond with a temporary message to keep the interaction valid

response = await ctx.respond("Working on it!", ephemeral=True)

...Do stuff that takes a while...

embed = discord.Embed(
    color=discord.Color.from_rgb(75, 255, 75),
    title="Success",
    description=f"You have successfully granted {user.name} the {rank} tier in {kit}.",
)
await ctx.respond("", embed=embed, ephemeral=True)```
sage tendon
#

thats not how it works

#

use await ctx.defer() to tell discord to wait longer

#

that must be ephemeral if your response is, too

quartz umbra
#

so at the top, I write await ctx.defer(ephemeral=True)?

little cobalt
#

yes

sage tendon
#

yes, and remove the temp response

quartz umbra
#

Ok, I'll try that out now and update on whether it works, thanks

sage tendon
#

also just remove the "" in the respond, its not needed

quartz umbra
#

will do!

quartz umbra
warm linden
#

can someone help me fix my say cmd? it doesn't let me create a new line

warm linden
sage tendon
#

and describe what you actually mean

warm linden
#

say i want to send a text:

Hey

How are you

sage tendon
#

not possible with options

warm linden
#

it'll send out: Hey How are you

#

ohh

fresh sierra
#

with prefix it work idk for the other

#

maybe you can add a logic

#

like if the use put \n it goes into the line

sage tendon
#

also you forgot to actually send the message to the selected channel

#

and you can just pass the message variable directly, no need to make it an f String with nothing else in it

#

and you don't need the * argument for slash commands

#

and you don't need to pass the name= kwarg, it automatically takes the function name as command name

little cobalt
sage tendon
#

too slow smh

little cobalt
#

oh xd

#

My messages are loading really slow

upper flint
#

I have a question. We can download pycord either by typing pip install py-cord or pip install py-cord[speed]. Latter variant claims to install some additional speed up packages. What are they? How exactly do they speed up bot?

sage tendon
#

I don't think it makes a noticeable difference unless your bot is huge
I think it just installs some more packages that you can use to do stuff faster, p sure it doesn't use them itself

upper flint
#

I see, ok. Then it's probably useless for me

#

Thought this will speed up pycord w/o me needing to do anything to the bot itself

sage tendon
#

Meh tbh the biggest thing affecting most bots is latency, and db or api shit

#

and you can't really make that faster except by using async

upper flint
#

True

warm linden
#

do the buttons always stop working if bot goes offline then come back on?

sage tendon
#

unless you use persistent views, yes

harsh bloom
#

What is the async timeout limit for pycord? Some of my responses that take 9-10 minutes are not returned

#

i send http post requests, the responses take 9-10 minutes

#

Used aiohttp for sending requests

harsh bloom
#

It's slow takes time to give a response

#

The bot forgets to fetch and give a response if it takes too long

sage tendon
#

your own API?

harsh bloom
#

Yep

sage tendon
#

then.. make it respond faster?

harsh bloom
#

The endpoint works I've tested it

lofty parcel
#

Why does your api takes 10 minutes to respond?...

harsh bloom
sage tendon
#

there's free APIs for that..

#

use the groq api

harsh bloom
#

Lmao

sage tendon
#

not lmao

#

what you are doing is lmao

harsh bloom
#

Can pycord increase the wait time? Is that possible?
I do not own the full stack I'm asking
I take your opinion and understand it

sage tendon
#

ctx.defer() extends it to 15m i think

#

but your solution is just... kinda bad, just use the API, you get a responds within 2-3 seconds at most every time

harsh bloom
sage tendon
#

its free

#

i use it myself

#

learn to take advice if you ask for solutions

harsh bloom
#

Yeah I'll check

errant trout
#

i mean you absolutely can get away with 10 minutes on a request

#

kinda silly, better to improve the time, but nothing really stopping you

lapis dock
warm linden
warm linden
lapis dock
rugged lodgeBOT
#

Here's the persistent example.

lapis dock
#

You have to tell the bot what custom_id the component is so it can listen for interactions from discord matching that ID

warm linden
#

ahhh

#

thanks i'll look into it

sage tendon
warm linden
#

would this have to be in the cog where my buttons are?

class PersistentViewBot(commands.Bot):
    def __init__(self):
        intents = discord.Intents.default()
        intents.message_content = True
        super().__init__(command_prefix=commands.when_mentioned_or(","), intents=intents)
        self.persistent_views_added = False

    async def on_ready(self):
        if not self.persistent_views_added:
            self.add_view(PersistentView())
            self.persistent_views_added = True

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

bot = PersistentViewBot()
sage tendon
#

Ideally you don't have your views in a cog at all :)

#

(the class definition)

sage tendon
warm linden
sage tendon
#

for example I just have a views folder where I define all my views

#

with an init file so I can do from views import xview

quiet nimbus
#

ModuleNotFoundError: No module named 'discord'

#

i'm using a venv and i reinstalled py-cord

#

nvm it worked with python main.py and not python3 main.py, not sure why

warm linden
sonic ferry
#

does anyone know if its possible to have a response send silent messages?

#

so basically have a slash command respond with a silent message

fresh sierra
#

If you mean that does not ping anything yes you can

#

Or invisible u can to

sonic ferry
#

i cant figure out how to do it with the ApplicationContext class though

little cobalt
sonic ferry
#

right but i want to ping people manually

#

by @ing them

fresh sierra
#

.rtfm allowedmention

sonic ferry
#

thank you!

#

works perfectly

#

dont know how i didnt see that tbh

sage tendon
harsh bloom
#

is it possible to defer prefix commands? My bot replies whenever it gets a ping.
I see that you require context to use defer, since I used an event on_message, I did not get a context.

frail basin
#

The only thing defer does is it gives you more time to respond to an interaction before it errors out.

harsh bloom
frail basin
harsh bloom
#

no im not

#

I checked the docs, I did not find a way to make the bot reply whenever it gets a ping (although I think it's possible?)

frail basin
frail basin
harsh bloom
frail basin
#

Ah

#

you are looking for this then:

fresh sierra
#

You don’t have a time thing using prefix

harsh bloom
fresh sierra
#

Defer is only for interaction so Dw about that

rugged lodgeBOT
fresh sierra
#

(No that’s for prefix definition only

harsh bloom
#

hmm I think defer is primarily for slash commands

little cobalt
#

you have to respond in 3 seconds at interactions or you gonna get an error and with defer you can increase that time to 15 minutes

#

that does not exist at prefix commands

glossy latch
#

hey who can help me

#

?

little cobalt
glossy latch
lofty parcel
signal trench
#

is it possible to mention a sub command

#

and if yes how can we ?

little cobalt
signal trench
#

let's say i have this

#

settings = SlashCommandGroup("settings", "Settings Commands")

#

and the comamnd is

@settings.command(name="set_meme_channel", description="Set channel for memes")
    async def set_meme_channel(
        self,
        ctx: discord.ApplicationContext,
        channel: discord.TextChannel,
        frequency: int,
    ):
        meme_config[str(ctx.guild.id)] = {
            "channel_id": channel.id,
            "frequency": frequency,
        }
        save_json("MEME.json", meme_config)

        embed = discord.Embed(
            title="Meme Channel Set",
            description=f"MEME Channel : {channel.mention} \nFrequency : {frequency} Minutes",
            color=0x00FF00,
        )

        await ctx.respond(embed=embed)
#

how can i mention set_mem_channel command ?

little cobalt
little cobalt
#

set_mem_channel.name would return the name

#

;3

signal trench
#

{self.bot.get_application_command('info').mention}

#

i used to mention the names like this

#

ohh i get it

#

so it will be like

little cobalt
signal trench
#

{self.bot.get_application_command('set_mem_channel.name').mention}

#

oh ic thanks sir

little cobalt
#

I wonder what you gonna get from it xd

signal trench
#

and learning

sage tendon
#

@harsh bloom just use the groq API dude

#

no one wants to wait 10m for a single command

#

you're making the experience worse for everyone involved for no reason

glossy latch
fresh sierra
#

Whats groq api

harsh bloom
sage tendon
sage tendon
harsh bloom
sage tendon
#

i mean, groq never takes more than 3 seconds max
so you have another slow api?

harsh bloom
#

let me rephrase pain - "can't I know how to get output from a slow api using pycord"

frail ocean
#

Is there a way to get the count on connected members in a voice channel

sage tendon
#

the solution to having a slow api is

  1. change the api if you can
  2. use aiohttp, never use requests
    ideally, both
frail ocean
#

hey toothy

#

long not seen

sage tendon
#

hi

sage tendon
#

oh its you again, the guy allergic to the docs

#

I never touched voice in my life, and i was able to find it within 5 seconds TOTAL in the docs
Please, use the docs

frail ocean
#

I found the user limit

sage tendon
#

there's a finite amount of attributes

#

read them all

frail ocean
#

Found

fresh sierra
#

.rtfm voice.channel.members

frail ocean
#

Okay another question

sly karmaBOT
#

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

frail ocean
#
            try:
                await ctx.author.voice.channel.connect()
            except:```
#

Except will not be triggered

rugged lodgeBOT
sage tendon
#

they literally said they found it already

#

and dont spoonfeed them, its proven not to help

sage tendon
#

them in particular

fresh sierra
frail ocean
#

Bro

#

U wanna troll me?

#

What is that for help xD

fresh sierra
#

Are u talking to me ?

frail ocean
#

yes

fresh sierra
#

Have u already install pynacl

#

@frail ocean did the install of pynacl solve ur case ?

frail ocean
#

No

#

I already installed it months ago

fresh sierra
#

And the Connect doesn’t work ?

quartz umbra
#

Hi, can somebody please explain the difference between display_name and name? I don't quite get it

#

Is it that the name is just your username while display_name will be your nick, if you have one, but if you don't, your username?

sage tendon
#

name is their unique username

quartz umbra
lapis dock
#

.tag pomelo

sly karmaBOT
#

Before Pomelo- Versions 2.4.1 and before

member.name          -> username
member.nick          -> guild nick name
member.display_name  -> member.nick OR member.name

After Pomelo- Versions py-cord-dev 2.5.0 and up

member.name          -> username
member.global_name   -> global display name (global nick name)
member.nick          -> guild nick name
member.display_name  -> member.nick OR member.global_name OR member.name
lapis dock
#

for more info ^

quartz umbra
#

I see, but I'm getting another error with this:```py
await ctx.respond(embed=embed)

I get the error:```py
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: HTTPException: 400 Bad Request (error code: 40060): Interaction has already been acknowledged.```
Now, this doesn't cause the message to not be sent, but I would appreciate why it occurs, in case it causes some issues in the future
sage tendon
#

show more of your code

hoary cradle
#

are polls supported in pycord?

lapis dock
#

Via the pending PR

hoary cradle
#

thanks 👍

lapis dock
umbral gazelle
#

Why bot sometime raise this error?
Application Command raised an exception: AttributeError: 'MessageInteraction' object has no attribute 'locale'

sage tendon
#

i mean, the error is quite clear

umbral gazelle
#

Explain please.

sage tendon
#

read?

#

you are trying to access .locale of a messageinteraction object

#

that doesnt exist

signal trench
#

can i build out a music bot which is compactable with pycord ? if so which module to use any references or so

#

like i am never successful with python to build a music bot

safe obsidian
#

got a question, if I have a bot that is making views within threads, will the view overwrite itself on each new thread view that is created?
example: I have a yes button and no button inside a discord thread. I make a second thread with the same buttons and push the same view name to that new thread, will it kill the old buttons/overwrite them?

loud kayak
sly karmaBOT
# signal trench can i build out a music bot which is compactable with pycord ? if so which modul...
class YouTubeTrack_fix(wavelink.YouTubeTrack):
    @classmethod
    async def convert(cls, _, ctx: discord.ApplicationContext, argument:str):
        return await super().convert(ctx, argument)

@slash_command()
async def play(self, ctx: discord.ApplicationContext, search: YouTubeTrack_fix):
    
    if not ctx.voice_client:
        vc: wavelink.Player = await ctx.author.voice.channel.connect(
            cls=wavelink.Player
        )
    else:
        vc: wavelink.Player = ctx.voice_client

    await vc.play(search)
    await ctx.respond(f'{search.title}')

FIXED

TypeError: SearchableTrack.convert() takes 3 positional arguments but 4 were given
signal trench
wintry zephyr
#

Can you create a cog and have it and its commands fall under a slash command group?

tidal vessel
wintry zephyr
#

I'd like the cog itself to be a subcommand of a parent SlashCommandGroup

#

Essentially, I'd like all my commands to adhere to the following structure heirachy:

/{basegroup} {cogname} {commands-inside-cog}

#

The basegroup would be universal, so ideally I'd define that in my main python file and then pass the context into the cog - having some issues passing the context in and accessing the value inside the cog class

fresh sierra
wintry zephyr
#

This looks promising - does the parent group have to be defined inside a cog, or could you define it elsewhere?

fresh sierra
wintry zephyr
#

Perfect, thats exactly the functionality I was hoping for originally - much easier to write a string than pass the context through classes

fresh sierra
#

Hello, looking at the doc, i saw

Context = Union[BridgeExtContext, BridgeApplicationContext]

to get the union of both, since im using a custom context, i decide to do the same :

However when using it as typehint i got that error :

2024-06-11 06:30:28 [WARNING] : Failed to load extension Slashs.Anime.smile: Extension 'Slashs.Anime.smile' raised an error: TypeError: Invalid usage of typing.Union

    @subcommand(f"bot")
    @bridge.bridge_command()
    async def exec(self, ctx: LumabotContext, code: str):
#

class Lumabot_App_Context(bridge.BridgeApplicationContext):
    ...
    
class Lumabot_Prefix_Context(bridge.BridgeExtContext):
    ...
    
LumabotContext = typing.Union[Lumabot_App_Context, Lumabot_Prefix_Context]
#

and im also getting the good context

    async def get_context(self, message: discord.Message, cls=Lumabot_Prefix_Context):
        return await super().get_context(message, cls=cls)
    
    async def get_application_context(self, interaction: discord.Interaction, cls=Lumabot_App_Context):
        return await super().get_application_context(interaction, cls=cls)
echo wraith
#

Was wondering, is it possible to get title and description of link embeds and whether a link was embedded directly from discord or do I need to check manually with something the open graph meta tags

echo wraith
fresh sierra
#

so if you have a link of a message

#

just access to the embed of the message

echo wraith
#

👍 thanks

umbral gazelle
umbral gazelle
fresh sierra
#

Doesnt

umbral gazelle
#

Now I understand...

errant trout
fresh sierra
#

mb then

errant trout
#

basically everything on ctx is a shortcut

fresh sierra
#

thanks for that

#

then for prefix command

#

how can you get the local since there is no interaction ?

#

i have my reponse, you dont

errant trout
#

locale is exclusive to interactions

fresh sierra
#

Yep, when bridge will be supported I will have to do some workaround

flat wind
#

is there a way to start the new shard when a bot is joining much servers without having to restart the full bot ?

fresh sierra
#

Not possible I think because share are start when the bot begin to run

fresh sierra
flat wind
#

okay but if there is an event listener for shard ready, there is no way to tell the bot to start the new shard provided by discord ?
like on all on_guild_join events, a verification of the shard number is sent to discord, and if the number is different from the actual one, just start the new shard

#

same for on_guild_remove

fresh sierra
#

or maybe autoshardedbot handle that itself but i dont think

flat wind
fresh sierra
#

there is a method shard connect

#

maybe if you edit the bot.shard_count while running to a bigger value

#

and then do for shard_id in shard_count get_shard then shard.connect

fresh sierra
flat wind
#

Yeah I will see, thanks

fresh sierra
#

too short to thanks me, first look if it works ;)

wintry zephyr
fresh sierra
#

There is other way to do that with some file / folder but it’s way harder and I never did that

wintry zephyr
#

So would it be like below?

@subcommand("command")
@subcommand("cog")
@command.command(name="XX")
async def blah(self, ctx):
   await ctx.respond("Hi")
#

This is within my cog's class

fresh sierra
#

First you create ur group
group = discord.SlashCommandGroup(name="group")
subgroup = group.create_subgroup(name="sub")
And then you do
@subcommand("group sub")

#

Im on phone so its normal for the missing codeblock +other thing

wintry zephyr
#

Ok ok, I get it. Let me try that out

wintry zephyr
#

bot.py

import discord
from discord.commands import SlashCommandGroup
from discord.ext import commands
from pycord.multicog import Bot

owner_id = 0000000000000

intents = discord.Intents.default()
bot = Bot(auto_sync_commands=True, intents=intents, owner_id=owner_id)

cmds = SlashCommandGroup("basegroup")

@cmds.command(name="ping", description="Pong!")
async def ping(ctx):
    await ctx.respond("Pong! 🏓")

# Load default cogs
modules.cog.setup(bot)

# Start the bot
bot.run(token="XXX")

modules.cog.py

import discord
from discord.commands import SlashCommandGroup
from discord.ext import commands

from pycord.multicog import Bot
from pycord.multicog import subcommand

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

    subcommand_group = SlashCommandGroup(name="cog")

    @subcommand("basegroup cog")
    @commands.slash_command(name="XX")
    async def blah(self, ctx: discord.ApplicationContext):
        await ctx.respond("Hi")
    
def setup(bot: discord.Bot):
    bot.add_cog(Cogs(bot))
#

Getting the following error message when running

#

I'd wager its probably the way I'm defining the subgroup in the bottom code block, however, I get a similar issue when creating the subgroup off the cmds object context

fresh sierra
#

You need to define the group cog as subgroup of basegroup

#

Not create a new group

wintry zephyr
#

If I drop the subcommand_group = SlashCommandGroup(name="cog") in modules.cog.py and add cmds.create_subgroup("cog") below cmds = SlashCommandGroup("basegroup") in bot.py I get the same thing

fresh sierra
#

And to do that it should be on the same file for the creation of group and subgroup

#

Can you show me the updated cog ?

#

And the decorator should be just upper the @commands

#

Not with a different identetion

wintry zephyr
#

bot.py

import discord
from discord.commands import SlashCommandGroup
from discord.ext import commands
from pycord.multicog import Bot

owner_id = 0000000000000

intents = discord.Intents.default()
bot = Bot(auto_sync_commands=True, intents=intents, owner_id=owner_id)

cmds = SlashCommandGroup("basegroup")
cmds.create_subgroup("cog")

@cmds.command(name="ping", description="Pong!")
async def ping(ctx):
    await ctx.respond("Pong! 🏓")

# Load default cogs
modules.cog.setup(bot)

# Start the bot
bot.run(token="XXX")

modules.cog.py

import discord
from discord.commands import SlashCommandGroup
from discord.ext import commands

from pycord.multicog import Bot
from pycord.multicog import subcommand

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

    @subcommand("basegroup cog")
    @commands.slash_command(name="XX")
    async def blah(self, ctx: discord.ApplicationContext):
        await ctx.respond("Hi")
    
def setup(bot: discord.Bot):
    bot.add_cog(Cogs(bot))
fresh sierra
#

Also you should not change the type hint to Bot, continue to use the commands.Bot

fresh sierra
#

Im on phone so maybe

#

But it doesn’t appear

#

Can you do a screenshot ?

wintry zephyr
#

The ping command isn't what I'm concerned about - I haven't used @subcommand with that

fresh sierra
#

Im talking for the XX commands

wintry zephyr
fresh sierra
#

It looks good, when you run that specific code what does it return ?

wintry zephyr
fresh sierra
#

This is when ur run the code ?

wintry zephyr
#

yep

#

it doesn't actually initialise - fails when trying to load the cog

fresh sierra
#

Can you show me how u load the cog ?

wintry zephyr
#

In bot.py I call modules.cogs.setup(bot) which runs the setup function at the bottom of the modules.cog.py screenshot

#

Prior to trying to implement all this subcommand stuff, this all worked fine and it would launch

lofty parcel
#

Did you read the error

fresh sierra
#

?tag paste

limber wagonBOT
#

Please copy and paste your code here. This makes it easier for everyone helping you.

fresh sierra
#

Can you put all ur file there

wintry zephyr
#

Yes, however, I don't think I would want it to be independent (if I'm properly understanding what independent actually means)

fresh sierra
#

I go at my house and then check from my Mac

fresh sierra
wintry zephyr
#

Appreciate the help

fresh sierra
#

try and see if it fix it

wintry zephyr
#

ok, lets give that a go - for my own understanding, what's the difference?

fresh sierra
#

basically

wintry zephyr
#

Was I meant to replace the code in bot.py or modules.cog.py sorry?

fresh sierra
#

by removing the modes.cog.setup(bot)

#

and also, remove the import modules

#

because to do modules.cog.py , you need to import it, and import it will run the cog before running the creation of group

#

and because of that u have this error

wintry zephyr
#

Ok, I've made those changes but I'm still getting the same error

#

my folder structure is like this:

|  src
|  - bot.py
|  - modules/
|    - cog.py
fresh sierra
#

the load_exention should be

#

src.modules.cog i guess

wintry zephyr
#

I'm referencing it correctly here yeah?

fresh sierra
#

is that an extension ?

#

let me try ur code

#

let me try

#

can you do a pip freeze

#

and give it me what it return ?

wintry zephyr
#
aiohttp==3.9.5
aiosignal==1.3.1
attrs==23.2.0
frozenlist==1.4.1
idna==3.7
multidict==6.0.5
py-cord==2.5.0
pycord-multicog==2.1.1
python-dotenv==1.0.1
yarl==1.9.4
fresh sierra
#

here how you can do

#

you apprenlty cant define group in main

#

so by putting the init you can put everything

wintry zephyr
#

ok, so basically what we're seeing is it loads cogs to the command list before the commands we define loosely in non-cog classes, and as a result we aren't actually initialising our command groups before the cog gets loaded

wintry zephyr
#

Everything is now working as intended, thanks for your help @fresh sierra

fresh sierra
#

with pleasure ;)

quartz umbra
#

Hello, I am encountering a strange issue with my bot. Though it appears online, and the console shows no sign of it going offline, after using one slash command, the bot's slash commands cannot be found again? I do not know why this could be happening

lofty parcel
#

Uhh, make sure you're not running multiple instances.

fresh sierra
#

maybe he did find a solution since

quartz umbra
quartz umbra
quartz umbra
sage tendon
#

have you considered using cogs

quartz umbra
sage tendon
#

Yea, have you looked at your bot file? its huge

#

well okay 300 lines isnt huge but in the scope of a discord bot (main.py), it is

quartz umbra
sage tendon
#

no, thats just unnecessary

#

use cogs

#

one command per file is too much

cogs typically make you put several similar ones into one file, which is well enough

quartz umbra
#

thanks, I'll look into that, but my original issue of the slash commands seemingly stopping to exist continues to perplex me

sage tendon
#

also uh

#

consider adding .DS_store to your gitignore, lol

sage tendon
#

just really make sure your bot isnt running twice, reset the token if you want to make double sure

fresh sierra
deft kestrel
fresh sierra
deft kestrel
#

this is it

sage tendon
#

if not, remove the self

deft kestrel
#

Yeah, it's in a cog

sage tendon
#

also, don't use has_permissions with slash commands

deft kestrel
#

I added in logging when settings are changed

#

and what replacement should I use for has_permissions

sage tendon
#

the @analytics? well, then try to find what it touches and make it not break stuff

sage tendon
deft kestrel
sage tendon
#

so you changed nothing about the code of the command?

deft kestrel
#

Nothing above the async def, only the contents of the function

sage tendon
#

and the traceback shows that command being the issue?

deft kestrel
#

No, the screenshot I posted is the whole log, alongside a ready message

#

I have it set on debug mode

fresh sierra
deft kestrel
#

Ok I tried it again without changing a single thing in the code and now it works

#

interesting

deft kestrel
#

How do I accept an emoji as an option of a command?

#

discord.Emoji in option type doesn't work properly

#

It only works with custom emojis, but I want the default ones too

#

Please reply ping to me, I'm going to go sleep now

rain dune
#

is there anyway object for guilds like we have for members for easy choosing of members

like

user: Option(discord.Member, "Mention the user you want to send", required=True)
lofty parcel
#

You'd have to create an autocomplete yourself

tidal vessel
deft kestrel
#

This parameter causes the warning above, unless a custom emoji is supplied

tidal vessel
deft kestrel
#

I want both

little cobalt
#

I dont even really know if its possible to do the stuff with the emojis

fresh sierra
deft kestrel
sage tendon
#

discord.Emoji is a valid command option??

little cobalt
#

I know I tried that at some point and it was not working

sage tendon
#

it would definitely be very new to me

lapis dock
#

According to ddev docs it is not

deft kestrel
#

If I do str(emoji) it does :heart: for ❤️ and ![pycord](https://cdn.discordapp.com/emojis/1063211537008955495.webp?size=128 "pycord") for pycord, right

sage tendon
#

i mean yea but im still flabbergasted about discord.Emoji as an option type

#

are you very sure it doesnt just fall back to str

deft kestrel
#

it works with custom emojis

#

Im going to try PartialEmoji as it should work with unicode ones, there's is_unicode_emoji()

sage tendon
#

emoji is not a slashcommandoptiontype

#

yea, neither emoji nor partialemoji is

#

apparently it still works and is passed as a emoji, but thats undocumented then
i really doubt this is intended behaviour

sage tendon
#

i tested it

#

yea, i just tested it

#

its a complete mess, undocumented, probably unintended, and doesnt work properly

atomic fern
#
Ignoring exception in on_message
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "/home/yon/.local/lib/python3.10/site-packages/discord/client.py", line 378, in _run_event
    await coro(*args, **kwargs)
  File "/home/yon/test/point/cogs/Points.py", line 242, in on_message
    await message.add_reaction("✅ ")
  File "/home/yon/.local/lib/python3.10/site-packages/discord/http.py", line 283, in request
    async with self.__session.request(
  File "/home/yon/.local/lib/python3.10/site-packages/aiohttp/client.py", line 1167, in __aenter__
    self._resp = await self._coro
File "/home/yon/.local/lib/python3.10/site-packages/aiohttp/client.py", line 562, in _request
    conn = await self._connector.connect(
  File "/home/yon/.local/lib/python3.10/site-packages/aiohttp/connector.py", line 540, in connect
    proto = await self._create_connection(req, traces, timeout)
  File "/home/yon/.local/lib/python3.10/site-packages/aiohttp/connector.py", line 901, in _create_connection
    _, proto = await self._create_direct_connection(req, traces, timeout)
  File "/home/yon/.local/lib/python3.10/site-packages/aiohttp/connector.py", line 1169, in _create_direct_connection
    raise ClientConnectorError(req.connection_key, exc) from exc
aiohttp.client_exceptions.ClientConnectorError: Cannot connect to host discord.com:443 ssl:default [Temporary failur
e in name resolution]

what cause this error? other bot in my vps doesn't have this issue, it's always happen when using Message.add_reaction()

#

and happened everyday

#

and how i handle automatically?

fresh sierra
#

Like an internet error

#

Maybe try to reinstall pycord bit I don’t rhino it will resolve it

atomic fern
deft kestrel
#

I settled on using this as my code

rain dune
#

how do i check if a button is clicked or not
?

view = discord.ui.View()
            yes_button = discord.ui.Button(label='Yes', style=discord.ButtonStyle.green)

added this to my embed

lofty parcel
rain dune
#

alright thanks

sage tendon
deft kestrel
#

It was similar in discord.py

sage tendon
#

ctx.respond

deft kestrel
#

Before I switched to this library

#

I haven't studied it too much but this seems to work so I used it, but now I'm going to replace all ctx.response.send_message() with ctx.respond() using a regex

sage tendon
#

regex?

#

have you heard of "find and replace"

deft kestrel
#

woah there's a lot

sage tendon
deft kestrel
#

It's a bit messy I know

errant trout
#

all Converters and their related classes are acceptable types, giving parity to prefix commands even when limited to string

sage tendon
#

oki

#

good to know

#

but i wish vanilla emojis worked then

errant trout
#

it'd be nice, but unicode emojis are just considered strings; the Emoji class is targetted towards custom emojis

deft kestrel
#

50% of the time when commands are run it gives 404 unknown interaction but then other times it doesnt?

maiden bloom
#

Anyone know why my slash command with the @has_permissions(administrator=True) decorator triggers false negatives?

sage tendon
#

because you should not use that decorator with slash commands

errant trout
sage tendon
#

you should always use default_permissions

errant trout
#

not necessarily

maiden bloom
# errant trout wdym

I haven’t been able to replicate it, but I’ve had several users say they have admin but that error message gets triggered anyway. Then after they wait a while and run the command again with the same permissions, it works. They could be wrong but wanted to check here first just in case

sage tendon
errant trout
#

are you sure it's not a different error and perhaps you're try-catching too broadly?

errant trout
# sage tendon in 95% of cases

they're not equivalent, default_permissions is freely controllable by other members in the guild while has_permissions is not.

#

ultimately it depends on your goal.

maiden bloom
#

This is how I’m handling it:


@toggle_integrated_ticketing.error
    async def toggle_integrated_ticketing_error(self, ctx, error):
        utilities = self.bot.get_cog("Utilities")
        if isinstance(error, MissingPermissions):
            await utilities.send_command_requires_admin_error_msg(ctx)
sage tendon
#

but default permissions hides the command which is what people generally try / want

errant trout
#

right, but the point is if you don't want it useable at all then has_permissions is objectively safer.

sage tendon
#

either only default, or both.

errant trout
#

the error has a missing_permissions attribute which is a list of what failed

#

it would be easier if some pattern could be found, im guessing cache is weird about it but not sure

maiden bloom
#

Definitely, I’d just rather not fill up a log file or display a messy error to the user. For the purpose of fixing this I could though

errant trout
#

yeah just some quiet logging is fine

sage tendon
#

either way, consider switching to default_permissions unless you have reasons not to
because typically you also wanna hide admin commands from non admins

maiden bloom
#

I’m fine with non admins seeing the commands. I only have the admin requirement set because the commands change the guild’s configuration for the bot. I’d rather have users see the error message and realize they need admin than not see the command entirely and come complaining in the support server

sage tendon
#

thats... a unique reason lol

#

how would they even know it exists when they never see it lolw

maiden bloom
#

Tutorials and documentation. I see your point, that's just not the way I'd rather implement it

nova epoch
#

I've made a cog to implement CaptchaVerification into my bot. When running the bot, I get the following error:
discord.errors.ExtensionFailed: Extension 'cogs.CaptchaVerification' raised an error: AttributeError: 'AutoShardedBot' object has no attribute 'add_command'
I have looked into this with the docs, and my syntax is how the docs said it should be:

for filename in os.listdir('./cogs'):
    if filename.endswith('.py'):
        extName = filename[:-3]
        bot.load_extension(f'cogs.{extName}')```

Anyone got any ideas on causes?
#

This is what is raising the exception btw: File "C:\Users\there\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0\LocalCache\local-packages\Python311\site-packages\discord\cog.py", line 562, in _inject

little cobalt
nova epoch
#

You're about to get the text equivalent of a zip bomb.

#

okay nevermind its 1800 characters too long for me to send

#

Okay there we go ^

little cobalt
#

mhm

candid ore
#

Does anyone know why I get this error while trying to install the turtle library?

nova epoch
#

it would need to be py except ValueError as ve: <code>

little cobalt
#

or any old windows versions?

candid ore
#

I do

nova epoch
#

It's a very old copy of Win10, most likely a compatibility issue. What version of python is it?

candid ore
#

3.8

little cobalt
#

@nova epoch at how many servers is your bot?

nova epoch
#

One at the moment. Hoping to scale it in the future though.

little cobalt
#

how did you define the bot?

nova epoch
#
intents = discord.Intents.default()
intents.members = True
intents.messages = True
intents.message_content = True
intents.guilds = True
intents.guild_messages = True

bot = discord.AutoShardedBot(intents=intents)```
little cobalt
#

if your bot is not at 2500+ server you dont need AutoShardedBot

fresh sierra
little cobalt
#

just use discord.Bot()

fresh sierra
#

(It will automatically pop a shard)

nova epoch
#

I did have discord.Bot, I only changed it to see if it would sort the error. It did not :(

nova epoch
fresh sierra
#

What ur issue I didn’t really understand

fresh sierra
candid ore
#

guys I'm still learning so just wanna know how often do u use RegEx and do I have to know all the syntaxes?

nova epoch
#

I find regex to be quite useful, but it depends with what you're making.
No, you can use tools online to generate regex expressions without having to know the syntax. I would suggest learning some basic syntax for pattern recognition though.

candid ore
#

ok, tnx

sage tendon
#

Rule #2, avoid regex if at all possible

edgy nest
sage tendon
#

i know

lofty parcel
#

So add_command doesn't exist in discord.Bot

fresh totem
#

GMGM!


    call = SlashCommandGroup("postcall", "Publish Post Commands", guild_ids=adminServer)

    # DeFi Updatez
    @call.command()
    async def defi_update(self, ctx: discord.ApplicationContext):
        await ctx.respond('<3')

rookie question, but where can I add the description* for the slash command defi_update?

little cobalt
#

;3

sage tendon
#

that, or as a docstring using """ this syntax """ right under the function definition

fresh sierra
#

Idk this will work for everything, ik for prefix it’s considered has short_doc or brief and not description (in my memory)
So description= should be better

sage tendon
#

man idk but thats not a bridge command to me

#

and it should work just fine on bridge too

fresh sierra
#

Still a thing to consider because we never know

sage tendon
#

completely unnecessary

fresh sierra
#

Nah

#

But u can think whatever you want tbh

lofty parcel
#

You should use description=

sage tendon
#

meh, doesnt matter

nova epoch
nova epoch
#

That's what I'm using, but that invokes bot.add_command:

for filename in os.listdir('./cogs'):
    if filename.endswith('.py'):
        extName = filename[:-3]
        bot.load_extension(f'cogs.{extName}')
        print(f"Loaded cog: '{extName}'")```
fresh sierra
#

it should tell u the issue if there is one

#

you can do
bot.load_extension("cogs", recursive = True)

#

and it should trigger the setup more at the end of ur cog

#

can you show me how does look ur cog ?

nova epoch
#

The setup is literally py def setup(bot): bot.add_cog(VerificationCog(bot))

#

The actual cog is way too long to put here

sage tendon
nova epoch
sage tendon
#

ah

fresh sierra
nova epoch
#

Nope

fresh sierra
#

can you show me how does look one of ur command ?

sage tendon
#

well, i definitely saw that error before

fresh sierra
#

just the command definition

nova epoch
#

The command itself is this

#
@commands.command(name="verify", description="Begin your verification attempt.")
async def verify(self, ctx):
    verify_url = f"https://{api_url}/?discord_id={ctx.author.id}&site_key={self.turnstile_site_key}"
    embed = discord.Embed(
        title="Human Verification",
        description=f"Please verify you are human by clicking the link below and completing the Turnstile challenge:\n[Verify Here]({verify_url})",
        color=discord.Color.blue()
    )
    embed.add_field(name="Note", value="Powered by Cloudflare Turnstile Enterprise")
    view = discord.ui.View()
    view.add_item(VerifyButton(self, ctx.author.id))
    await ctx.send(embed=embed, view=view, ephemeral=True)```
fresh sierra
#

this is for prefix

#

@commands.command

#

that ur issue

#

you should use @discord.slash_command

nova epoch
#

bruhhhhhhhhhhhhh

#

im gonna die istg

sage tendon
#

no, in cogs it's @discord.slash_command

nova epoch
#

i thought they were aliases 😭

fresh sierra
sage tendon
#

also, why not make a proper view subclass with the button you want

nova epoch
#

like this button?

#
class VerifyButton(discord.ui.Button):
    def __init__(self, cog, user_id):
        super().__init__(label='Submit Verification Token', style=discord.ButtonStyle.primary)
        self.cog = cog
        self.user_id = user_id

    async def callback(self, interaction: discord.Interaction):
        await interaction.response.send_modal(VerificationModal(self.cog, self.user_id))```
fresh sierra
#

well you can just do

#

instead of
view = discord.ui.View()
view.add_item(VerifyButton(self, ctx.author.id))
do
await ctx.send(embed=embed, view=VerifyButton(self, ctx.author.id), ephemeral=True)

sage tendon
#

im almost certain thats not how views work

nova epoch
#

the view works fine (to my knowledge)

#

i guess we';; see

#

IT HASNT ERRORED THIS TIME GUYS

#

1m ill test

#

yea ok i broke it gimme a min]

fresh sierra
#

mb i didnt see it was a discord.ui.Button and not view

maiden bloom
dull iron
#

hi, I made a silly webhook generator to imitate friends on our server like:

@bot.command(description="Imite un utilisateur")
async def imite(ctx, user: discord.User, *, message: str):
    avatar = await user.avatar.read()
    webhook = await ctx.channel.create_webhook(name=user.nick, avatar=avatar)
    await webhook.send(content=message)
    await webhook.delete()

how can I setup the color of the nickname, it would be better but i can't find anything on the doc or internet about it 😦

#

please telle me there's a way

errant trout
vital bramble
#

I have a quick intent question:
I did this (and enabled the intents in the dev portal)

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

But now, when I receive an on_message event, I don't get the Message.content. But when I fetch messages with e.g. Channel.history, I do get the content? Why is that? Did I set the intents right?

#

It's also weird, because a few days before it did already work using exactly this setup...

fresh sierra
#

.tag intents

sly karmaBOT
#

Pycord Docs - Intents
Discord API Docs - Gateway Intents

import discord
from discord.ext import commands

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

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

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

# Apply intents when creating your bot
bot = commands.Bot(prefix="?", intents=intents)
fresh sierra
torn spire
#

Don't you need .guilds and .messages ?

shell radish
torn spire
#

ah

vital bramble
shell radish
#

Can confirm that the code is correct

vital bramble
#

oh nvm

#

they actually still had an older version where there was only default() set.

hoary cradle
#

im reloading my cog which adds my new print statement but doesn't remove my old print statement, i don't receive any errors what could the issue be?

frail basin
#

We'll need more context

#

Both old and new code get executed?

hoary cradle
#

it seems so

#

its within a loop

fresh sierra
umbral gazelle
#

Is it possible to make my bot use all CPU threads instead of just one?

torn spire
#

Or if your bot has a lot of guilds, you can shard the bot

sly karmaBOT
#

Tag not found.

#

Tag not found.

umbral gazelle
sage tendon
#

go on

umbral gazelle
umbral gazelle
sage tendon
#

also, isn't that event meant for servers that basically go offline?

umbral gazelle
sage tendon
#

well, what are you checking with that event?
its really not something you need typically because guilds rarely ever go offline
your case seems more like you want to check all guilds once the bot starts

umbral gazelle
sage tendon
#

then just iterate through all guilds

#

you're kind of absuing that event lol

#

just use bot.guilds and iterate through it, with asyncio.sleep possibly so you can regulate the speed

umbral gazelle
sage tendon
#

async db calls?

umbral gazelle
sage tendon
#

can you show your code if it isnt too much?

#

because, for real, your CPU usage shouldn't go to absolutely 100% for a minute

umbral gazelle
sage tendon
#

well then, do it when you can

fresh sierra
torn spire
sage tendon
#

but really, you should just iterate through bot.guilds

sage tendon
torn spire
#

Does it just use a separate websocket connection only?

sage tendon
#

almost certainly

torn spire
#

In djs there was a hacky way to run a single bot on multiple servers iirc

#

Does pycord not have anything like that?

sage tendon
#

think someone said you can, but you have to manually specify shard ids per machine

torn spire
#

Yeah you have to do the same in djs

fresh sierra
#

Yes that possible with cluster

sage tendon
#

what is create_task?

#

Also I mean
You iterate through every guild, and potentially every of those guilds' members
That is... a lot

tiny fractal
#

Is there anything against using fetch over gets methods. Wouldn’t be called in loops or anything. Just hate how discord client cache is crap and I can never see the mention names in my moderation embeds.

umbral gazelle
sage tendon
#

mentions in embeds don't resolve properly, thats just a discord bug

#

But generally, avoid fetch if you can

tiny fractal
#

Roger

sage tendon
#

ping them in the content, thats how i do it

#

that way, if you leave the embed ping there, that'll also work if the normal ping resolves fine

umbral gazelle
#

How can I improve speed?

sage tendon
#

yea, well, why do you need to iterate through so much on every bot start

#

thats the first thing you could work on lol

#

and again, if time isnt critical, iterate through bot.guilds and use asyncio.sleep to regulate sleep

fresh sierra
#

Why aren’t u using some loop ?

#

It will delay the process and not put everything in one time

#

(Task.loop)

#

So you can do 3 différents loops one for giveaway one for voice one for autorole

umbral gazelle
fresh sierra
daring grove
#

How would i save attachments to a specific folder?

little cobalt
daring grove
#
    async def download_attachments(channel):
        for message in channel.history(limit=None):
            for attachment in message.attachments:
                save_path = os.path.join(parts_directory, attachment.filename)
                await attachment.save(save_path)
#

I thought this would save the attachment to my parts_directory

little cobalt
#

lemme get the attachment stuff, 1 sec.

daring grove
#

Cheers

little cobalt
#

take a look at that

fresh totem
#

Do we have something like on_raw_reaction for Buttons such that the buttons responds even if the instance is re-run..

little cobalt
fresh totem
#

yes, can we make it work for buttons?

#

functionality of on_raw_reaction but for UI Buttons.

little cobalt
#

the event is called on_interaction

fresh totem
#

yes, but let's say I re run the bot - the same button no longer responds.

#

I want it to be able to 'revive' the button so it continues to respond - just like reaction emojis do in on_raw_reactions

sage tendon
#

you need persistent views for that

#

and you dont need to listen for any event for that

shadow bear
#

Does PyCord support user apps yet?

sage tendon
#

not on stable, no

shadow bear
#

I run off of master anyway

#

Well I pin to specific commits, I'm not a complete maniac

sage tendon
#

master should have it

shell radish
#

there’s a pull request, just waiting for discord to finalize it ##2409

rugged lodgeBOT
#

No GitHub issue or pull request mentions (ex. #123) found.

lofty parcel
#

I thought it was gonna be ephemeral

sage tendon
#

same

fresh totem
echo wraith
#

Can I ratelimit button presses

shell radish
#

yes

echo wraith
fresh totem
#

Hi. I'm trying to create permission overwrite for specific roles when creating a category

Code:

    moderatorsRole = await guild._fetch_role(ModeratorsID)

        # 1v1 Cateogry
    perm1v1Challenge = {
        guild.default_role: discord.PermissionOverwrite(send_messages=False, view_channel=False),
        judgeRole: discord.PermissionOverwrite(read_messages=True, send_messages=True, view_channel=True),
        moderatorsRole: discord.PermissionOverwrite(read_messages=True, send_messages=True, view_channel=True),
        guild.me: discord.PermissionOverwrite(read_messages=True, send_messages=True, view_channel=True)}

    category1: discord.CategoryChannel = await guild.create_category(name="🟢┊Ongoing 1v1 Challenges", overwrites=perm1v1Challenge, position=0)```

**Error:**

```    category1: discord.CategoryChannel = await guild.create_category(name="🟢┊Ongoing 1v1 Challenges", overwrites=perm1v1Challenge, position=0)
                                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

    data = await self._create_channel(
                 ^^^^^^^^^^^^^^^^^^^^^

    "id": target.id,
          ^^^^^^^^^```
#

What am I doing wrong? when I remove judgeRole and moderatorRole overwrites, it works fine.

sage tendon
#

why guild._fetch_role

#

also, you should first try getting the role anyway, it should be cached regardless
only fetch when necessary

fresh totem
fresh totem
sage tendon
#

what if you print judgeRole

little cobalt
#

so, what did you get?

fresh totem
#

prints the role name

👩‍⚖️ Judge

#

should have printed the object, correct?

sage tendon
#

also, you dont have to typehint everything
we aren't in java, and the return type of that function is already categorychannel

sage tendon
sage tendon
#

plus excessive typehints make your code less readable IMO
the only place you usually need typehints are function parameters

fresh totem
#

yeah, got rid of it, it's the only unnecessary typehint in the snippet..

sage tendon
#

:>

#

also, can you send the full error here?

#

like the entire traceback

fresh totem
#
    judgeRole = guild.get_role(JudgeRoleID)
    moderatorsRole = guild.get_role(ModeratorsID)

        # 1v1 Cateogry
    perm1v1Challenge = {
        guild.default_role: discord.PermissionOverwrite(send_messages=False, view_channel=False),
        judgeRole: discord.PermissionOverwrite(read_messages=True, send_messages=True, view_channel=True),
        moderatorsRole: discord.PermissionOverwrite(read_messages=True, send_messages=True, view_channel=True),
        guild.me: discord.PermissionOverwrite(read_messages=True, send_messages=True, view_channel=True)}

    category1 = await guild.create_category(name="🟢┊Ongoing 1v1 Challenges", overwrites=perm1v1Challenge, position=0)```

Ignoring exception in command setup:
Traceback (most recent call last):

ret = await coro(arg)
      ^^^^^^^^^^^^^^^

await self.callback(ctx, **kwargs)

category1 = await guild.create_category(name="🟢┊Ongoing 1v1 Challenges", overwrites=perm1v1Challenge, position=0)
                                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

data = await self._create_channel(
             ^^^^^^^^^^^^^^^^^^^^^

"id": target.id,
      ^^^^^^^^^

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

sage tendon
#

can you print both judgerole and moderatorsrole

#

im a bit confused on that error ngl

fresh totem
#

ohhh f that's where I messed up

sage tendon
#

what was it

#

wrong moderator id?

fresh totem
#

I never gave the right moderatorID

#

🤦‍♂️

sage tendon
#

:>

little cobalt
#

quick reminder

#

.get_x

sly karmaBOT
#

Any function that starts with get_ in Py-cord is retrieving the related object from your bots cache. If the object is not in the bots cache the get_ method will return None. Because of this behavior you should check if the get_x method is None and if it is use the fetch_x method.

Why Is Using fetch_ Without Using get_ First Bad?
The fetch_ method makes a call to the discord API. This API call is unneeded if you already have the information. It will also make your command take longer because it will have to send and than wait for a response from the discord API. It will also contribute to the discord APIs global rate limit of 50 requests per second.

What Is Cache?
The cache is a temporary storage inside your bot. It holds many objects from members to messages. When you restart your bot the cache will be empty. When the cache is full it will delete older objects to make space for the new objects.

fresh totem
sage tendon
#

np

sage tendon
#

you rarely need fetch

#

i dont have a single fetch in my bot

little cobalt
#

I still added it

sage tendon
#

yeye its good

little cobalt
#

just to be safe

fresh totem
#

I have a lot of fetches - would it be considered inefficient?

little cobalt
#

I do it like that

sage tendon
fresh sierra
#

you can do
guild = client.get_guild or await guild.fetch

little cobalt
#

so I can import it

sage tendon
#

costs a tiny amount of time and is, as i said, generally unnecessary

fresh sierra
#

if you want to have a thing smaller

fresh sierra
sage tendon
#

unless your bot is in a huge amount of servers with a billion members, your bot has everything cached

#

and fetch just ignores cache

little cobalt
fresh sierra
little cobalt
#

I even got both bots sub classed

fresh totem
little cobalt
sage tendon
little cobalt
fresh sierra
#

and it will type hint using ur class

sage tendon
#

you dont even know if thats a method of their bot subclass

#

could just be in a util file

fresh sierra
weary meteor
#

hey all, how can i purge every message in a channel except for the first message that was sent

fresh sierra
sage tendon
#

set the limit to the message count of the channel - 1
i assume there wont be a lot of messages
if yes, do it like luma said

fresh sierra
#
for channel in guild.channels:
    if channel.id == ctx.channel.id:
      continue
    ur renew here
weary meteor
#

i cant delete the channel, i need to jus delete all the messages except for the first one, when you say -1, do you mean ctx.channel.purge(limit=-1)?

fresh sierra
#

if there is a lot of message in ur channel

#

it will be difficult

#

i dont think there is any limit arg

weary meteor
#

there probably wont be over 500

fresh sierra
#

you should do so await channel.history(limit=-1) if i understood thooty and then delete all message

#

but purge can only delete 100 by 100

weary meteor
#

.history(limit=-1) returns an empty list

sage tendon
#

thats...

#

not how that works

little cobalt
#

lol

weary meteor
#

then what exactly were u askng me to do

sage tendon
#

still the same thing

#

but thats not how you count messages

weary meteor
#

so how do i in a performant manner

little cobalt
#

uh, do it one time and after that count every message which is getting send. I dont really know a better idea of it

#

if you gonna do it, you have to go from old to new or you gonna get a error soon

#

so its not gonna work with new to old if they are to many messages

sage tendon
#

also, just very generally, what are you trying to achieve

weary meteor
#

literally just delete every message in a channel except the first one, its sort of like a private channel but the first message is important so i dont want to delete that one but the rest can be deleted

sage tendon
#

yea i got that lol
but like, whats the use case

weary meteor
#

to just clear out the channel, sorta like how most utils bots have a !purge command

sage tendon
#

but why do you need to do it so frequently whats the point

little cobalt
#

I would instead safe the channel settings and delete/create the channel

weary meteor
sage tendon
#

knowing the actual point usually helps people find solutions for their odd problems

weary meteor
#

well there you have it, the only solution i need is to delete every message except for the first one that was sent in the channel

sage tendon
#

-w-

#

forget it

fresh sierra
#

role.is_integration return None even for the interagration of a bot

#

is that just me that dont know how to use it or its a bug

fresh sierra
#

What is the rate limit for the route : /channels/{channel_id}/webhooks"
Handled under the bucket "1251652749834194955:None:/channels/{channel_id}/webhooks"

fresh sierra
#

and same how many time can we edti webhooks and in how many time

ivory beacon
#

is there any way get the slash command name from message ?

#

/profile

#

like this slash command

sage tendon
#

ctx.command

#

docs are your friend

sage tendon
#

or do you mean in an on_message event that catches a slash command interaction

fresh sierra
#

you can still do the same ig

#

since you can get the context from a message

#

or that only for prefix ?

sage tendon
#

well there is message.interaction.data which is a dict of the interaction data the docs dont further specify

fresh sierra
#

well

#
@bot.event
async def on_message(message: discord.Message):
    if message.interaction:
      ctx = await bot.get_application_context(message.interaction)
      ctx.command.name
sage tendon
#

ah

fresh sierra
little cobalt
#

lol

#

why

sage tendon
#

well, it wont work for any other bot's messages

#

i guess

little cobalt
#

you could use on_interaction for it

sage tendon
#

depends on what they need really :> @ivory beacon

fresh sierra
ivory beacon
#

but i can't find any idea

fresh sierra
#

ctx.orignal_message

sage tendon
#

message.embeds

#

lol

little cobalt
#

its a message at the end

#

^

ivory beacon
#

like title is depend on user pets name
description isn't showing pet isn't prestiged (i mean 0)

sage tendon
ivory beacon
fresh sierra
#

why ?

sage tendon
ivory beacon
sage tendon
ivory beacon
fresh sierra
fresh sierra
sage tendon
#

and.. permission for what lol

ivory beacon
sage tendon
#

its not forbidden to literally read what the bot posts lmfao

ivory beacon
sage tendon
#

its literally public

#

if they didnt want the world to read it they shouldn't publicly post it

ivory beacon
#

pets care

sage tendon
ivory beacon
sage tendon
#

print it and check

ivory beacon
#

ok

ivory beacon
sage tendon
#

dict* :)

ivory beacon
#

ahh thanks:)

sage tendon
#

does it have the command name?

ivory beacon
#

yes

#
{'user': {'username': 'dipdey', 'public_flags': 4194560, 'id': '833972562210979891', 'global_name': 'D1P', 'discriminator': '0', 'clan': None, 'avatar_decoration_data': {'sku_id': '1154896005045694555', 'asset': 'a_c7e1751e8122f1b475cb3006966fb28c'}, 'avatar': 'f4482aef993c6c6757bf645edb690693'}, 'type': 2, 'name': 'info bot', 'id': '1251860422252826634'}
#

ofc different command, but it has command name

ivory beacon
#

type:2 ?

sage tendon
#

the type of the interaction

ivory beacon
sage tendon
#

user commands, message commands, slash commands

#

button presses

ivory beacon
#

thanks mate

sage tendon
#

np

fresh sierra
#
Task was destroyed but it is pending!
task: <Task pending name='pycord: on_ready' coro=<Client._run_event() running at /home/container/.local/lib/python3.11/site-packages/discord/client.py:400> wait_for=<Future pending cb=[Task.task_wakeup()]>>
#

Appear when im loading my but and doing a command, any idea ?

cyan prism
#

how do cogs work generally

#

I don't fully understand the concept

little cobalt
cyan prism
#

just a regular bot with add_cog() stuff?

little cobalt
#

That is my main file

cyan prism
#

heh environment file

#

nice

little cobalt
#

I usually use json or yaml

cyan prism
little cobalt
cyan prism
#

oh also where do the cogs go

little cobalt
little cobalt
cyan prism
#

you don't need to specify them manually and can even organise them into categories

little cobalt
sage tendon
#

lol my discord didnt scroll down despite me hitting esc and trying to scroll

#

now it did

#

wtf

sage tendon
little cobalt
sage tendon
fresh sierra
#

Nah