#Basic Pycord Help

1 messages ยท Page 53 of 1

real glacier
#

the thing is im trying to make it as a slash cmd

errant trout
#

well... you might be trying, but your cog is creating prefix commands

#

you're probably using the wrong decorator

real glacier
#

ToT

real glacier
#

its ok, i figured it out now c:

real glacier
#

i want to all to below @pagetest.command() so i can call a var

sage tendon
#

No, that makes no sense

#

without def you don't have a function

fresh sierra
#

Anyone to explain me the point of the mock, is that to test the code before the bot run that ?

sage tendon
#

it's just unit testing stuff

#

Google it

echo wraith
#

Can I defer modal interactions?

sage tendon
#

no

echo wraith
#

that's sad

#

now I'm going to cry

sage tendon
#

if you mean sending the modal

#

If you mean submitting it, no idea

echo wraith
flat wind
#

Hello !
How can I get my own slash commands ID to mention them in another commands ?

echo wraith
#

.rtfm discord.SlashCommand.mention

sly karmaBOT
flat wind
# echo wraith .rtfm discord.SlashCommand.mention

yes but how can I get all the others commands from one ?
I mean... from the /help command, I would like to mention the /ping command.
How do I get the mention for /ping command from the /help command ?

rugged lodgeBOT
flat wind
#

I precise that they are in cogs

echo wraith
#

what does atomic exactly do in add_roles?

sage tendon
#

whether it's done all at once or one at a time I think

flat wind
#

thanks

flat wind
sage tendon
#

it does

quartz umbra
#

Hi so, I had a question. Whenever my bot goes offline, all previous views sent become permanently unfunctional, i.e. I need to resend the same msg when the bot goes online again. Is there any way to fix this? Or is the onnly way to store the message ids of these, then resend them in on_ready()?

rugged lodgeBOT
#

Here's the persistent example.

echo wraith
#

it is kind of what you said with messages ids

#

check the example above out

echo wraith
#

Feel dumb asking this, but any reason why on_member_join would simply not fire?
I have member intents enabled, and other events (i.e. on_ready) in the same cog do in fact fire.

sage tendon
#

regular member joining?

echo wraith
#

yeah

#
    @commands.Cog.listener()
    async def on_member_join(self, member: discord.Member):
        logger.info("Member joined")
        if member.bot:
            return
        await member.add_roles(self.add_role)
        try:
            await member.send(self.config["welcome_dm"].format(member))
        except discord.Forbidden:
            logger.warning(f"Failed to send welcome DM to {member.display_name}")
sage tendon
#

show intents

echo wraith
#

ok it is intents

#

but wierd

echo wraith
sage tendon
#

?

echo wraith
#

like bot.intents.smth = True

sage tendon
#

why tho

#

just set them

echo wraith
#

because I am working in something modular

sage tendon
#

I mean probably

echo wraith
#

like bot._connection.intents

#

or something

#

idk

#

because

    @property
    def intents(self) -> Intents:
        """The intents configured for this connection.

        .. versionadded:: 1.5
        """
        return self._connection.intents
sage tendon
#

but tbh

#

just set the intents as late as possible if it's modular

#

or what am I missing

echo wraith
#

I can't

#

let's say

#

I have a "welcome" extension

#

which needs members

#

but no other needs

#

if I disable that extension, I don't want member intents to be enabled

opal swan
sage tendon
#

meh idk

echo wraith
# sage tendon meh idk

the thing is that (you might have seen it) I have a thing I made called botkit which I use as a template for all my bots now

#

and that is nice but oh well

#

at this point just gonna ad a feature in that for intents

sage tendon
#

tho

#

i dont get whats wrong with like, getting all disabled modules from the DB, then setting intents accordingly, then starting the bot

echo wraith
#

like

#

the point is it being a template

#

so yeah sure I can know what intents are needed for the default example extensions

#

but for all the ones added after the template is cloned

#

i would have to define that

sage tendon
#

oh

#

i get it

edgy nest
#

bot._connection._intents is modifiable

echo wraith
#

I missed the underscore

edgy nest
#

idk why it feels the need to give you a copy of them

#

but whatever

#

ยฏ_(ใƒ„)_/ยฏ

errant trout
flat wind
#

is there an event for when someone add a bot for user installable commands ?
I know on_guild_join when the bot joins a server, but what about user install ?

sage tendon
#

According to [Discord](#discord-api-updates message), soon

#

(last sentence)

flat wind
#

yeah thanks !!

sage tendon
#

The member flags contain stuff like "suspicious account activity" etc right?

#

trying to figure out how to detect if someone has one of those flags, since its not really documented at all in pycord

#

and i fear it's just bare

errant trout
#

there's the SPAMMER flag as 1048576, but the other modview flags are not available

#

it's not included in the library because discord doesn't want it documented (i think?)

sage tendon
#

Yea, im getting a lot of users with the red account activity flag, i think that is that

#

how would i go about checking whether someone has that tho

errant trout
#

i'd doubt it, you can check with #general message but it won't match up

sage tendon
#
if member.public_flags == 1048576

?

errant trout
#

they are different flags, SPAMMER isn't what the members view shows

sage tendon
#

oof

errant trout
#

i think anyway

sage tendon
#

so no way?

errant trout
#

nop

sage tendon
#

this the one btw

#

in the 2 minutes we talked another one joined
shows how big of a problem it is :>

errant trout
#

i mean you can just check over all your members with the bitwise method

edgy nest
errant trout
errant trout
sage tendon
#

but seems not possible then if its different flags

edgy nest
errant trout
#

just check if the people with that spammer flag method i linked match up with what you're seeing in the mod view

sage tendon
#

yea kinda hard to test lol
a mod already kicked them so i have to wait for someone new to join

#

or wait, it should be on User right? so i can test it with a user app mb?

edgy nest
#

just fetch the user

errant trout
#

you can just fetch the user yeah

edgy nest
#

it might show up

sage tendon
#

with a user app too?

edgy nest
#

doesn't fkin matter

#

they're the same thing

sage tendon
#

ok chill lol

#

from experience user apps cant do shit so i just thought

edgy nest
#

can't do guild shit

errant trout
#

it's just a fetch_user call

edgy nest
#

can do user shit

sage tendon
#

Okay, works

#

great, thanks

errant trout
sage tendon
#

i hate these shitty 1 << 20 notations, they tell me nothing and its all over the discord docs

errant trout
#

it's a bit shift

sage tendon
#

would your solution detect this combination btw?

sage tendon
errant trout
#

probably not

#

no, it shifts 1 by 20 bits

#

so it's 100000000000000000000 (probably)

#

in binary

#

half of discord relies on bitwise logic

sage tendon
#

yea so basically what i said, makes the 20th bit 1

errant trout
#

i guess

sage tendon
errant trout
#

eh it's more convenient for them

sage tendon
errant trout
#

because bitlogic is incredibly easy

#

instead of having a dict of true/false/null for permissions, it's a single integer

mellow pebble
#

how to use persistent view for buttons in cogs ?

lofty parcel
#

You can use a listener in the cog to add the views when on_ready

mellow pebble
#

no like i mean where to add them

#

i am not getting it

#

you add them in on_ready

#

so like ...

lofty parcel
#

Yes?

#
@commands.Cog.listener
async def on_ready(self):
     await bot.add_view(MyView())
mellow pebble
#

thanks sir :)

#

lrt me try and letting you know

#
@commands.Cog.listener
async def on_ready(self):
     await self.bot.add_view(WhitelistButtons())
     await self.bot.add_view(WhitelistRejectModal())```

Traceback (most recent call last):
  File "d:\Code Projects\Fallen SMP\Fallen-SMP-BOT\Version 2\Main.py", line 7, in <module>
    import COGS.Whitelist
  File "d:\Code Projects\Fallen SMP\Fallen-SMP-BOT\Version 2\COGS\Whitelist.py", line 901, in <module>
    async def on_ready(self):
  File "C:\Users\SOHAM\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\discord\cog.py", line 406, in listener
    raise TypeError(
TypeError: Cog.listener expected str but received 'function' instead.
sage tendon
#

listener()

#

with parentheses

mellow pebble
#

ohh

#

wait working

#

let me check

mellow pebble
little cobalt
#

did you resent the buttons?

#

with a new message

mellow pebble
#

no like i sent it

little cobalt
#

also did you add a custom ID to the buttons

mellow pebble
#

then i restart the bot

mellow pebble
sage tendon
#

and set the timout to None

little cobalt
#

also dont use the same ID for every button

mellow pebble
sage tendon
#

you still need timeout=None

#

99% sure

mellow pebble
#

and timeout is to none

sage tendon
#

then just say that lol

mellow pebble
#

still same

#

like then what to do sir so that even after bot restart it reponds to buttons and all

sage tendon
#

show your button definitions

mellow pebble
#
class WhitelistButtons(discord.ui.View):
    def __init__(
        self, user_id: int, user: discord.Member, bot: commands.Bot, main_embed
    ):
        super().__init__(timeout=None)
        self.main_embed = main_embed
        self.user_id = user_id
        self.user = user
        self.bot = bot

        self.mongo_client = MongoClient(os.getenv("MONGO_URI"))
        self.db = self.mongo_client["Users"]
        self.collection = self.db["UserData"]

#
    @discord.ui.button(
        label="Accept", custom_id="accept", style=discord.ButtonStyle.success
    )
    async def accept_button_callback(self, button, interaction):

        if interaction.user.id not in ADMINS:
            await interaction.response.send_message(
                "You Are Not Allowed To Use This Button", ephemeral=True
            )

        else:

            document = self.collection.find_one({"ID": self.user_id})

            if document:
                username = document.get("Username")

                ConsoleChannel = self.bot.get_channel(CONSOLE_CHANNEL)
                await ConsoleChannel.send(f"whitelist add {self.user}")

                embed = discord.Embed(
                    title="User Whitelisted",
                    description=f"User `{username}` Has Been Whitelisted",
                    color=0xD5E4CF,
                )

                user_embed = discord.Embed(
                    title="Whitelist Application Accepted",
                    description=f"Your Whitelist Application Has Been Accepted. \n## Join Now : `play.fallensmp.xyz`",
                    color=0xD5E4CF,
                )

                try:
                    User = self.bot.get_user(self.user_id)
                    await User.send(embed=user_embed)
                except Exception as e:
                    pass

                await interaction.response.send_message(embed=embed, ephemeral=True)

                message_id = interaction.message.id

                self.disable_all_items()
                button.style = discord.ButtonStyle.secondary
#

                self.main_embed.add_field(
                    name="Whitelist Accepted By",
                    value=f"{interaction.user.display_name}",
                    inline=False,
                )

                await interaction.followup.edit_message(
                    embed=self.main_embed, message_id=message_id, view=self
                )

            else:
                embed = discord.Embed(
                    title="User Not Found",
                    description=f"No Whitelist Application Found For **{self.user.display_name}**.",
                    color=discord.Color.red(),
                )
                await interaction.response.send_message(embed=embed, ephemeral=True)

                message_id = interaction.message.id

                self.disable_all_items()
                button.style = discord.ButtonStyle.secondary

                self.main_embed.add_field(
                    name="ERROR", value="User Not Found", inline=False
                )

                await interaction.followup.edit_message(
                    embed=self.main_embed, message_id=message_id, view=self
                )
little cobalt
#

Keep in mind that pymongo is not async and can create issues

mellow pebble
little cobalt
#

you also dont need bot at the button

little cobalt
mellow pebble
little cobalt
#

also you dont need bot at the button

#

you already get the bot with interation.client

mellow pebble
mellow pebble
little cobalt
#

you can remove the bot at the __init__ and replace the other stuff with it

mellow pebble
#

any suggestions on what to do ?

echo wraith
#

Ok so atomic means if one role fails all fail

opal swan
little cobalt
#

and on_interaction also reacts to slash commands

opal swan
little cobalt
#

I never use on_interaction

mellow pebble
opal swan
mellow pebble
#

how can i use mentioning of but as a prefix ?

opal swan
mellow pebble
#

i have another question, possible to remove help command in bridge ?

little cobalt
real glacier
#
page_buttons = [
            pages.PaginatorButton(
                "first", emoji=":backskip:", style=discord.ButtonStyle.blurple
            ),
            pages.PaginatorButton("prev", emoji=":backwardbtt1:", style=discord.ButtonStyle.blurple),
            pages.PaginatorButton(
                "page_indicator", style=discord.ButtonStyle.gray, disabled=True
            ),
            pages.PaginatorButton("next", emoji=":forwardbtt2:", style=discord.ButtonStyle.blurple),
            pages.PaginatorButton("last", emoji=":nextskip:", style=discord.ButtonStyle.blurple),
            ]
            page_groups = [
                pages.PageGroup(
                    pages=[embed_p1, embed_p2, embed_p3, embed_p4],
                    label="Back",
                    description="Detail Cards",
                    use_default_buttons=False,
                    custom_buttons=page_buttons,
                    disable_on_timeout=True,
                    timeout=300,
                    loop_pages=True
                ),
                pages.PageGroup(
                    pages=[
                        total_embed
                    ],
                    label="Summary",
                    description="All cards info in one!",
                    show_disabled=False,
                    show_indicator=False,
                ),
            ]
            paginator = pages.Paginator(pages=page_groups, show_menu=True)``` it wont display custom button, somehow
flat wind
#

can a synchronous thing inside an asynchronous function that is called inside another asynchronous function raise an Unknown Interaction error ?

Example :

async def SomeFunctions():
    Calling synchronous function from flpc or fnmatch.fnmatch

@command
async def myCommand():
    await SomeFunctions()
```(this is pseudo-code, not the real one).

Can the `Calling synchronous function from flpc or fnmatch.fnmatch` block the full python bot or not ?
lapis dock
#

It can. You can use the below to counteract it

#

.tag rie

sly karmaBOT
#

You can run blocking code (such as PIL/Pillow) in an executor to run it in a separate thread: ```py
def my_blocking_func(*args):
...

@bot.command()
async def test_command(ctx):
ret = await bot.loop.run_in_executor(my_blocking_func, 'put', 'args', 'here')``` See the python documentation for more info.

flat wind
#

okay thanks !

mellow pebble
lapis dock
real glacier
#

discord.ext.pages

errant trout
#

(i highly recommend going through paginator docs)

real glacier
#

ok thanku

sage tendon
#

if in my error handler i raise an exception (for the case where i dont know what the underlying error is) does that stop the bot or not

#

im a bit dumb rn

echo wraith
#

by error handler I assume you mean in the on_error event

sage tendon
#

because currently i just have this and i was told i should throw an exception instead

echo wraith
sage tendon
#

so raise(err)?

lofty parcel
#

Or print the traceback

echo wraith
#

like logging.error

sage tendon
#

yea but we have different log files

#

with pm2

#

prints go somewhere other than error logs

#

so the print would go to an info log instead of an eror log

echo wraith
#

I mean in any case your code is not going to break

sage tendon
#

also what exception should i raise
i legit never ever work with exceptions except ignoring them explicitly

echo wraith
#

just do

raise err
#

or raise from as seen here

#

so you can have your own "UnknownError" class or whatever and you do raise UnknownError(f"{ctx.author.blah}...") from err

echo wraith
#

if you wanna know

sage tendon
#

hm but i kinda dont wanna lose the information of the command used etc

echo wraith
#

because

  1. you can add it in your message
  2. you do raise from so it keeps the traceback
sage tendon
#

but the only exception i expect at that point is of some API providers
so idk

echo wraith
#

you decide it's your code

sage tendon
#

like this right

#

chatgpt said raise from err alone isnt valid lol idk

lofty parcel
#

Just raise err

sage tendon
#

there that looks good

little cobalt
opal swan
#

how to get a ctx.args ?

sage tendon
#

What do you want to do

opal swan
#

but idk how it work ๐Ÿ˜‚

sage tendon
#

yea I got about that much
but what do you want to do
why can't you grab the option directly for example

opal swan
#

nah just for testing

#

and know how it work

#

for futur commands

sage tendon
#

well, ctx.args[0] if it's the first option

opal swan
opal swan
#

mb

fresh sierra
#

ctx.kwargs give a dict

#

ctx.kwargs["name of option"] -> value

opal swan
#

I do that : ctx.kwargs["member"]

#

but None

fresh sierra
fresh sierra
#

kwargs are generally in command the *, things

opal swan
#

oh mb that's fine

#

ty

fresh sierra
#

(should be)

#

depends in ur usage, share code might be useful

opal swan
#

like for say command it's good

opal swan
#

like this

fresh sierra
#

share code

#

cos here i dont understand anything

opal swan
#

@bot.command()
async def test(ctx, membre : discord.Member):
await ctx.reply(f"> args : {ctx.args[0].id}")

fresh sierra
#

here

async def buyer(self, ctx: LumabotContext, arg: discord.User, *, kwarg: str):
    pass
#

for exemple ctx.args[1] will be the member, ctx.kargs["kwarg"] the kwargs

opal swan
#

I know wth is the index

fresh sierra
opal swan
#

nice ty

fresh sierra
#

well dont think ctx is the first one normally

#

except ur using other thing

opal swan
#

done tysm

opal swan
fresh sierra
#

where ctx is passed twice

opal swan
opal swan
#

like discord.TextChannel it convert id in channel

sage tendon
#

yes

opal swan
#

ty

misty sandal
#

Hi guys! Is there a way to create bot linked roles using py-cord?

obsidian blaze
#

So I was able to get it working for both pc and mobile. I was followed what someone did in the disnake server and just added a couple things. #1242420866806190091 message (Altering waveform to get discord voice message to work)

from io import BytesIO
from json import loads
import base64
from aiohttp import ClientSession, FormData
import asyncio

BOT_TOKEN = ""
channel_id = 0

async def send_voice_message(voice_bytes: BytesIO):
    len_bytes = voice_bytes.read()
    voice_bytes.seek(0)

    async with ClientSession() as session:
        async with session.post(
            url=f"https://discord.com/api/v10/channels/{channel_id}/attachments",
            headers={
                "content-type": "application/json",
                "Authorization": "Bot " + BOT_TOKEN
            },
            json={
                "files": [{
                    "file_size": len(len_bytes),
                    "filename": "result.mp3",
                    "id": 0
                }]
            }
        ) as response:
            data_response_upload = loads(await response.text())

            url_to_upload = data_response_upload["attachments"][0]["upload_url"]
            filename_upload = data_response_upload["attachments"][0]["upload_filename"]

        data = FormData()
        data.add_field("file", voice_bytes, filename="result.mp3")

        async with session.put(
            url=url_to_upload,
            headers={
                "Content-Type": "audio/mp3"
            },
            data=data
        ) as response:
            pass

        async with session.post(
            url=f"https://discord.com/api/v10/channels/{channel_id}/messages",
            headers={
                "Content-Type": "application/json",
                "Authorization": "Bot " + BOT_TOKEN
            },
            json={
                "flags": 8192,
                "attachments": [{
                    "id": 0,
                    "filename": "result.mp3",
                    "uploaded_filename": filename_upload,
                    "duration_secs": 42,
                    "waveform": base64.b64encode(len_bytes[:100]).decode("utf-8")
                }]
            }
        ) as response:
            pass

async def get_voice_bytes(file_path: str) -> BytesIO:
    with open(file_path, "rb") as file:
        return BytesIO(file.read())

async def main():
    voice_bytes = await get_voice_bytes("result.mp3")
    await send_voice_message(voice_bytes)

asyncio.run(main())```
lofty parcel
#

we should get that pinned lol

#

impressive work

obsidian blaze
#

I won't lie I didn't do much I just have been hunting for the past couple days to find something that would work. I needed this to work for my one bot as the main thing is sending voice messages so mobile can hear too.

tidal vessel
#

Can anyone help me with this problem? I have uploaded my bot to a server on Digital Ocean and the bot starts up with no problems, but the application commands have stopped working.

I tested them locally and they do work.

I get this error
Unknown integration.

I have restarted discord and the commands no longer work.

#

now I checked again and the commands are no longer displayed

#

hahaha I know what I did wrong, sorry for the inconvenience

lapis dock
errant trout
#

bots aren't really meant to be sending them

shell radish
#

it's not documented

real glacier
#
      title=f"Item #{self.item.id} ITEM(S)"
    )```
how `{self.item.id}` works with paginator?
echo wraith
opal swan
#

def check_owner(self, ctx : commands.Context):
   if await self.bot.is_owner(ctx.author):
     return
    else:
       raise commands.NotOwner

@commands.command()
@commands.cog(check_owner)

# traceback is smthing like that :

"""
Missing 1 required argument ctx
"""
sage tendon
#

if that function isn't in a class, you have to remove self

opal swan
#

and so I can do a thing like that :

#
def owner_check(ctx, bot)

@commands.check(ctx=commands.Context, bot=self.bot)
#

in my memory I can't use self

#

but how to do that

sage tendon
opal swan
#

without any check just in the def async ?

#

it's wth I do but it was just a question

sage tendon
#

@commands.is_owner()
thats all you need

opal swan
#

how to fix that

opal swan
#

tyyy

#

"A decorator that adds a maximum concurrency to a command"

#

??????

sage tendon
#

if you dont understand it, chances are you dont need it

opal swan
#

alr

sage tendon
opal swan
#

bruh I didn't read it

#

and u said I don't need to use it sooo

sage tendon
opal swan
#

is it transform float into a datetime.datetime and after a dt or not ? discord.utils.format_dt(datetime.datetime(second=int(myfloat), style="R")

sage tendon
#

no

#

it makes it into a discord timestamp

#

<t:0:R>

opal swan
#

ok so it's nice for me

proven valley
#

is there a way to center within an embed text?

shell radish
summer knot
#

How can I know if a member has timeout?

rugged lodgeBOT
summer knot
ivory beacon
#

Is it possible to remove an embed sent by another bot?

opal swan
opal swan
#

no u can't.

ivory beacon
opal swan
edgy nest
ivory beacon
edgy nest
ivory beacon
ivory beacon
visual wren
#

Besides using ```py
@commands.slash_command(integration_types={
discord.IntegrationType.guild_install,
discord.IntegrationType.user_install,
},)

#

Nevermind this question, i forgot to remove command syncing.

opal swan
#

but format_dt is not recognized

rugged lodgeBOT
echo wraith
#

that's your ide

opal swan
#

TypeError: format_dt() got an unexpected keyword argument 'type'

#

my new error

#

๐Ÿ‘€

opal swan
#

i'm on it

opal swan
echo wraith
lapis dock
# opal swan go on dm

Please do not DM for help unless the person helping you specifically says you can. The help channels are for help so there is no reason to not use the help channels for help.

opal swan
lapis dock
#

Still ask for permission first.

#

You can talk in other languages here as well.

little cobalt
#

@opal swan just create a thread and you can talk in french there

opal swan
#

ty

#

for the information

opal swan
#

code :

invitation = await random.choice(guild.text_channels).create_invite(max_age=500, max_uses=1)``` and yes I try guild.text_channels[0] but it return an another error

Traceback : Command raised an exception: IndexError: Cannot choose from an empty sequence
echo wraith
opal swan
echo wraith
opal swan
#

hmmm no

echo wraith
#

that's litterally what the error means

#

yeah so it is

#

do something else

#

use this:

rugged lodgeBOT
echo wraith
#

the first one

opal swan
#

๐Ÿ˜ญ

#

NoneType

#

bruh

echo wraith
#

What I meant is use that in preference, and else create an invite in a random channel

opal swan
#

Command raised an exception: HTTPException: 400 Bad Request (error code: 30001): Maximum number of guilds reached (10)

#

10 the max ???????

#

nahh

opal swan
little cobalt
#

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

sage tendon
#

wtf is "max_age" lol

lofty parcel
sage tendon
#

nuh uh
:3
just did

quaint cipher
#

hello, i was trying to make a bot join a voice channel, but ctx.author.voice.channel.connect() does not work. has pycord updated to deprecate ctx.author.voice?

#

it doesnt even raise any errors

sage tendon
#

show your code

lapis dock
#

This requires Intents.voice_states.
Do you have this?

quaint cipher
#

i have enabled discord.Intents().all().

#

the problem persists in a server where the bot has admin privileges.

sage tendon
#

For testing you should always enable every permission individually
was told bots don't work with the admin permission as expected

either way, show your code

opal swan
#

can u send the code

sage tendon
#

almost as if i asked that twice already

opal swan
#

@quaint cipher

quaint cipher
#

sorry discord was turned off

#

let me edit out the problematic part to show

opal swan
#

xddd

#

send ur code

#

pls

quaint cipher
#
from discord.ext import commands

intents = discord.Intents().all()
intents.voice_states=True

bot=commands.Bot(command_prefix="!", status=discord.Status.online, intents=intents, help_command=None)

@bot.slash_command(guild_ids=[...])
@discord.option("text", type=discord.SlashCommandOptionType.string)
async def test(ctx:discord.ApplicationContext, text: str):

    print(1)
    await ctx.author.voice.channel.connect()
    print(2)

bot.run(token)```
#

this code prints 1 and the bot joins my voice channel, but 2 is not printed.

#

also, ctx.voice_client returns None even the bot is in a vc.

#

first guess was that there was something off with intents, but using .all() and enabling .voice_states directly did not work.

little cobalt
#

you dont need intents for slash commands

lapis dock
#

???

quaint cipher
#

is that true? very interesting

lapis dock
#

That's not true, idk what zervy is talking about

little cobalt
quaint cipher
#

hmm

little cobalt
#

But I cannot find the old Basic PyCord help

quaint cipher
#

should i move my question to a new post

little cobalt
#

I always said they need it

lapis dock
#

Well, it's not the issue in this case no matter what

little cobalt
#

@quaint cipher what are your bot permissions?

quaint cipher
sage tendon
#

can you print ctx.author.voice

#

and did you enable the intents in the dev portal too, just to make sure

little cobalt
#

so they are enabled

quaint cipher
#

my bot is small so all privileged intents are enabled. also i think voice intents are not prevliged

#

and yes ctx.author.voice properly prints True

little cobalt
#

you can delete the intents.voice_ line

#

you already got all the intents

sage tendon
#

it shouldn't print true..

#

or actually maybe thats overriden

#

hm

quaint cipher
#

well ctx.author.channel properly prints as well

sage tendon
#

is the bot in a voice channel already in the server?

quaint cipher
#

it prints some long python object

#

type is VoiceState

sage tendon
#

yea

#

show

quaint cipher
#

show the object?

sage tendon
#

yes.

quaint cipher
#

<VoiceState self_mute=True self_deaf=False self_stream=False suppress=False requested_to_speak_at=None channel=<VoiceChannel id=1090650007738265655 name='์ž์œ ๋ฐฉ
_1' rtc_region=None position=0 bitrate=64000 video_quality_mode=<VideoQualityMode.auto: 1> user_limit=0 category_id=1090650007738265652>>

sage tendon
#

hm looks fine

quaint cipher
#

same problem happens with the bot already joined.

sage tendon
#

ohh

#

yea i misunderstood

quaint cipher
#

it reliably spits error in my computer

lapis dock
echo wraith
quaint cipher
#

if the second print statment runs it worked

#

in my enviroment 1 prints and the bot joins but 2 dosent get printed

lapis dock
#

you do not have any sort of global error handling or similar do you?

quaint cipher
#

yes the code above is all there is

echo wraith
#

So

#

I cannot reproduce the issue with your code, it works on my side

quaint cipher
#

hmmmmmm

echo wraith
#
1
INFO:discord.voice_client:Connecting to voice...
INFO:discord.voice_client:Starting voice handshake... (connection attempt 1)
INFO:discord.voice_client:Voice handshake complete. Endpoint found milan10014.discord.media
INFO:discord.gateway:selected the voice protocol for use (xsalsa20_poly1305_lite)
INFO:discord.gateway:received secret key for voice connection
2
quaint cipher
#

makes my head hurt

echo wraith
#

just to see if that changes anything

quaint cipher
#

oh maybe i should try debug mode

echo wraith
#

.tag logging

sly karmaBOT
quaint cipher
#

oh thanks

#

hmm

#

pycord is in the latest version....

#

there is a new line that popped up some time later

#

WARNING:discord.gateway:Shard ID None has stopped responding to the gateway. Closing and restarting.

echo wraith
#

I'm gonna try to vpn in south korea to see what it does

quaint cipher
#

thanks! although other music bots do work so i think it is not a regional problem

quaint cipher
#

yea this is being a major headache

#

ctx.voice_client also returns None at all times, could this problem be related?

echo wraith
#

yeah no

1
INFO:discord.voice_client:Connecting to voice...
INFO:discord.voice_client:Starting voice handshake... (connection attempt 1)
INFO:discord.voice_client:Voice handshake complete. Endpoint found south-korea1121.discord.media
INFO:discord.gateway:selected the voice protocol for use (xsalsa20_poly1305_lite)
INFO:discord.gateway:received secret key for voice connection
2
echo wraith
quaint cipher
#

yes

little cobalt
quaint cipher
#

just in case ill try to uninstall and reinstall [voice]

echo wraith
echo wraith
quaint cipher
#

does [voice] show up differently in pip show?

little cobalt
#

good question

#

I never installed it and still was able to join voice

echo wraith
quaint cipher
#

ahhhhh

#

god

#

reinstalling worked

#

just for the record

#

i tried pip install py-cord[voice] --upgrade in a py-cord environment

#

sorry guys it was problem on my side

#

thanks for helping out

echo wraith
quaint cipher
#

thanks so much

fresh sierra
#

how can i check if a token is valid and has the 3 intents enabled on the panel of discord ?

opal swan
fresh sierra
#

im gonna make a thread i thing its more diffcult

civic moon
#

Is there a way to pull message formatting from a message? For example Bold with the asterisks.

dense summit
#

No masked links in embeds?

#

Is there a way to fix this?

echo wraith
echo wraith
dense summit
shell radish
dense summit
#

it should be with the protocol?

shell radish
#

yes

civic moon
dense summit
errant trout
little cobalt
#

do I have to add views at the on_ready event or can I also do with before starting the bot?

errant trout
#

i.e. [www.vinted.it](https://www.vinted.it)

little cobalt
#

so I cannot just do it like the cogs?

errant trout
#

well, just add an on_ready in your cog

little cobalt
#

I just currently doing it like this

errant trout
#

that's fine

errant trout
#

no

#

only in one of them, not the other

#

i.e. they shouldn't match

#

...though at that point, you don't really need to use the markdown do you

#

unless you really don't want the https:// to show

dense summit
#

oh thanks got it

dense summit
errant trout
#

isee

fresh sierra
#

is it possible for a bot to see options enter by an other bot command in ephemeral ?

fresh sierra
#

perfect

#

thanks

flat wind
#

how do I create a message_command in a cog ?

echo wraith
#

@commands.command

flat wind
echo wraith
#

I am a bit tired

#

lol

flat wind
#

np lol

#

okay I found it

rugged lodgeBOT
flat wind
#

is it possible to get the client language using pycord ?

little cobalt
flat wind
#

my discord client is in french

little cobalt
#

oh you mean that

#

1 sec.

flat wind
#

sure

little cobalt
#

ctx.interaction.locale

#

its only possible with interactions

flat wind
little cobalt
#

you mean the right click at messages?

flat wind
#

yes

little cobalt
#

and apps?

flat wind
#

yes

little cobalt
#

so its fine

wise bluff
#

hey there! i have this command which takes a role as an argument. is there a way to add "None" into the roles list-autocomplete? so the user could choose none/nothing (doesnt really matter what its called) instead of a role?

flat wind
# little cobalt

do they show up immediatly ? I don't have them on my discord but the ping test I have made was showing up immediatly

flat wind
#

example :

@option(
        name="allowed",
        description="True or False",
        required=False,
        type=bool
    )
little cobalt
flat wind
#

okay, np

little cobalt
#

sometimes you have to refresh dc

flat wind
#

I will find what I have made that I should not lol

flat wind
little cobalt
#

oh

wise bluff
#

thank you both! that worked

flat wind
# little cobalt oh

how can I put the message_commands in the DM too ? I tried with the IntegrationType set but that's why my commands disappeared from the menu ๐Ÿ˜ญ

sage tendon
#

context, not type

opal swan
#

how to know all member badge and it return a list

#

is it flags things ?

lofty parcel
sage tendon
#

an object is an instance of a class

lofty parcel
lofty parcel
shell radish
sage tendon
#

that is not right for all i know and was ever taught

lofty parcel
sage tendon
#

should i catch those with except (Forbidden, HTTPException)?

maiden bloom
#

Is support for recurring subscriptions being worked on? I noticed 2.6.0 only supports one-time

nimble matrixBOT
maiden bloom
#

Oh, the patch notes said one-time and I haven't tried it out yet

edgy nest
deft kestrel
#

i can do selfbot with pycord?

opal swan
#

good question ๐Ÿ˜‚

little cobalt
deft kestrel
lofty parcel
deft kestrel
opal swan
lofty parcel
sage tendon
#

needlessly rude

errant trout
#

you can't selfbot with pycord

#

(probably)

#

any user-only api features don't exist

little cobalt
#

Many used self botting to scam people

opal swan
#

xd

fresh sierra
errant trout
echo wraith
fresh sierra
echo wraith
fresh sierra
#

thanks

merry ermine
#

When I have an on_auto_moderation_action_execution event and the AutoMod action has multiple actions, it causes things to run multiple times, how do I avoid this?

sage tendon
#

I guess compare the rule id and keep a small list of previously received events

#

and then ignore further events with the same rule id if it happens within like 1s or whatever

#

or you can use the message object for that

#

that's probably easier actually

merry ermine
#

Well it's time to make a temporary in memory database for only this

sage tendon
#

... what

#

just make a dict lol

#

don't overcomplicate it

merry ermine
#

I made a list and use a tuple of rule_id and message_id, it ain't broken

#

I copied the code from another location in the code and changed it slighlty

sage tendon
#

yea
but that's not at all what an in memory db is lol

merry ermine
#

it kind of serves as a in memory db, except it has alzheimers as it forgets after 1 second

sage tendon
#

a list isn't an in memory db
H2 is an in memory db
:)

fresh sierra
#

any idea to do that if someone use an autocomplete but the value that he pass is not inside the autocomplete, it does not trigger the command ?

sage tendon
#

handle it inside the command

fresh sierra
#

how can i get autocomplet choice if you prefer

sage tendon
#

i mean you'll have a list of all possible values, no?

#

just check against that

fresh sierra
#

(if there is a easy method, else i will trigger the fonction)

fresh sierra
#

else i will trigger the function and check

sage tendon
#

else, what are you autocompleting on

fresh sierra
#

trying to do something kinda like so if u prefer

solar salmon
#

when running slash command how can I get the channel command was ran in?

solar salmon
#

thanks

solar salmon
#

is there an option for getting timestamp for when user was banned? i know there is joined_at.timestamp() is there a syntax for ban?

fossil valve
#

is it possible to catch all the errors from events (on_message, on_guild_channel_create etc.) globally like with the slash command error event or is there only the option to use try/except?

fossil valve
#

I see thank you

errant trout
tough prawn
#

I keep getting this error after testing my slash command that i'm trying to get a cooldown on.
Appreciate any help on this problem and thanks to anyone that does.

the error:

discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: Scommands.test_error() takes 2 positional arguments but 3 were given 
 @discord.slash_command(
            name="test",
            description="Used for testing! :alien:",
            guild_ids=ALLOWED_SERVER_IDS
    )
    @commands.cooldown(rate=1, per=5*60) # WIP
    async def test(self, ctx: discord.ApplicationContext):
        await ctx.respond("Test success! :muscle:")

    @test.error
    async def test_error(ctx, error):
        if isinstance(error, commands.CommandOnCooldown):
            await ctx.send("Command is on cooldown! :man_guard:")
        else:
            raise error

tough prawn
little cobalt
#

Keep in mind to use ctx.respond and not ctx.send

uncut swift
#

I am having a heck of a time trying to create a cog that runs a task at 10 minute intervals, that sends text to a specific channel. I have some blocky ass code and thought that maybe using a cog would clean things up. Quite a few examples i am finding are pretty old...

little cobalt
#

Do you use dpy or py-cord?

#

Also just get the channel and send the message

compact shadow
#

In guide says : 'bridge commands do not currently support per-command error handling". It mentions Issue #1388 but in that issue it says that PR #1411 was made to close the issue. So, is it now possible to use the per command error in slash commands?

opal swan
#
def check(member):
   return (member.id == ctx.author.id) and (member.guild.id == ctx.guild.id)

member = await bot.wait_for('member_join', check=check)

is it right ?

sage tendon
#

try it and see

#

I'm just unsure on what it'd achieve

#

you're basically waiting for the command caller to rejoin the server

nova epoch
#

Feel like a moron asking this, but I can't find an actual answer anywhere. Is there a button type to copy text to the clipboard?

sage tendon
#

no

nova epoch
#

aight, i'll have to find a workaround

#

thanks :D

lapis dock
errant trout
proven valley
#

my embed has 3 fields but im getting an error saying it has more than 10 elements but I'm almost certain it doesn't unless im missing something, anyone have some insights here?

proven valley
#

Ignoring exception in command mma queue:
Traceback (most recent call last):
File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\discord\commands\core.py", line 138, in wrapped
ret = await coro(arg)
^^^^^^^^^^^^^^^
File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\discord\commands\core.py", line 1078,
in _invoke
await self.callback(self.cog, ctx, **kwargs)
File "c:\Users\User\Desktop\Test\cogs\mmq.py", line 265, in queue
await paginator.respond(ctx.interaction, ephemeral=False)
File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\discord\ext\pages\pagination.py", line 1197, in respond
msg = await interaction.response.send_message(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\discord\interactions.py", line 908, in send_message
raise ValueError("embeds cannot exceed maximum of 10 elements")
ValueError: embeds cannot exceed maximum of 10 elements

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

Traceback (most recent call last):
File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\discord\bot.py", line 1137, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\discord\commands\core.py", line 435, in invoke
await injected(ctx)
File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\discord\commands\core.py", line 138, in wrapped
ret = await coro(arg)
^^^^^^^^^^^^^^^
File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\discord\commands\core.py", line 1486,
in _invoke
await command.invoke(ctx)
File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\discord\commands\core.py", line 435, in invoke
await injected(ctx)
File "C:\Users\User\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\discord\commands\core.py", line 146, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: ValueError: embeds cannot exceed maximum of 10 elements

lofty parcel
#

How are you defining your pages?

proven valley
#

I use a for loop to make a embed with the fields I need for displaying the data, then, make a page with the embed and fields and add it to a list, python pagelist.append(Page(embeds=embed)) paginator = Paginator(pages=pagelist) await paginator.respond(ctx.interaction, ephemeral=False)

oblique sable
#

hey guys any quick idea on why my slash commands stop working when i log out? on windows

#

pinging the bot still works though

lofty parcel
#

You can also just pass a list of embeds to the paginator itself pages=pagelist, pagelist being a list of discord.Embeds

proven valley
#

okay, thank you. So if I'm understanding correctly, if I pass multiple embeds it will treat each embed as a page?

lofty parcel
#

You kinda don't need a Page unless you're adding more stuff than just an embed

waxen citrus
#

hey guys, maybe you could help me.. when I access overwrites property within ctx.channel it returns empty dict..

did I miss something that may change within developer portal that I need to enable?
simple code example:

async def test(self, ctx: discord.ApplicationContext):
    print(ctx.channel.overwrites)```
rugged lodgeBOT
waxen citrus
opal swan
#

but no reason for using fetch to get a banner

#

๐Ÿค”

opal swan
atomic fern
#

how long discord.ui.View.message expires? sometimes return discord.Message or None
does it have message_id attribute?

uncut swift
# little cobalt Also just get the channel and send the message

Pycord. When I was not using cogs, i was doing this..

await chan.send('my message')```

In my cog, I am trying:
```chan = discord.utils.get(self.bot.get_all_channels(), name='my-channel')
await chan.send('my message')```

But i get a `AttributeError: 'NoneType' object has no attribute 'send'`
rugged lodgeBOT
echo wraith
#

wait no my bad

#

You should not always assume all channels to be in the cache

spring plume
#

the easy way is how to make the buttons work after restarting the bot?
or do I need to save the message to my database and edit it when the bot starts?

heavy inlet
#

you can use persistent buttons

spring plume
heavy inlet
#

It was in the the guide but it's down

#

Hold on

rugged lodgeBOT
#

Here's the persistent example.

spring plume
#

thx!

heavy inlet
#

Np

deft kestrel
#

How to disable a button?

shell radish
opal swan
#

await self.message.edit(view=self)

proven valley
#

is it possible for me to implement the twitch API with my discord bot, so certain actions on a twitch channel can be done through a interaction through a discord bot?

#

or should I write a seperate program for that?

errant trout
#

Should be easy enough

#

I've personally used twitchAPI on pip

proven valley
#

is it any good?

errant trout
#

Just check the examples and read through docs for what you wanna implement

proven valley
#

yeah the docs look pretty good, i'll have a try at implementing it.

errant trout
#

It's also fully async so shouldn't cause any blocking

opal swan
#

how can I use the class commands.Bot and why it's good to do it ?

#

I mean this thing

errant trout
#

.tag client

sly karmaBOT
#
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
bridge.Bot # above + bridge commands (application commands and text commands in one)
opal swan
#
class bot(commands.Bot):
  ..
errant trout
#

commands.Bot is if you want prefix command support, which was the standard before slash commands

errant trout
#

Then what

#

Do you mean subclassing?

opal swan
#

like some guys use it for like get his prefix when he is edit by the database

#

idk how to say it but it's a thing like that

errant trout
#

Indeed, commands.Bot comes with a function you can override for custom prefixes

#

It's explained in the docs

opal swan
#
class bot(commands.Bot):
   ...

  async def set_prefix(self):
      pref= db.execute("...").fetchone()

   if pref:
      Bot.prefix = pref[0]
   else:
      Bot.prefix = "+"
opal swan
#

ty also

sage tendon
#

please make your classses uppercase, and variables lowercase

#

you are like going directly against convention

opal swan
errant trout
# opal swan like Bot ? or all characters need to be uppercase ?

in python it's standard for variables and functions to be lowercase, while class names start with a capital letter; e.g. ```py
some_var = True

class Bot(commands.Bot):
...```this ISN'T required by any means, people break conventions all the time, it's just what you normally see

sage tendon
#

class names are PascalCase, methods and variables are snakecase

opal swan
sage tendon
#

breaking conventions isn't clean code

#

you're free to use whatever casing you want, but if anything, its not "clean code"

errant trout
#

your friend is blatantly wrong, but ultimately this is relatively unimportant; just do whatever style you prefer

#

(i.e. your friend prefers doing it that way, and that's perfectly fine)

sage tendon
#

it gets important if you wanna share your code

errant trout
#

GuraShrug im not here to preach about what style to use

sage tendon
#

because i would've assumed that with Bot.prefix, you are addressing the bot class, not an object

late slate
#

Is it possible to use the following decorator for a command function in a slash command group that's in a cog?
@discord.default_permissions(manage_channels=True)

Like...

admin = discord.SlashCommandGroup("admin", "Admin commands")

@admin.command(name = "kick", description="Kicks member")
@discord.default_permissions(manage_channels=True)
async def kick(self, ctx):
    # Do stuff

I ask because last time I tried this (like almost a year ago now), there were no errors, but the decorator was ignored and anyone could run the command. I'm just double checking if there have been any improvements to allow preventing (and hiding) commands in cogs to users who do not have permission to run them.

errant trout
#

can't apply discord permissions to subcommands

late slate
errant trout
#

you have to pass it to the entire group py admin = discord.SlashCommandGroup("admin", "Admin commands", default_member_permissions=discord.Permissions(manage_channels=True))

late slate
#

Ahhhhh! That's what I was forgetting... Makes sense. Tyvm for the quick response โค๏ธ

errant trout
#

you'll know if it's correct if you check settings > integrations and select the group

#

will have some message about permissions

late slate
errant trout
#

mhm, admins can adjust command permissions

opal swan
sage tendon
#

has_permissions should not be used with slash commands

opal swan
#

ah

#

sad

sage tendon
#

why sad?

#

it was made for prefix commands

#

naturally it doesnt meet what a slash command needs

rugged lodgeBOT
echo wraith
fresh sierra
#

keep in mind that this can be overwrite by the admin of each guild

echo wraith
fresh sierra
#

i guess they might be some case where u dont want the thing to be overwrite

errant trout
#

while default_permissions is superior if you're fine with admins overriding it

sage tendon
#

i know
but i find the result very hacky-looking

errant trout
#

GuraShrug it's the same implementation and same error handling as anything else

sage tendon
#

yet lacks the possibility to hide commands which is what most people actually want

errant trout
#

i personally like to respond with a view button to a yt vid if someone fails a perm check

#

can't really do anything about that

echo wraith
#

It might be interesting to add default_permissions(force:bool) or something similar maybe... Just an idea

fresh sierra
#

prefer to show each command too

errant trout
#

i guess, but then it'd just fall back on has_permissions

echo wraith
#

Idk

#

Just an idea

sage tendon
#

that makes no sense lol

echo wraith
proven valley
#

is this the correct way to get a user from their ID? it doesn't seem to be working for me.

#

player1 = await discord.Bot.fetch_user(queue[n][1])

#

queue[n][1] being the ID

errant trout
#

you've initialized Bot in your main file as a variable, so you refer to that

#

if you're in a cog, this is typically self.bot

#

(also, make sure your id is an integer)

shadow sigil
#
  File "D:\GitHub\fractal-rhomb\fractalrhomb.py", line 148, in change_status_command
    activity = discord.Activity(type=discord.ActivityType.custom, state=content, emoji=emoji)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\GitHub\fractal-rhomb\.venv\Lib\site-packages\discord\activity.py", line 250, in __init__
    PartialEmoji.from_dict(emoji) if emoji is not None else None
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "D:\GitHub\fractal-rhomb\.venv\Lib\site-packages\discord\partial_emoji.py", line 114, in from_dict
    animated=data.get("animated", False),
             ^^^^^^^^
AttributeError: 'PartialEmoji' object has no attribute 'get'
```what
#

it says emoji is supposed to be a PartialEmoji, but gives an error when i give it one

errant trout
shadow sigil
#

thanks
though it doesn't seem like you can even add an emoji to a custom status

errant trout
#

eh... you should be able to...?

errant trout
#

(though, reading through docs PRs, apparently emoji actually straight up isn't supported?)

shadow sigil
#

I did start using that when i found out that it exists

#

the docs for discord.Activity don't mention it like they do for discord.Game and discord.Streaming

#

or if they do i didn't notice it

#

and yea, i "can" add an emoji
but it just doesn't do anything

shell radish
errant trout
#

It is

#

For bots

edgy nest
#

^

deft kestrel
#

How to do cooldown button callback?

#

and only user who used command

little cobalt
#

1 sec.

deft kestrel
little cobalt
#

I know, 1 sec xd

deft kestrel
#

ok

little cobalt
#
from discord.ext import commands
cd_mapping = commands.CooldownMapping.from_cooldown(1, 60, commands.BucketType.user)
bucket = cd_mapping.get_bucket(interaction.message)
retry_after: float = bucket.update_rate_limit()
little cobalt
#

@deft kestrel

deft kestrel
deft kestrel
#

How to create a command with a space like

/start here

echo wraith
#

Your group would be called start

#

And the command here

deft kestrel
#

Oh okay, thank you!

rugged lodgeBOT
#

Here's the slash cog groups example.

opal swan
#
async def snowflake(ctx : commands.Context, message : discord.Message): -> discord.Message -> discord.utils.snowflake_time ?
#

I mean discord.Message return an discord.utils.snowflake_time or no ?

atomic fern
#

how to respond to an interaction without sending any message? i use interaction.response.pong but interaction failed?

errant trout
#

if it's a component, just defer

lapis dock
opal swan
#

so that's why I asked this question

errant trout
#

well, kinda?

#

it depends on which

#

if you typehint an option as discord.Message, then it will use the MessageConverter to attempt to retrieve it

#

because discord doesn't natively support that

#

discord will natively provide ints, floats, users/members, channels, roles, and attachments, anything else the library will attempt to handle or just read as string

deft kestrel
#

When I give a role to someone, can I put a reason?

lofty parcel
#

Yes

#

Literally reason="a"

sage tendon
#

the docs have it all

proven valley
#

is there a better way to do this? it takes a bit

sage tendon
#

for

#

lol

errant trout
#

bro

#

store your players in a list instead

proven valley
#

I just knew I was gonna catch flack for this

errant trout
#

i mean you COULD do that but you're hurting yourself

sage tendon
#
for thingy in queue[n]:
    players.append(await self.bot.fetch_user(thingy))
#

should work unless im missing smth

errant trout
#

they're starting at 1 instead of 0, i guess?

sage tendon
#

oh yea

proven valley
#

it's pulling from a database, and there is something else in col 1

errant trout
#

then just offset n

sage tendon
#

well then skip the first ig
id just add a bool switch

errant trout
#

or use range(1, 9) instead

sage tendon
#
firstcolumn = True
for thingy in queue[n]:
    if firstcolumn:
        firstcolumn = False
        continue
    players.append(await self.bot.fetch_user(thingy))

This is probably really ugly but it does the trick

sage tendon
errant trout
#

...you've never used for i in range?

sage tendon
#

nop

errant trout
#

open the schools....

proven valley
#

should I just save the @mention paramter directly to my database instead of pulling the user ID and then doing .mention?

errant trout
#

eh

#

saving ID is more useful

proven valley
#

I would have to save both

errant trout
#

well you don't, user.mention is just <@{id}>

#

no need to fetch

proven valley
#

oh man

#

like this?

#

player1 being the ID

errant trout
#

no

#

like <@id>

#

try typing it in chat

#

with someone's id

proven valley
#

I see

sage tendon
proven valley
#

3373% faster love to see it

errant trout
#

it's one of the first python concepts you'd ever learn apensive

#

not knowing for i in range is like not knowing how to walk

sage tendon
#

well how would it be used to skip the first index here

errant trout
#

for i in range (1, 9) does exactly that

#

because it skips 0

#

no messing with bools or whatever

sage tendon
#

ah

proven valley
#

very useful, used it many times for school projcets to go through csv's and such

shell radish
sage tendon
#

see, i see it like this
my code is just so good that i never needed for i in range

shell radish
#

toothy i'm revoking your helper priveledges

errant trout
#

you sprinted ahead while abandoning the roots, for shame
mods, subject him to a month long codeacademy course

proven valley
#

this guy just got demoted live

sage tendon
#

-w-

real glacier
#
view.add_item(discord.ui.Button(label="Test Button, Does Nothing", row=1))``` how do i await an interaction response with this?
errant trout
#

well

#

you're kinda skipping a few things

real glacier
#

which part

errant trout
#

there's a couple examples i'd refer to

rugged lodgeBOT
#

Here's the confirm example.

#

Here's the counter example.

errant trout
#

these both show slightly different approaches to using and responding to buttons

real glacier
#

are those related to ext.pages?

errant trout
#

not particularly? but ext.pages does make use of views

real glacier
#

alr isee

#

oo i understand now, ty c:

hazy turret
#

Is there a better way to search for a message on the Discord server to make as few API requests as possible and thus not run the risk of running into a rate limit if I want to do this on many servers at the same time?

        message = bot.get_message(message_id)
        if message is None:
            channel = bot.get_channel(channel_id)
            if channel is None:
                channel = await bot.fetch_channel(channel_id)
                if channel is None:
                    raise discord.NotFound
                message = await channel.fetch_message(message_id)
                if message is None:
                    raise discord.NotFound
            else:
                message = await channel.fetch_message(message_id)
                if message is None:
                    raise discord.NotFound```
fresh sierra
#

your code has some issue in it

little cobalt
#

.tag partial-objects

sly karmaBOT
#

Partial Objects

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

Methods which can be used on them are

  • Partial Messageable (analogous to a Channel) - Docs
  • Partial Message (analogous to a Message) - Docs

Example Usage:

async def star_message(channel_id: int, message_id: int):
    # Get Partial Messageable object
    partial_channel = bot.get_partial_messageable(channel_id)

    # Get Partial Message
    partial_message = partial_channel.get_partial_message(message_id)

    # Add a reaction
    await partial_message.add_reaction(":star:")
fresh sierra
#

for example:

channel = await bot.fetch_channel(channel_id)
                if channel is None:
                    raise discord.NotFound
#

cant work since if fetch fail it trigger an error

hazy turret
# little cobalt .tag partial-objects

That means if I can't find the channel and message via get_channel and get_message and then work with partial_channel and partial_message, will these objects be in the bot's cache the next time and can be found via get_channel and get_message?

fresh sierra
#

you can directly work with partial

#

depending on what u want to do with the message object

hazy turret
hazy turret
fresh sierra
#

if i understood partial does not do api call

hazy turret
# fresh sierra so you can use partial

Then I can just simplify the whole thing without getting into rate limits?

        partial_channel = bot.get_partial_messageable(channel_id)
        partial_message = partial_channel.get_partial_message(message_id)

        await partial_message.edit(embed=embed)```
fresh sierra
#

i think so

hazy turret
fresh sierra
#

but in the edit thing yes

hazy turret
#

I have an error counter to reset the whole thing if there are too many errors on the server.
Will this continue to work without any problems?

    try:
        partial_channel = bot.get_partial_messageable(channel_id)
        partial_message = partial_channel.get_partial_message(message_id)

        await partial_message.edit(embed=embed)

    except discord.NotFound:
        handle_not_found_error(guild_id)
    except discord.Forbidden as e:
        handle_forbidden_error(guild_id, e)
    except discord.errors.DiscordServerError as e:
        # Log the error and handle the retry logic
        await asyncio.sleep(10)


def handle_not_found_error(guild_id):
    logger.warning(f"Message not found in guild {guild_id}")
    error_count[guild_id] += 1
    reset_if_necessary(guild_id)


def handle_forbidden_error(guild_id, e):
    logger.warning(f"Missing access on guild {guild_id}: {e}")
    error_count[guild_id] += 1
    reset_if_necessary(guild_id)```
fresh sierra
#

why do you have an error count for each guild ?

#

there is maybe a better way to handle that

#

than a try except for each thing

#

maybe using the event on_command_error if its inside a command

hazy turret
#

If the message was not found 3 times on the Guild, the Guild should be removed so that the Guild is no longer processed during the next run.

fresh sierra
#

like if the first time it was notFound

#

why suddently it will not raise a notfound ?

hazy turret
#

That's a good question ๐Ÿ˜„

fresh sierra
#

what you can maybe do is

hazy turret
#

Then I don't need a counter but throw the Guild out directly when I get NotFound for the first time ๐Ÿ˜„

fresh sierra
#

        partial_channel = bot.get_partial_messageable(channel_id)
        partial_message = partial_channel.get_partial_message(message_id)
    try:
        await partial_message.edit(embed=embed)

    except discord.NotFound:
        remove from list
    except Exception as e:
        logger.warning(f"Error during ... 
: {e}")
#

maybe something like so would be more convenient

proven valley
#

can I make it so that a link in an embed triggers a slash command?

dense summit
#

Hey there, i started to working on a feature in my bot and i thought about using the tasks extension although i have some questions. The feature should allow a user to start a monitor that sends a request every X seconds to an api endpoint till X parameter is true. With tasks how would i go about starting a task that is linked to a user?

sage tendon
lethal loom
#

Hi, Why?

Ignoring exception in modal <cogs.dev.xenority.verify1 object at 0x7eff5c75c6a0>:
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.10/site-packages/discord/ui/modal.py", line 341, in dispatch
    await value.callback(interaction)
  File "/home/container/cogs/dev/xenority.py", line 135, in callback
    channel = self.bot.get_channel(log_channel)
TypeError: Client.get_channel() missing 1 required positional argument: 'id'```'
        log_channel = SERVER_SYSTEM["log_channel"]
        print(f"Log: {log_channel}")
        channel = self.bot.get_channel(log_channel)
echo wraith
lethal loom
# echo wraith try get_channel(id=log_channel)
Ignoring exception in modal <cogs.dev.xenority.verify1 object at 0x7fad7a574940>:
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.10/site-packages/discord/ui/modal.py", line 341, in dispatch
    await value.callback(interaction)
  File "/home/container/cogs/dev/xenority.py", line 135, in callback
    channel = self.bot.get_channel(id=log_channel)
TypeError: Client.get_channel() got some positional-only arguments passed as keyword arguments: 'id'```
#

this is my codee

    def __init__(self, bot: discord.Bot, *args, **kwargs) -> None:
        self.bot = bot

        super().__init__(*args, **kwargs)

        global code
        code = ""
        zeichen = "QAYXSWEDCVFRTGBNHZMJUIKLOP1234567890"
        long = int("10")
        for _ in range(long):
            code = code + secrets.choice(zeichen)

        self.add_item(discord.ui.InputText(label=f"GEBE HIER DEN FOLGENDEN CODE EIN: {code}", placeholder=f"{code}"))

    async def callback(self, interaction: discord.Interaction):
        user = interaction.user
        if self.children[0].value == code:
            role = interaction.guild.get_role(SERVER_SYSTEM["verify_role_id"])
            remove_role = interaction.guild.get_role(SERVER_SYSTEM["join_role_id"])
            await user.add_roles(role)
            await user.remove_roles(remove_role)
            await interaction.response.send_message(f":tada: Du bist verifiziert!", ephemeral=True)
            log_channel = SERVER_SYSTEM["log_channel"]
            print(f"Log: {log_channel}")
            channel = self.bot.get_channel(id=log_channel)
            embed = discord.Embed(title="Verifizierung", description=f"{user.mention} hat sich Erfolgreich Verifiziert", color=int(get_config("colors")["green"], 16))
            embed.timestamp = datetime.utcnow()
            embed.set_footer(text=f"ID: {user.id} ")
            await channel.send(embed=embed)
        else:
            await interaction.response.send_message(f":x: Du hast einen falschen Code eingegeben!", ephemeral=True)
            log_channel = SERVER_SYSTEM["log_channel"]
            print(f"Log: {log_channel}")
            channel = self.bot.get_channel(id=log_channel)
            embed = discord.Embed(title="Verifizierung", description=f"{user.mention} hat einen falschen Code eingegeben", color=int(get_config("colors")["red"], 16))
            embed.add_field(name="Falscher Code / Code", value=f"{self.children[0].value}")
            embed.add_field(name="Richtiger Code", value=f"{code}")
            embed.timestamp = datetime.utcnow()
            embed.set_footer(text=f"ID: {user.id} ")
            await channel.send(embed=embed)


class RoleButton(discord.ui.Button):
    def __init__(self):
        super().__init__(
            label="Verifiziere dich hier!",  # Text auf dem Button!
            style=discord.enums.ButtonStyle.blurple,  # Button-Fabre!
            custom_id="interaction:RoleButton",
            emoji=":greentickincircle_xenority:"
        )

    async def callback(self, interaction: discord.Interaction):
        verify = random.randint(1, 2)
        user = interaction.user

        role = interaction.guild.get_role(SERVER_SYSTEM["verify_role_id"])

        if role is None:
            return

        if role not in user.roles:
            modal = verify1(Bot, title="Xenority")
            if verify == "1":
                modal = verify1(Bot, title="Xenority")
            if verify == "2":
                ...
            await interaction.response.send_modal(modal)

        else:
            await interaction.response.send_message(f":x: Du bist bereits verifiziert!", ephemeral=True)
sly karmaBOT
# lethal loom this is my codee ```class verify1(discord.ui.Modal): def __init__(self, bot:...

1. Uninstall discord.py or any other forks of discord.py you might have with the namespace discord.
python -m pip uninstall discord.py discord -y

2a. Install py-cord
python -m pip install py-cord

2b. Update py-cord
python pip install -U py-cord

Installing other builds:
Note: You need to have git installed. Use ?tag git to find out how to install git.

Updating the module to master branch (unstable):
pip install -U git+https://github.com/Pycord-Development/pycord

lethal loom
# echo wraith .install

i only have one

aiofiles==24.1.0
aiohttp==3.9.5
aiomysql==0.2.0
aiosignal==1.3.1
annotated-types==0.7.0
anyio==4.4.0
asyncio==3.4.3
attrs==23.2.0
beautifulsoup4==4.12.3
better-ipc==2.0.3
certifi==2024.7.4
cffi==1.16.0
charset-normalizer==3.3.2
chat_exporter==2.8.0
click==8.1.7
colorama==0.4.6
contourpy==1.2.1
croniter==2.0.7
cycler==0.12.1
dnspython==2.6.1
email_validator==2.2.0
emoji==2.12.1
fastapi==0.111.1
fastapi-cli==0.0.4
feedparser==6.0.11
fonttools==4.53.1
frozenlist==1.4.1
grapheme==0.6.0
h11==0.14.0
httpcore==1.0.5
httptools==0.6.1
httpx==0.27.0
idna==3.7
Jinja2==3.1.4
kiwisolver==1.4.5
lxml==5.3.0
markdown-it-py==3.0.0
MarkupSafe==2.1.5
matplotlib==3.9.1
mdurl==0.1.2
multidict==6.0.5
NBT==1.5.1
numpy==2.0.1
orjson==3.10.6
packaging==24.1
pillow==10.4.0
py-cord==2.6.0
pycparser==2.22
pydantic==2.8.2
pydantic_core==2.20.1
Pygments==2.18.0
PyMySQL==1.1.1
PyNaCl==1.5.0
pyngrok==7.1.6
pyparsing==3.1.2
python-dateutil==2.9.0.post0
python-dotenv==1.0.1
python-multipart==0.0.9
pytube==15.0.0
pytz==2024.1
PyYAML==6.0.1
requests==2.32.3
rich==13.7.1
scrapetube==2.5.1
sgmllib3k==1.0.0
shellingham==1.5.4
six==1.16.0
sniffio==1.3.1
soupsieve==2.5
starlette==0.37.2
twitchAPI==4.2.1
typer==0.12.3
typing_extensions==4.12.2
tzdata==2024.1
tzlocal==5.2
urllib3==2.2.2
uvicorn==0.30.3
watchfiles==0.22.0
websockets==12.0
xmltodict==0.13.0
yarl==1.9.4
ytnoti==1.1.2```
echo wraith
#

also use a venv if you aren't doing so.

lethal loom
echo wraith
#

Maybe add an additional print, another one, and see if when deployed it prints it as well or not.

echo wraith
lethal loom
echo wraith
lethal loom
#
Test 123
Ignoring exception in modal <cogs.dev.xenority.verify1 object at 0x7fcac4a76380>:
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.10/site-packages/discord/ui/modal.py", line 341, in dispatch
    await value.callback(interaction)
  File "/home/container/cogs/dev/xenority.py", line 138, in callback
    channel = self.bot.get_channel(id=log_channel)
TypeError: Client.get_channel() got some positional-only arguments passed as keyword arguments: 'id'```
lethal loom
sage tendon
#

i mean, the error tells you exactly whats wrong

#

dont pass it by keyword

echo wraith
sage tendon
#

very clearly is right now

sage tendon
#

i dont think bot is initialised properly then

sage tendon
sage tendon
#

well first of all remove the id=, its wrong
and then, show where you call the modal in your code

lethal loom
# sage tendon well first of all remove the `id=`, its wrong and then, show where you call the ...
    def __init__(self):
        super().__init__(
            label="Verifiziere dich hier!",  # Text auf dem Button!
            style=discord.enums.ButtonStyle.blurple,  # Button-Fabre!
            custom_id="interaction:RoleButton",
            emoji=":greentickincircle_xenority:"
        )

    async def callback(self, interaction: discord.Interaction):
        verify = random.randint(1, 2)
        user = interaction.user

        role = interaction.guild.get_role(SERVER_SYSTEM["verify_role_id"])

        if role is None:
            return

        if role not in user.roles:
            modal = verify1(Bot, title="Xenority")
            if verify == "1":
                modal = verify1(Bot, title="Xenority")
            if verify == "2":
                modal = verify2(Bot, title="Xenority")
            await interaction.response.send_modal(modal)

        else:
            await interaction.response.send_message(f":x: Du bist bereits verifiziert!", ephemeral=True)

The Bot object is a import
from bot import Bot

the bot.py

import datetime
import asyncio
import os

from discord.ext import commands
from discord import InteractionContextType, IntegrationType

from colorama import *

from utils.funcs import get_database_tables

class Bot(commands.Bot):
    def __init__(self):
        intents = discord.Intents.all()
        command_prefix = commands.when_mentioned_or("-")
        default_command_context={InteractionContextType.guild}
        default_command_integration_types={IntegrationType.guild_install}
        super().__init__(command_prefix=command_prefix, intents=intents, default_command_context=default_command_context, default_command_integration_types=default_command_integration_types)
    
    async def on_ready(self):
        total_members = sum([len(guild.members) for guild in self.guilds])
        average_members = total_members / len(self.guilds)

        bot_infos = f"| Bot Name --> {self.user}  (ID: {self.user.id})"
        bot_commands = f"| Commands --> {len(self.application_commands)}"
        bot_stats = f"| Guilds   --> {len(self.guilds)} mit {total_members} Usern, Durchschnitt: {average_members:.2f}"
        
        length_bot_infos = len(f"| Bot Name --> {self.user}  (ID: {self.user.id})")
        length_bot_commands = len(f"| Commands --> {len(self.application_commands)}")
        length_bot_stats = len(f"| Guilds   --> {len(self.guilds)} mit {total_members} Usern, Durchschnitt: {average_members:.2f}")

        max_string = max(length_bot_infos, length_bot_commands, length_bot_stats)

        line = "|" + "=" * max_string + "|"

        print(Fore.BLUE + line)
        print(f"|               {self.user} ist Online               |")
        print(line)
        print("|   ____                                 _                _  |")
        print("|  / ___|   ___    _ __     ___    ___  | |_    ___    __| | |")
        print("| | |      / _ \\  | '_ \\   / _ \\  / __| | __|  / _ \\  / _` | |")
        print("| | |___  | (_) | | | | | |  __/ | (__  | |_  |  __/ | (_| | |")
        print("|  \\____|  \\___/  |_| |_|  \\___|  \\___|  \\__|  \\___|  \\__,_| |")
        print("|                                                            |")
        print(line)

        print(bot_infos)
        print(bot_commands)
        print(bot_stats)
        print(line)
        database_tables = len(get_database_tables())
        print(f"| {database_tables} Databases Loaded")
        print(line)

        for cog in self.cogs:
            print(f"| --> {cog}")
        print(line + Style.RESET_ALL)```
sage tendon
#

yea, thats not how it works

#

you cant import stuff like that