#Basic Pycord Help

1 messages · Page 71 of 1

errant trout
#

maybe we should have asked that first

sage tendon
#

What's that

#

shared hosting?

eternal kite
#

is it not good

sage tendon
#

if yes, I KNEW it

eternal kite
edgy nest
#

railway uses shared ip addresses

sage tendon
#

I KNEW IT

#

that was the first thing I asked

errant trout
#

it's one of those ones

eternal kite
#

is it not a vps?

edgy nest
#

no

shell radish
eternal kite
#

i wanted to use digital ocean but idk how to set up docker

edgy nest
#

basically how railway works (for free at least) is it shoves a bunch of things on one machine and they all use the same ip address

sage tendon
#

there's dozens

errant trout
#

what plan do you have?

edgy nest
sage tendon
#

pm2 is indeed more than enough for a discord bot

#

multiple, even

eternal kite
errant trout
#

oh i forgot railway actually killed their free plan

eternal kite
#

yeah

sage tendon
#

all free services eventually crumble lol

eternal kite
sage tendon
#

it's not

#

it's a single command

errant trout
eternal kite
shell radish
#

changing your region should be fine

sage tendon
#

just look up "pm2 run python"

eternal kite
shell radish
#

you want virginia anyways

errant trout
#

the general point is, at the scale of your bot, a service like railway isn't viable

sage tendon
#

but pm2 isn't a hosting provider its just a Linux utility

eternal kite
#

so does pm2 uses your pc to host?

sage tendon
#

you use pm2 on your vps

eternal kite
errant trout
#

if you really can't move away from railway then do at least try the fixes we presented earlier, but if you keep running into issues then it's highly recommended you look into getting a linux VPS and setting up your bot on there

eternal kite
echo wraith
#

You should probably use webhooks for sending log messages

eternal kite
errant trout
#

if pm2 is scary, you can even use simpler utilities like screen or tmux

eternal kite
sage tendon
errant trout
#

yeah ik but people find things arbitrarily scary

echo wraith
errant trout
#

webhooks also have a lower ratelimit

eternal kite
#

wait im getting a lot of pings again one sec

errant trout
#

regular channel sends are 5 per 5 while webhooks are 5 per 2 or so

lapis dock
#

I only pay $4 for a dedicated IP droplet on digital Ocean

sage tendon
#

is a droplet a vps

echo wraith
#

I pay way too much for a cluster of servers in openstack

sage tendon
#

god I hate when services make up a completely custom set of terms

lapis dock
sage tendon
#

a friend of mine has an old plan and the vps is like 1.30 per month

lapis dock
eternal kite
#

or the cost is calculated by ur usage

lapis dock
#

Not entirely sure but I think I have to use a lot of network to get charged

sage tendon
#

a regular VPS is unlimited amount of compute time, and the main differentiation is amount of RAM and type and amount of disk
net bandwidth is usually insanely high so you'd never reach it

eternal kite
#

my bot is using a bunch of networks cuz my bot has to send a bunch of local images

sage tendon
#

I've rarely seen less than 1TB bandwidth

lapis dock
#

500 GB bandwidth and $0.01 per GB over

eternal kite
#

railway calculates network egress

sage tendon
#

yea and 500GB is much more than my entire household uses in a month lol

#

bruh that's so expensive

eternal kite
#

lmao

#

i usually get charged more than the plan i subscribed to

sage tendon
#

for 5 bucks you can get a proper vps easily

#

less even

echo wraith
#

Infomaniak gives me unlimited bandwidth

#

.tag vps

sly karmaBOT
sage tendon
#

oh yea if you have a credit card oracle has an insane free vps tier

eternal kite
#

i tried it and it sucks

echo wraith
#

Never used it so idk

sage tendon
#

lol don't they give you a shitton of everything? whats wrong with it

eternal kite
#

it's not user friendly

sage tendon
#

you get like 40GB ram on the arm one

eternal kite
#

at least for me

sage tendon
#

do they give you a terminal or ssh

eternal kite
#

i forgot the details but the name reminds me of a hard time

sage tendon
#

lol

eternal kite
#

it was back in 2021

lapis dock
sage tendon
#

just put a note that it's free and thus nothing is guaranteed

shell radish
#

didn’t GalaxyGate get a data breach

stoic patio
#

if a msg is sent in a forum channel, what is the message.channel object type?

#

and if it's in a vc channel, is the channel type VoiceChannel/StageChannel?

sage tendon
#

channeltype should be thread

#

voicechat, no clue, if i had to guess i'd say textchannel

#

just try and print it

lapis dock
#

Pretty VoiceChannels are messageable, so it would just be a VoiceChannel object

sage tendon
#

the docs dont mention VoiceChannel as a valid type for message.channel tho

stoic patio
#

that's what i'm saying

sage tendon
#

just try it and print the type then we know

lapis dock
#

I think the docs are just out of date
It is typed as
MessageableChannel

PartialMessageableChannel = Union[
    TextChannel, VoiceChannel, StageChannel, Thread, DMChannel, PartialMessageable
]
MessageableChannel = Union[PartialMessageableChannel, GroupChannel]
sage tendon
#

weird

round heart
#

Heyhey. Can someone remind me how I can add a thumbnail in an Embed with a file I have in BytesIO?

IIRC there's something with attachment://, but I can't find any relevant examples

#

Oh, do I add it as a file attribute to the message? (I would think that would show separately)

#

ah-hah! Conversation between @echo wraith and @shell radish proves useful

echo wraith
#

it still mentioned me lol

round heart
#

Audible or just badged? I added silent

echo wraith
#

Hmm I forgot

dusky ermine
#

Getting the following error when trying to run a Pycord bot on Python 3.13 using MacOS

Traceback (most recent call last):
  File "/Users/<redacted>/Documents/MyPrograms/ProfitGreen/bot/main.py", line 2, in <module>
    import discord
  File "/Library/Frameworks/Python.framework/Versions/3.13/lib/python3.13/site-packages/discord/__init__.py", line 27, in <module>
    from . import abc, opus, sinks, ui, utils
  File "/Library/Frameworks/Python.framework/Versions/3.13/lib/python3.13/site-packages/discord/abc.py", line 58, in <module>
    from .voice_client import VoiceClient, VoiceProtocol
  File "/Library/Frameworks/Python.framework/Versions/3.13/lib/python3.13/site-packages/discord/voice_client.py", line 55, in <module>
    from .player import AudioPlayer, AudioSource
  File "/Library/Frameworks/Python.framework/Versions/3.13/lib/python3.13/site-packages/discord/player.py", line 29, in <module>
    import audioop
ModuleNotFoundError: No module named 'audioop'
shell radish
#

pip install audioop-lts

#

or whatever your pip is

dusky ermine
#

It works now, thanks

echo wraith
#

.tag audioop

sly karmaBOT
#

Pycord 2.6.1 may work with Python 3.13, but it is not officially supported and can cause various issues. Until Pycord 2.7 includes official support for Python 3.13, it is recommended to use a previous version.

For voice features in Pycord versions before 2.7, you might need to run pip install audioop-lts. Some users have reported issues with voice features when using Python 3.13, so ensure that you clear the __pycache__ and .pyc files before running your bot.

maiden bloom
#

PyCord doesn't return cancelled_at

guild_entitlements_iter = guild.entitlements(exclude_ended=True)
guild_entitlements = await guild_entitlements_iter.flatten()
errant trout
maiden bloom
errant trout
#

ah

#

yeah it'll be in 2.7 (lol)

#

or master if you want it now

maiden bloom
#

Gib release plz soontm

round heart
#

Ugh. What the hell are you supposed to typehint when you get_channel and pass it into a function? If I typehint discord.TextChannel, then my calling method complains "Expected type 'TextChannel', got 'GuildChannel | Thread | PrivateChannel | None' instead "

If I typehint discord.abc.GuildChannel, then my .send() and .is_news methods show warnings

If I typehint discord.abc.MessageableChannel, then I get a runtime error "AttributeError: module 'discord.abc' has no attribute 'MessageableChannel'"

echo wraith
#

You should check it with isinstance

sage tendon
#

what warnings does .send() show tho?

echo wraith
#

Which makes total sense

silk spire
#

Or just channel: discord.TextChannel | None = ... # type: ignore 🤓

echo wraith
#

😭

deft kestrel
#

Anyone know why this been showing since the discord update

sage tendon
#

read the last line

deft kestrel
#

Oh yeh 😂

deft kestrel
sonic onyx
#

I wanna know if this is alright.

#

It works, but I'm looking to see if the structure is sound.

#

though I think I'm actually going to replace the literal file location with a static string so that its easy to read and change for all my functions.

#

also I added break after is_admin = true since there's no reason to go through the rest of the list if a match was already found

little cobalt
sonic onyx
little cobalt
#

Opening and writing a file is not asyncio, so its gonna block the whole bot

sonic onyx
#

Each user has a different file.

#

This is only done because its a bot for ~30 people

frail basin
#

Saves the for loop

little cobalt
sonic onyx
little cobalt
#

Yea

sonic onyx
little cobalt
#

Use something like aiofiles

sonic onyx
#

Ah I see. I'll try using that instead.

little cobalt
#

Its pretty simple to use

sonic onyx
#

@little cobalt I'm now using this. It works in discord. Does that look about right?

little cobalt
#

What type of File is that?

sonic onyx
#

.txt

little cobalt
#

You forgot to await a write

sonic onyx
#

Oh

#

fixed it

little cobalt
#

And add encoding="UTF-8" next to the "r"

sonic onyx
#

What does that mean?

little cobalt
#

So, for me, if I want to write something in my language. It doesnt know what do to with ä, ü or ö. And the encoding is for that.

sonic onyx
#

So, I'm trying to use this but I don't know where to put @commands.cooldown in my function to get it to work.
docs.pycord.dev/en/stable/ext/commands/api.html#discord.ext.commands.cooldown

sonic onyx
#

Where do I put this: @discord.ext.commands.cooldown(rate, per, type=<BucketType.default: 0>)
in

sage tendon
#

below the command decorator

sonic onyx
#

This isn't working though. The program just crashes.

silk spire
#

Elaborate

#

Nothing just crashes without an error

sonic onyx
#

When I open it, it instantly closes.

sly karmaBOT
sonic onyx
#

I don't get any error. It just closes itself. It doesn't do so when I just remove that line.

sonic onyx
#

commands is imported from discord.

sonic onyx
#

Ok, I have a proper error. I was running the program the wrong way where no error was showing.

shell radish
#

should be discord.ext.commands

sonic onyx
shell radish
#

yes

sonic onyx
#

This works. Thanks.

#

the example block I saw elsewhere was just using @commands.cooldown() so I didn't know why it wasn't working.

echo wraith
sonic onyx
#

Oh, so I missed a step by importing commands directly from discord

fresh sierra
#

Like a class for all of ur related « database » so you can do get_balance(target_id) and it just return you the thing. Might be way more clear if you use it in different commands

sonic onyx
#

One thing I'm not really understanding is how events are ordered.
We have @bot.command() which is establishing how the command is seen and indicating that I'm implementing a bot command. The function that defines the command's behavior follows it.
Sandwiched between @bot.command() and the function itself is @commands.cooldown(), which gives the command a cooldown and throws an exception if the command is used on cooldown, but this exception doesn't go to the function that defines the command's behavior(?), so where do I handle it?

fresh sierra
#

Or use a general event
on_command_error

sonic onyx
#

I think I need to read about decorators more, because from the documentation I know what to use but not how to use it

marble compass
#

Is there any downside to using commands.Bot over discord.Bot when fully operating on app commands?

My friend says commands.Bot provides additional functionality, which may or may not be useful, but he doesn't see any harm in keeping it.

Just want to confirm if there's any drawback to this approach.

frail basin
#

.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)
frail basin
#

@marble compass

marble compass
fresh sierra
#

but if you will not use at all prefixed commands there is no need at all to use commands.Bot

marble compass
#

yeah I have not been able to convice him, he says just keep the options available

#

I might suggest using bridge.Bot instead then

fresh sierra
#

rn bridge is kinda broken

marble compass
#

oh okay

fresh sierra
#

how should i do to pass some local file as thumbnail inside a paginator ?

#

each pages should have a different one

#

(there might be a lack of support in the library for that)

edgy nest
#

send a file and use attachment://filename

sonic onyx
#

So I'm getting this error, but in the documentation it says that it is discord.ext.commands.on_command_error()

sage tendon
#

you are using it from the wrong namespace

#

wait nvm lol

sonic onyx
#

I can't seem to figure how to handle errors that are caught before entering my function (like by commands.cooldown).

fresh sierra
fresh sierra
#

Another issue would be that when passing from a pages to another one I will need to reset attachements which is not possible

sage tendon
#

very possible

#

bots can add and delete files and attachments as they see fit

fresh sierra
#

How should I do ?

edgy nest
fresh sierra
#

let me try again, it gaves me an error first( ok its not in the same way)

echo wraith
#

ping me if I need to pr smth :p

fresh sierra
#

ok but everything works, just i needed to use Page and not just do pages = embeds

#

thanks plun

fresh sierra
fresh sierra
#

usually we have to do attachements = []

echo wraith
# fresh sierra

I had this issue when using another discord lib for python some time ago, and didn't have it w pycord

fresh sierra
#

so i dont really know how i should do to remove them

sage tendon
#

why attachments=[]?

fresh sierra
#

that's how we usually do

sage tendon
#

doesnt passing files= handle that already

fresh sierra
#

files = [] will not remove any previous file on it

sage tendon
#

hm

#

yea no clue then honestly

fresh sierra
#

i think it might be lack of support

#

i'll check the code

echo wraith
#

@fresh sierra if you manage to have a pure pycord mrc I can take a look

echo wraith
#

pycord minimal reproductible code

#

using just pycord

fresh sierra
#

i'll do that for u

echo wraith
#

so without using Lumabot, etc...

fresh sierra
#

and here it is

        pages_list = []
        for i in range(3):
            embed = discord.Embed(title=f"Embed n°{i}")
            files = []
            if i == 2:
                async with aiohttp.ClientSession() as session:
                    async with session.get(
                        "https://cdn.discordapp.com/avatars/707196665668436019/948a1b5911d8529767c8be676f7d5b92.png?size=2048"
                    ) as response:
                        if response.status == 200:
                            test_file = discord.File(
                                io.BytesIO(await response.read()), filename=f"test.png"
                            )
                            files.append(test_file)

            embed.set_image(url=f"attachment://test.png")
            page = pages.Page(embeds=[embed], files=files, attachments=[])
            pages_list.append(page)

        paginator = pages.Paginator(pages=pages_list)
        await paginator.respond(ctx)
#

@echo wraith

errant trout
# fresh sierra

this happens when existing attachments on the image are no longer able to target an attachment:// found in an embed
passing attachments into Page does nothing

fresh sierra
#

you might need to change the repond according to what you are using

fresh sierra
errant trout
#

but hm, paginator is meant to clear attachments every time...

fresh sierra
errant trout
#

might have guessed the issue but not 100% sure

errant trout
#

i.e. paginator.send

#

and see if you have the same issue

fresh sierra
errant trout
#

yes

fresh sierra
errant trout
#

hm it's also broken on paginator.send? strange

fresh sierra
#

Possible, but strange because it’s using attachments =[] at each edit

#

So it’s strange that it’s not removing it

errant trout
#

ahhh i guess the send method technically wouldn't change anything...

#

maybe better to test directly

errant trout
fresh sierra
errant trout
#

(this likely needs to change regardless of this issue you're facing, as it means webhook.edit_message(attachments=[]) does not work)

errant trout
#

hell yeah

fresh sierra
#

man are you alright ?

errant trout
#

LOL

fresh sierra
#

how did you find this in like second

errant trout
#

message.edit looked fine so the answer was webhook

errant trout
fresh sierra
#

well it doesnt look quite obvious for me but that's impressing ;)

errant trout
#

actually

#

that fix might be naive

#

eh

#

it'll probably break if you pass files without attachments

#

if attachments is not MISSING or _attachments:

fresh sierra
#

this works fine:
@Lumabot Test#4042debug exec

async with aiohttp.ClientSession() as session:
    async with session.get("https://cdn.discordapp.com/avatars/707196665668436019/948a1b5911d8529767c8be676f7d5b92.png?size=2048") as response:
        if response.status == 200:
            test_file = discord.File(
                io.BytesIO(await response.read()), filename=f"test.png"
            )
msg = await ctx.send(file=test_file)
await asyncio.sleep(1)
await msg.edit(attachments=[])
errant trout
#

i mean webhook edits (e.g. edit after defer) with files wouldn't work with the first fix i suggested

#

assuming the user didn't pass attachments

#

(which is usually the case)

errant trout
fresh sierra
errant trout
#

no the code you posted isn't affected

#

because those are normal message edits

fresh sierra
#

it should be a webhook since i defer before no ?

errant trout
#

i guess i'll break it down

fresh sierra
#

because from my side even using it inside an interaction works fine, defering before sending the paginator

errant trout
#

simplified version of current webhook code ```py
_attachments = []
if attachments is not MISSING:
_attachments = [a.to_dict() for a in attachments]
if files:
for index, file in enumerate(files):
...
_attachments.append(attachment_info)
if _attachments:
payload["attachments"] = _attachments

- this was an issue because `if _attachments` is `False` if the user passes `attachments=[]`
- if we change it to `if attachments is not MISSING`, this is `False` if the user passes `files` and not `attachments` - `files` requires the `_attachments` list, so certain attachment info would never send
- the final adjustment suggested was `if attachments is not MISSING or _attachments` - this catches every case (if the user passes `attachments=[]` then `attachments is not MISSING`, and if the user passes `files` then `_attachments` is truthy)
#

this was not an issue anywhere else because they handle it differently

sonic onyx
#

How do I make the response to a command private? Like the commands that yield a ‘only you can see this’ message

sage tendon
#

ephemeral=True in the response

nocturne jewel
#

how to put that status in a bot?

#

client status

nocturne jewel
#

File "/Minecraft/soundboards/bot.py", line 304, in callback vc = await user.voice.channel.connect() ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/dist-packages/discord/abc.py", line 1986, in connect voice = cls(client, self) ^^^^^^^^^^^^^^^^^ File "/usr/local/lib/python3.11/dist-packages/discord/voice_client.py", line 233, in __init__ raise RuntimeError("PyNaCl library needed in order to use voice") RuntimeError: PyNaCl library needed in order to use voice ^Croot@v2202503261488325026:/Minecraft/soundboards# ^C root@v2202503261488325026:/Minecraft/soundboards# ^C root@v2202503261488325026:/Minecraft/soundboards# ^C root@v2202503261488325026:/Minecraft/soundboards# pip install PyNaCl Requirement already satisfied: PyNaCl in /usr/lib/python3/dist-packages (1.3.0)

Great.

lapis dock
edgy nest
nocturne jewel
edgy nest
#

what command are you us9ing to run your bot

nocturne jewel
#

python3.11 bot.py it is the same

edgy nest
#

something on your system is screwed up then

sonic onyx
void schooner
#

is it possible to make the bot send a message without the "<user> used <bot>" part above it? if yes, then how?

errant trout
#

but note you have to respond to a command

#

so either:

  • use respond(..., ephemeral=True) to send a hidden response, then ctx.send after
  • if you don't mind a *little* jank, you can do ctx.defer(ephemeral=True) -> ctx.delete() -> ctx.send(...)
void schooner
errant trout
#

no, just send but you might have to go to channel.send in docs

#

send and respond more or less use the same arguments

void schooner
errant trout
#

ctx.send should work regardless? oh well

void schooner
errant trout
#

no, defer -> delete

#

just try it, you'll understand

void schooner
errant trout
#

ah both defer and delete should be await

void schooner
#

oh

#

yep, that works now. Thanks 😊

eternal kite
#
print(member.roles, member.roles[0], member.roles[0].id)

im getting this error from the code above
Application Command raised an exception: AttributeError: 'list' object has no attribute 'id'

#

kinda weird though but that is what written in the docs

errant trout
#

print them separately

#

and see what the result is

eternal kite
#

i found the bug

#

thanks to my procrastination it took an hour

void schooner
# errant trout that would be ctx.send
async def say(ctx, msg: str):
    await ctx.defer(ephemeral=True)
    await ctx.delete()
    await ctx.channel.send(msg)

I’m assuming ctx.channel.send doesn’t work in DMs and groups? What to use in that case?

errant trout
#

It works in DMs

void schooner
#

interesting…

errant trout
#

But for groups, bots can only exist through interactions

#

So you can only respond

#

(You can also do user.send to DM a user)

void schooner
#

just tried in a DM and it’s the same as in a group: it sends a buffering message “sending command” or something (greyed out), deletes it, and doesn’t do anything else

errant trout
#

Idk send works regularly in direct messages

sage tendon
#

the user might have disabled bot DMs

#

and no you can't send a message with a bot into a DM

#

only as response to a slash command

errant trout
#

Well in this context I think they're running a command in the dm

sage tendon
#

if anything the bot has to DM the user directly

errant trout
sage tendon
errant trout
#

Yeah we already established group dms are different

sage tendon
#

aren't they talking about 1:1 DMs too rn

errant trout
#

I guess they never specified

errant trout
#

is it you and the bot or you and another user

void schooner
errant trout
#

Then respond only

void schooner
#

Oh

errant trout
#

Because the bot cannot exist in another user's DM

void schooner
#

Makes sense

errant trout
void schooner
#

is there like a ctx.typeof or something to check if I’m in a dm/group? that way if true I can do respond instead

errant trout
#

You can do isinstance on ctx.channel

void schooner
#

Thanks

errant trout
#

there's discord.DMChannel and discord.GroupChannel

#

While discord.abc.GuildChannel will cover every guild channel

#

(You could also check if channel.guild is None, but that doesn't cover the difference between DM and Group)

void schooner
#

it do be kinda weird to see the message body in the context, but this works in DMs and Group Chats now. Thanks 😊

sage tendon
eternal kite
#

how do i get the webhook class with a webhook url

rugged lodgeBOT
eternal kite
#

i read it yeah but what's the session arg?

echo wraith
#

an aiohttp session

eternal kite
#

i've found examples but they did not pass the session argument

echo wraith
ivory beacon
#

on_message_edit() Triggering Like on_message() in Certain Servers
idk why 😔

sage tendon
#

more info?

lapis dock
# void schooner is there like a ctx.typeof or something to check if I’m in a dm/group? that way ...

https://docs.pycord.dev/en/master/api/models.html#discord.Interaction.context might be a better thing to check in case discord changes something in the future. Both this and what nelo said work but I think this is the more "correct" approach as it is a specific check instead of implying from something else

jovial dagger
#

Is it possible to access the chat history in voice channels? I am able to send messages in the chat but not able to see the history.

for channel in voice:
        # get all messages for channel
        messages = await channel.history(limit=None).flatten()
        print(channel.type)
        print(channel.name, len(messages))
        print(messages)

This returns an empty list

sage tendon
#

do you have message content intent

jovial dagger
#

Yes my bot works fine on text channels and is able to access history. I only need access to the messages in the voice channel chat, not any voice data.

sage tendon
#

does the bot have proper permissions in that channel too?

jovial dagger
#

From my knowledge, it should have adequate permissions for all channels. Would voice channel chat require different permissions than regular text channels?

sage tendon
#

also i would try with a lower limit (or any limit for that matter) to see if thats the issue

sage tendon
lapis dock
#

You might also need the connect permission

jovial dagger
#

Thank you! Turns out the bot does not have permissions to view the chat

lapis dock
#

From what I can tell users cant access the chat if they cant connect

jovial dagger
#

Thank you both!

sage tendon
#

according to the docs the bot only needs read message history

jovial dagger
#

When I view it as the bot role and click on the voice channel chat it says I don't have permissions. Text channel ones are fine

#

It says I can't view the history

void schooner
lapis dock
#

No,
ctx.interaction.context == discord.InteractionContextType.xxx

sage tendon
#

basic python: :o

void schooner
sage tendon
#

i mean interaction isnt an iterator lol

brave nacelle
#

@echo wraith sorry to @ you but im trying to use your reactiveviews project and im having some trouble. when i run the code below i get the following error TypeError: ReactiveView.send() missing 1 required positional argument: 'ctx' and also just to test the reactiveviews out i have your counter example in the counter_test class so i doubt its an issue with that

    @discord.ui.button(label="Continue", row=4, style=discord.ButtonStyle.success)
    async def continue_callback(self, interaction: discord.Interaction):
    
        await counter_test.send(interaction)
sonic onyx
#

So I tried defining a cog and I threw my hello command in there, hoping that the command would become /greetings hello but instead it stayed /hello and is now requesting ctx as a passed variable. How do I get a command to be /greetings hello?

errant trout
rugged lodgeBOT
#

Here's the slash cog groups example.

sonic onyx
errant trout
#

why wouldn't you

#

for what you're asking for specifically, you need to define something like greetings = SlashCommandGroup(...) and then use @greetings.command

#

(conveniently, this matches the linked example above)

echo wraith
#

Nw for the ping

fresh sierra
#

how can i correct the typehint for it typehint that as discord.Emoji ?

class EmojiConverter(commands.Converter):
    async def convert(self, ctx: LumabotContext, argument: str) -> discord.Emoji:
        emoji = EmojiSetupCog.get_emoji(ctx.guild, argument)
        if not emoji:
            raise commands.CommandError(ctx.translator.emoji.not_found)

        return emoji
echo wraith
#

But idk if ext.conmands supports it

fresh sierra
#

yep it does not

echo wraith
#

typing.cast

fresh sierra
#

is this a bad practice (for the roles)

await member.edit(
    nick=member_data["nick"],
    roles=[discord.Object(role_id) for role_id in member_data["roles"]],
)
fresh sierra
#

i want to put back each nick + roles saved as the moment

echo wraith
#

I mean that would work as long as the roles still exist

#

but yeak

round heart
#

This is blasphemous, but has anyone used any of the AI platforms for all the discord.ui boilerplate stuff for Views? I just asked Claude to write something and on a skim it looks fairly workable, but curious if there are any specific gotchas I should look out for.

sage tendon
#

make sure you understand it before using AI for it

round heart
#

Well of course, just want to speed up development of the shitty parts.

flat wind
#

I have been granted the members intent from discord minutes ago. I just added it to my bot and restart it. Now the on_guild_join and on_ready events are not triggered.
My idea was that the bot is caching all users. But is there any argument to ask him to not store them at start ?
FYI : My bot is in 32k server for around 3.9M users

sage tendon
#

yea thats gonna take a while to start

fresh sierra
flat wind
fresh sierra
#

yep, both can work but because of that you will no longer have all member of all guild cached

flat wind
fresh sierra
#

since you can use guild.fetch_member(limit=None) to get all member in 1 request

sonic onyx
#

So I put my project on a different computer. Installed python, pip, and the pycord library in accordance with the install instructions, but it says ‘discord’ has no attribute ‘bot’ when I run bot = discord.Bot(intents = intents)

#

This is all that I have up to the error

shell radish
#

check if what you installed is the right thing

modern trail
shell radish
#

if you are using pip, then use pip list and send the output

sonic onyx
shell radish
#

uninstall discord and discord.py and re-install py-cord

sonic onyx
#

I did that and now it gives me an earlier error.

from discord.ext import commands
Cannot import name ‘commands’ from ‘discord.ext’(unknown location)

shell radish
#

you did not re-install py-cord

sonic onyx
#

Oh weird. I didn’t delete it, just used install again. It’s working after I explicitly deleted it then installed it

#

Thanks

lapis dock
modern trail
#

oh interesting

#

and annoying

lapis dock
#

I don't see any reason why they would do that intentionally.

modern trail
#

that must be it though

#

as if I needed more reasons to hate this update

lapis dock
#

I almost wonder if they use text inputs throughout the app and wanted their titles to be consistent but forgot that it would affect bots to

modern trail
#

I certainly wouldn't put it past them

fresh sierra
#

Is there any way to implement a timeout for the view that renew after each interaction ?

echo wraith
#

it's already the case ?

#

I think ?

errant trout
#

yes, timeout is refreshed on every interaction

fresh sierra
#

let me try

errant trout
#

Go read the code GuraSquintSmol

fresh sierra
#

idk sometime im clicking the button and it get disabled

#

maybe there is another reason for this disable

#

is there a max timeout that get trigger or something like that ?

lapis dock
#

not unless you implement it yourself

fresh sierra
lapis dock
#

If you are replacing the view it will go with whatever timeout that view has

fresh sierra
#

so it will not keep it mind the old timeout

#

(5min timeout on the first view, edit the message for another view,the first view will never timeout and so edit the message )

lapis dock
#

It shouldent, but I guess it is possible that is a bug

errant trout
#

uhh strictly speaking if you edit a view over another, there's no existing logic that stops the old view

fresh sierra
#

so that might be why i had that feeling about the timeout

#

so we should impletement something that stop the old view from working right ?

#

also can be memory efficient

errant trout
#

you can try but it's not very straightforward

fresh sierra
#

should i do a pr or should we wait until the component v2 ?

#

(try to make a pr)

echo wraith
#

@fresh sierra if you don't wanna do it lmk 🙈

fresh sierra
lapis dock
#

components v2 should not effect this fix

sage tendon
#

affect*

lapis dock
#

fdajhgabj

echo wraith
#

Is it possible to know when an automod rule is enabled or disabled?

lapis dock
echo wraith
#

Thy Wolfy

lofty parcel
errant trout
#

they're the same

#

but in that screenshot, they were using bot.command inside a cog; this syntax doesn't work

lofty parcel
#

Ah so they're just an alias

void schooner
#

Any examples of OOP where slash commands are declared within the class? Or is it not possible?

Here there’s a class that doesn’t do anything other than subclass (and logs something, but that’s mot useful), and slash commands are still declared outside the bot class, making OOP somewhat pointless: https://guide.pycord.dev/popular-topics/subclassing-bots

errant trout
#

uhhh if you mean in the bot subclass, it's never realllyyyy been designed that way

#

that's mainly relegated to cogs

#

we probably could add support for it? but might be strange to put it in the final versions of v2

sage tendon
#

my main question would be why

sage tendon
#

there's already 3 different intended ways to put commands into the bot, and probably more ways if you do it completely manually

echo wraith
#

Yeah frankly I don't see any need for another way of doing things

errant trout
#

i don't particularly care either way, but i can see why people find it strange that you can't define commands in the bot subclass

sage tendon
#

@self.command doesn't work right

fresh sierra
#

what are the limit for the ban ?

#

i have the impression here that its 2000 per 24h however what does that mean for non guild memebrs ?

sage tendon
#

it's per guild no? doesn't matter if member or not

#

and yes lala said it's 2000 per day

fresh sierra
#

but ok the non guild members had me a bit lost

errant trout
#

strange but discord probably doesn't want people mass banning random IDs?

#

i.e. the 2000 limit doesn't apply if, theoretically, everyone you ban was in the server when you banned them

sage tendon
#

according to lala, no

errant trout
#

from everything i just searched that is the case, but it's possible the behavior changed GuraShrug

#

(and i think the error itself makes that distinction for a reason)

sage tendon
round heart
#

So per day you can only ban 2000 ids that are not currently part of your server?

round heart
fresh sierra
#

even tho i think this limit might also be from the current member according to the example of lala

round heart
fresh sierra
#

And they ban bot for they don’t for they don’t unlimited image

#

And in my case since I’m making a backup system, if they save the ban I need to know the limit in case they have more then …

round heart
sage tendon
#

Soundboard isn't in 2.6 right? I'm trying to download sounds

echo wraith
sage tendon
#

Wil be in 2.7?

echo wraith
#

No idea depends on the review and test willingness of others, but if you test it and find (or don't find) problems you can add a comment

fresh sierra
#

So in case they have more than 2k bans I will have to implement a cooldown system to not get rate limit or smth like that

sage tendon
#

could do kicks on join as an interim solution until you can ban again

lapis dock
fresh sierra
sage tendon
#

doubt

fresh sierra
#

If I make a bot that have as only point to get free image I’ll make a loop making them join and then get the free stuff

#

Like I thinking that a simple kick will stop bot from joining is a bit unrealistic

sage tendon
#

midjourney isn't even the best model or the easiest to exploit, idk why people go for it

fresh sierra
#

Maybe cos it’s free

#

(Or u can get pretty easily free trial)

round heart
# lapis dock Pretty sure it is a per guild limit

That’s very dumb. You have to wait for a known spam account to join your server before banning it?

What about accounts that were part of your server but left (and then changed their name to something spammy)? Does it count against you when you ban those, since they’re not “currently” in the server?

lapis dock
#

I dont know much about it, it just would not make sense to have a per user limit like that because then there is essentially no limit if you can just get another user to do it ¯_(ツ)_/¯

sage tendon
#

look, 2000 bans per day is extremely high already

#

if you need that amount of bans regularly your server is unusual anyway

round heart
#

Well I am thinking of creating a moderation bot for the “unusual servers” who get high scam rates, and where administrators could get notifications about other servers and opt to pre-empt a scammer joining theirs

#

Granted I could also wait until they join and then ban, but seems silly to put a limit on one and not the other

sage tendon
#

there are already bots you can use to sync bans btw

fresh sierra
#

im a bit lost with the invitable of thread

#

is it only for text channel thread ?

#

or also forum channel thread ?

sage tendon
#

what?

fresh sierra
#

but i dont really understand when can i use it and how, for instance i cannot create a thread and pass invitibale as an arg

sage tendon
#

It's just the setting for private threads whether anyone can add people or just moderators

fresh sierra
#

i mean its not really one but

#

invitable arg is only for text_channels thread

#

and not forum channels

sage tendon
#

yea because you can't make private forum threads

nocturne jewel
#

I'm noticing that when I try to mention a user inside an embed on Discord, searching for mentions (using mentions:username) doesn't display the embed, whereas it works fine with regular messages. Does anyone know of a workaround for this?

nocturne jewel
edgy nest
#

works for me

nocturne jewel
nocturne jewel
nocturne jewel
# edgy nest works for me

it's not very user-friendly for normal users who may not know their IDs/how to use discord. Is there any workaround that lets us search by the display name or mention directly in embeds?

edgy nest
#

no

nocturne jewel
#

damn

edgy nest
#

or just put their literal display name in the embed

nocturne jewel
marble compass
#

I want to run an async method before my discord.Bot starts. Is bot.start() a better option than bot.run() for this, and what cleanup steps would I need to handle manually?

little cobalt
marble compass
little cobalt
#

cleanup?

marble compass
# little cobalt cleanup?

By cleanup, I mean properly shutting down the bot, like this:

try:
    await self.start(*args, **kwargs)
finally:
    if not self.is_closed():
        await self.close()

And also handling SIGINT/SIGTERM to stop the bot cleanly

sage tendon
#

not really

#

ig

marble compass
#

or I could do this and keep using bot.run()?

ik it will be called before its connected to the websocket

silk spire
#

Yes

solid sapphire
echo wraith
echo wraith
echo wraith
#

np

fresh sierra
#

like i had some error by not doing like so

#

(to recap run had an issue so we had to use start but to start you should use something like than asyncio else it's gonna block all of ur loop

marble compass
frail basin
#

Override the bots __init__ and call it after super().__init__

marble compass
echo wraith
#

@marble compass fyi you can wrap a link in <> to avoid the embed from rendering

fresh sierra
#

but as i said, the bot.run can be an issue

#

idk if it has been fixed

silk spire
#

There shouldn't be any issue as long as you don't do anything blocking in the "setup_hook"

round heart
#

When a Cog gets to be 2K lines, how do you break it up? 😅

You can't really do 'sub-cogs', I take it. I'm using recursive cog loading, so if I add a subdirectory I could just split them out in there, right?

fresh sierra
#

is there is multiple commands i'll make different cog with one command in each

#

if its from helper function i'll make a helper file

round heart
#

Ugh, the other sucky part is organizing command groups.

fresh sierra
#

if its from text i'll just go kfm

fresh sierra
#

but i understand your point, is it only ur commands or the view associated with etc

round heart
#

I do keep my Views in a separate directory, so that won't be too much of a problem.

#

I use multicog already, but I don't recall the intricacies; can I .create_subgroup from a group I created in another file?

fresh sierra
#

im not using it persoally but i think its something like

#

@subcommands("group name")
@commands

round heart
#

how what

lapis dock
#

Honestly IDE code folding. You should not be separating things just because they are too long.

sage tendon
#

Are those 2000 lines all for commands belonging to a single coherent topic and all duplication-free?

round heart
#

Well, multiple related topics technically, since I have some subcommands.

#

Of course, this is built up over 4 years. I'm sure if I refactored the whole thing, it would come down some. But still I hate adding things to this (relatively) giant file.

#

What's the best way to add a subcommand group to an existing group defined in another file? Like is there some way to guarantee order?

sage tendon
#

What I typically do is move long blocks that are just generic utility within your commands to cogname_helper.py

#

especially if you reuse the same logic

round heart
#

Oh, I have that already. My bot does a lot of things.

#

Nearly 26K total lines of python between Views, dataclasses, Cogs, helpers, etc.

sage tendon
#

geez

errant trout
#

if it's not the cog itself, some other file will inevitably end up being that long

#

you can't really avoid large files at that point unless you're crazy enough to split every function into its own file

little cobalt
silk spire
#

Is it me or is 2k lines in one cog like nothing?

sage tendon
#

its quite a bit

#

my cogs are 500 max

silk spire
#

But everything relevant is together so why would you break that up

silk spire
round heart
sage tendon
round heart
#

That 2K-line Cog file is just the Cog and its containing functions, not Views (another 800 lines for the related Cog) or anything else.

silk spire
sage tendon
#

then you have bloated as hell code

#

typing doesnt take up any lines..

silk spire
#

Okay maybe not 500 but typing on strict does force you to resolve every Unknown or generics that exist

silk spire
round heart
sage tendon
#

bro is making python into c

shell radish
silk spire
#

Why not? It's easier to start with it than afterward

sage tendon
#

its unnecessary

#

typing on its own is already more than you need

silk spire
#

True

limber cedar
#

hey, I had a bot running on pycord 2.4.0; I have just updated it to 2.6.0 and I'm getting a deprecation warning for this line in an on_message event:

if message.interaction is not None and message.interaction.name == "setup":

DeprecationWarning: interaction is deprecated since version 2.6, consider using interaction_metadata instead. See https://discord.com/developers/docs/change-log#userinstallable-apps-preview for more information.
sage tendon
#

fyi there's 2.6.1, you should update

limber cedar
#

anyways, i'm looking at interaction_metadata and it doesn't seem to have the information I require (the interaction command for the message)

sage tendon
#

and yea i mean its exactly what it says

limber cedar
#

i need to listen for application commands invoked on another bot by a user in my use case

#

is there an alternative since interaction_metadata doesn't have such data

#

or would it be safe for me to stick to message.interaction

#

maybe i should make a separate post for this

sage tendon
#

i mean it'll be removed eventually

echo wraith
limber cedar
#

time to remove a feature 😔

#

thanks for that link, couldn't find it

sage tendon
#

what do you need this for btw?

errant trout
#

you can continue to use message.interaction until it's removed sometime down the line, there will be advanced warning to when you can no longer use it

#

if you really want to stick to interaction_metadata, you can either

  • fetch the raw data
message = await bot.http.get_message(channel_id, message_id)
command_name = message["interaction_metadata"]["name"]```
- manually update your `discord/interactions.py` file to add the `data` attribute to `InteractionMetadata`
limber cedar
# sage tendon what do you need this for btw?

my bot listens to commands invocated by another bot to do automate certain actions (listening to a mafia bot game setup using the /setup command, listening to Dank Memer command invocations for reminders)

flat wind
#

Does anyone know how to avoid discord.errors.Forbidden: 403 Forbidden (error code: 50083): Thread is archived when someone is using a context app command ?

flat wind
#

the exception is raised in the defer... but I cannot .respond if I have this error

#

I wanted to make a post but.... I forgot an invite link and I have to wait 1h now in order to create a new post

rugged lodgeBOT
echo wraith
#

maybe check this before ?

fresh sierra
#

how can i know if im rate limit when creating webhooks ?
i would like to do something like so :

for i in range(1000)
    await channel.create_webhook()
    if rate_limit:
        await asyncio.sleep(75)
#

would be way faster than waiting 75 seconds each time, since we can create around 50 webhooks before the rate limit of 75s between each

sage tendon
#

pragmatic approach: spam webhooks until you're rate limited and figure out what exception it throws

#

nah but honestly I don't think there's a way to directly tell that, the docs only say Forbidden and HTTPException

fresh sierra
#

Since its handle by pycord it just say retry after

#

Except when all of ur bot is completely block it does raise an error but its too late

errant trout
echo wraith
#

I ❤️ webhooks

#

Except

#

Stripe webhooks

sage tendon
errant trout
#

you don't

sage tendon
#

im p sure this is doable all via one webhook tho

errant trout
#

you can pass username and avatar_url in Webhook.send

#

as such, you generally only need 1 webhook for any single channel

sage tendon
#

yea i just said what i think lumas thinking is

fresh sierra
#

i do only use 1 webhook per channel

#

but the limit is shared so its the same, creating 100 webhooks in a channel or 100 in differents will cause the same rate limit

#

and what im doing is creating a webhook for each channel and each time waiting 75s, but if i knew when i was touching the rate limit i could create like 50 without waiting and then wait

errant trout
#

don't create the webhooks beforehand, just create it on demand when you target that channel

fresh sierra
#

let me show you

errant trout
#

then what's the issue

fresh sierra
#
        async with asyncio.TaskGroup() as tg:
            for channel_data in (
                self.data["text_channels"] + self.data["voice_channels"]
            ):
                if not channel_data["messages"]:
                    continue
                channel_id = self._get_translated_id(channel_data["id"])
                channel: discord.TextChannel = await self.bot.get_or_fetch_channel(
                    channel_id
                )
                if not channel:
                    continue
                webhooks_for_channel = webhook_map.get(channel_id, [])
                backup_webhook = (
                    webhooks_for_channel[0] if webhooks_for_channel else None
                )
                if not backup_webhook:
                    await asyncio.sleep(75)

                tg.create_task(_load_message(channel_data, channel, backup_webhook))

#

my issue is tha ti would like to create as much webook as possible before rate limit and then when the rate limit hits i wait 75s for each

sage tendon
#

this may be a shot in the dark but in the discord UI, you can change a webhook's channel - can you do the same via the API to reuse the exact same webhook for every channel?

fresh sierra
#

So create new one is a bit better for I can send message in all channel at the same time

sage tendon
#

can't you just keep a counter
i mean you wont run it parallelly nor in quick succession, right?
so just do your thing until you count up to 75 webhooks, then wait?

fresh sierra
#

So the issue is that I cannot really know where am I so when I will hit the limit

#

The solution might be to send a normal request using the self.bot.jttp and so then catch the error and start using the await

sage tendon
#

i think you are way overengineering this

fresh sierra
sage tendon
#

having to restore a server is a super rare thing anyway (id hope...) so i dont see why 3 or 4 more minutes would matter (who has that many channels anyway?)

fresh sierra
#

But yeah it’s true that it’s not a big deal

sage tendon
#

an hour??

fresh sierra
#

It takes 75s per channel

sage tendon
#

do you have 5000 channels or smth

fresh sierra
#

I cannot go faster than that hitting the limit that might be around 50 webhooks

#

So if instead of directly waiting 75s for each I could skip as much as possible and then wait it will be 1h faster

errant trout
#

is this creating a new server or restoring a current server

fresh sierra
errant trout
#

meh

#

just deal with the limits

fresh sierra
#

Yeah but how ;€

errant trout
#

you could just run into the ratelimit and let the library wait it out

fresh sierra
#

Don’t you think doing the real request and catch the 429 and await it might work ?

fresh sierra
#

And also an error

errant trout
#

you're not trying to recreate it in parallel are you

fresh sierra
#

Because else I do get some global limit about webhook that 429 me

errant trout
#

right

fresh sierra
#

Do you have any counter issue about doing a real request (using pycord internal or a normal thing) and catch it ?

#

Because I don’t really see a better way rn

#

Will that messed up a bit pycord in a way

fresh sierra
fresh sierra
# errant trout for what

So i would like to do smth like this;
Webhook = Https request to create webhook
If 429: await asyncio.sleep(75) and start back to use channel.create_webhook and asyncio each time

errant trout
#

if you do it through the library, anything using HTTPClient.request will automatically wait on 429s; if you want to bypass that, you have to do manual requests through a ClientSession

fresh sierra
#

Ok thanks so like a bot.ClientSession( and then a normal requests) ?
I’ll check that when im back home

errant trout
#

you'd have to access bot.http._HTTPClient__session

#

(due to how __ vars work)

#

or you can just create your own clientsession

fresh sierra
#

Should I do like this ?
async with bot.http._HTTPClient__session() as session:
async with session.get(f"create webhook") as response:
If response.status == 429:
Flag = true
data = await response.json()

errant trout
#

not quite

fresh sierra
#

If u have some docs / examples it will be really appreciated

errant trout
#

you don't need to instansiate it

#

i.e. you start from the second line - async with bot.http._HTTPClient__session.get (or request, or whatever other method)

fresh sierra
#

And can i from the request get the webhook object ?

#

Or should I just fetch it

errant trout
#

uhhh wdym

#

the route for create_webhook returns the relevant data

fresh sierra
errant trout
#

like the Webhook object?

fresh sierra
#

Is there a class where I should do webook = Webhook(data=dzta€

fresh sierra
errant trout
#

use Webhook.from_state(data, state=bot._connection)

fresh sierra
#

Thanks !!!

#

I’ll try that when I get home

errant trout
#

allgood

fresh sierra
#

it works perfectly, i went from 1:12:48 to 0:19:13

errant trout
#

damn fair enough lol

stoic patio
#

does searching for webhooks contribute to rate limits

fresh sierra
#

I think all the route for wehooks are under the same bucket

#

So ideally don’t use channel.webhook() but more guild.webhook and itinerary

stoic patio
#

i see

#

cuz i'm trying to implement carlbot/dyno using webhooks for action logging

sage tendon
#

i never understood why they do that tbh

fresh sierra
#

so instead of sedning a message to a channel

#

they use a webhook ?

sage tendon
#

yes

#

for logs anyway

fresh sierra
sage tendon
#

that is exactly what i wonder

#

i can only imagine ratelimits

#

or shard issues

fresh sierra
#

30 messages per min per channel

#

so you have less rate limit using normal bot

stoic patio
#

i think it's a ratelimit thing

errant trout
#

the rate of logs is significantly higher than any other messages you would get on those bots

#

so offloading them to webhooks means that logging doesn't contribute to their global ratelimit

stoic patio
#

then is it possible to find the webhook to use to send stuff without fetching it every time

fresh sierra
#

using a request you just need to pass the webhook id and token in some case

sage tendon
#

i honestly dont get why webhooks are treated differently

errant trout
#

Because the only purpose of webhooks are to send messages

errant trout
#

(Or the full URL, pycord will parse it for you)

sage tendon
fresh sierra
#

because webhooks are also rate limit ;)

errant trout
#

it's painfully inconvenient to use webhooks for regular message responses, logging is the perfect use case for them

fresh sierra
#

also its not that rate-limit now that respond to an interaction is not touch at all

errant trout
#

(webhooks in general, beyond discord, are just a way for sending messages)

#

hell, channel webhooks have half the ratelimit of message create (30/min vs. 5/5s = 60/min)

#

while interaction responses have a more generous ratelimit

sage tendon
#

My point is, why give webhooks higher ratelimits if they arent locked behind anything major?

#

what makes them so different?

errant trout
#

i don't really have an "official" answer, but because the only purpose of webhooks is to send messages, and they can be utilized without a discord account or application, they're more susceptible to abuse/spam in certain conditions; they need some sort of limitation

sage tendon
#

but they have higher ratelimits than a bot, or isnt that what i just read

errant trout
#

discord documented it as lower (30/min vs 60/min)

sage tendon
#

hm

#

so if the message ratelimit is per channel for bots why use a webhook lol

errant trout
#

...but that might be outdated because im testing the ratelimit right now and i think webhooks were updated to 60/min anyway lol, so my entire argument is moot

#

because webhooks are also per channel

#

they face the same restrictions, it's just to offload the global ratelimit

sage tendon
#

oh

errant trout
#

large bots like dyno have to request an increased ratelimit anyway, so i imagine discord support also has to test them to see if they actually need that increase

#

standard bot responses shouldn't really use webhooks, but something like logging is a pretty reasonable purpose

sage tendon
#

seems like a hacky workaround to me imho
only reason i see webhooks used is github repo updates and bots like tupper

errant trout
#

hey that's a form of logging :)

lapis dock
#

How I see it is that they make sense in places where unprompted messages will be sent to one (or a small number) of channels

fresh sierra
#

is it possible to create a post using a webhook for the first message ?
So right now im just sending a message with the bot but so it seems a bit strange to not have the name/profil of the real user

silk spire
#

Yes

silk spire
#

See thread_name

fresh sierra
#

let me show you coz it wasnt really clear

fresh sierra
#

here instead of the bot creating the post i would like to use a webhook so i can put the same icon and avatar as the user that created it

errant trout
silk spire
#

^^

#
webhook = Webhook.from_url("url", session=aiohttp.ClientSession()) # or create one in the forum (Thread.parent) via the bot

await webhook.send(
    thread_name="my very cool post",
    username=..., 
    avatar_url=...,
    content=?,
    embeds=?,
)
fresh sierra
errant trout
#

Luma

fresh sierra
#

Or does it create it automatically

errant trout
#

Literally try it

#

Read the docs

fresh sierra
#

I didn’t know that send was also creating that’s mb, I was first creating the thread and then using thread.send

#

Thanks tho

errant trout
#

thread_id (thread in pycord) targets an existing thread, while thread_name creates one (if it's a forum channel)

fresh sierra
#

Ok, sorry for the misunderstanding

silk spire
#

It's literally in the docs

#

Maybe read those instead of assuming

sage tendon
#

chill lol

silk spire
#

I mean, they misassumed twice like.. rtfm lol

lapis dock
#

And this is a help channel.

fresh sierra
#

and i read the docs about creating_thread, was not very logical for me that a send with a webhook could create a post. Again that's mb i was tired and i should have check ur answer first

fresh sierra
#
    | Traceback (most recent call last):
    |   File "/home/container/commands/backup/__setup__.py", line 856, in _load_message
    |     thread = await send_discord_message(
    |              ^^^^^^^^^^^^^^^^^^^^^^^^^^^
    |   File "/home/container/commands/backup/__setup__.py", line 848, in send_discord_message
    |     message = await backup_webhook.send(**kwargs)
    |               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    |   File "/home/container/.local/lib/python3.11/site-packages/discord/webhook/async_.py", line 1817, in send
    |     data = await adapter.execute_webhook(
    |                  ^^^^^^^^^^^^^^^^^^^^^^^^
    |   File "/home/container/.local/lib/python3.11/site-packages/discord/webhook/async_.py", line 348, in execute_webhook
    |     payload["thread_name"] = thread_name
    |     ~~~~~~~^^^^^^^^^^^^^^^
    | TypeError: 'NoneType' object does not support item assignment
    +------------------------------------

#

is this a pycord issue ?

#
kwargs = {
    "content": self._translate_mentions(message_data["content"][:2000]),
    "username": message_data["author_name"],
    "avatar_url": avatar_url,
    "embeds": [
        discord.Embed.from_dict(self._translate_mentions(embed))
        for embed in reversed(message_data["embeds"])
    ],
    "files": [
        discord.File(
            fp=attachment["path"],
            spoiler=attachment["spoiler"],
            filename=attachment["filename"],
        )
        for attachment in reversed(message_data["attachments"])
    ],
    "allowed_mentions": discord.AllowedMentions().none(),
    "wait": True,
}

if thread_name is not None:
    kwargs["thread_name"] = thread_name
elif thread_id is not None:
    kwargs["thread"] = discord.Object(thread_id)

message = await backup_webhook.send(**kwargs)
#

or else how should i do ?

fresh sierra
errant trout
#

oh that's silly

#

idk who designed that but thread_name needs to be handled in handle_message_parameters rather than execute_webhook

#

think it works right now if you don't upload files

fresh sierra
errant trout
#

figured

fresh sierra
#

It been some days I’m finding bug everytime I’m adding a new things lmao

#

Idk if I should call be lucky or not

errant trout
#

hey better sooner than later

sage tendon
#

you probably find bugs because you do the most outlandish things and solutions

fresh sierra
#

Yeah toothy we need 2.7

#

I agreed with you

#

Shit wrong guess

sage tendon
#

thank you

fresh sierra
echo wraith
# fresh sierra thanks !

Ca you try pip install git+https://github.com/Paillat-dev/pycord.git@fix/webhook-thread-name ?

shadow sigil
#

hello, i've been tempted to use the latest version currently available on the master branch
so uh, would that be a bad idea and how much?

lofty parcel
#

It is very much stable rn iirc?

#

Unless you really need a feature in it, you don't need it

lapis dock
#

I dont know of any bugs that are on master but not on stable.

echo wraith
fresh sierra
# echo wraith Ca you try `pip install git+https://github.com/Paillat-dev/pycord.git@fix/webho...

so really strange but when using ur commit i got this error:

  File "/home/container/commands/backup/__setup__.py", line 1073, in load
    await loading_methods.pop(task)()
  File "/home/container/commands/backup/__setup__.py", line 786, in _load_webhooks
    channel: discord.TextChannel = await self.bot.get_or_fetch_channel(
                                   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/container/utils/client.py", line 126, in get_or_fetch_channel
    self.get_channel(channel_id) or await self.fetch_channel(channel_id)
                                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/container/.local/lib/python3.11/site-packages/discord/client.py", line 1875, in fetch_channel
    data = await self.http.get_channel(channel_id)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/container/.local/lib/python3.11/site-packages/discord/http.py", line 371, in request
    raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access
#

which doesnt really make a sens because you didnt edit this part right

#

(i think i know, its because my commit is not in yours so i cannot really create any other channel which give me a missing access )

echo wraith
fresh sierra
#

let me just add ur thing to mine so i'll test that

fresh sierra
# echo wraith Wdym

so my commit permit me to create channel with everything, when im using yours i cannot create the channel (raise an error) and so later in my code it cannot get the channel

echo wraith
#

I'll just try to reproduce and fix it later

fresh sierra
#

so since it was not very clear, ur commit might work, im gonna test it right now using the appropriate way

#

ok so after test in the right condition i get this error:

    |   File "/home/container/.local/lib/python3.11/site-packages/discord/webhook/async_.py", line 1818, in send
    |     data = await adapter.execute_webhook(
    |            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    |   File "/home/container/.local/lib/python3.11/site-packages/discord/webhook/async_.py", line 225, in request
    |     raise HTTPException(response, data)
    | discord.errors.HTTPException: 400 Bad Request (error code: 50109): The request body contains invalid JSON.
#

tell me if you need more info or something like so

echo wraith
#

No I just did bs yesterday also cause I didn't test it

upper flint
#

Hello guys! How to create context commands available in private messages with any user in discord? If I click on user in dm I see the "apps" menu, so I suppose it is possible. Any relevant link or article will be highly helpful =)

rugged lodgeBOT
#

Here's the slash users example.

#

Here's the context menus example.

shadow sigil
sage tendon
#

we're all waiting for 2.7

torn barn
#

how many times have you said that in the last 24 hours

sage tendon
#

always in response to someone else asking for something 2.7
so it's clearly needed

ebon swift
#

Hi, I would like to use my database content (which stores specific STRING => discord categories IDs), to let my user choose a STRING from a list and let my command use the associated ID.

Can anyone guide me to an example on how to use dynamic choices list/dict returned by a function as a command choices ?

ebon swift
#

Ty

viscid depot
#

Hello! Are there some guides about monetisation in addition to the one by Discord? Examples are fine too.

west depot
#

Currently have this code

class Points(commands.Cog):
    def __init__(self, bot):
        self.bot: commands.Bot = bot
        self.request_channel = 1358740210153951336
        self.history_channel = 1358740224431358114

    class RequestView(discord.ui.View):
        def __init__(self, User, Amount, Reason, Proof, timeout=None):
            super().__init__(timeout=None)
            self.User = User
            self.Amount = Amount
            self.Reason = Reason
            self.Proof = Proof

        @discord.ui.button(label="Accept", style=discord.ButtonStyle.green, custom_id="accept")
        async def accept(self, button: discord.ui.Button, interaction: discord.Interaction):
            if "____v[Executive]v____" not in [role.name for role in interaction.user.roles]:
                await interaction.response.send_message("You do not have permission to use this command.", ephemeral=True)
                return
            embed = await utils.request_embed_builder(user=self.User, amount=self.Amount, reason=self.Reason, proof=self.Proof, colour=discord.Color.green(), status="Accepted")
            self.disable_all_items()
            await interaction.edit(embed=embed, view=self)
            database.add_points(self.User.id, self.Amount)
            embed_his = discord.Embed(title="Points Added", color=discord.Color.green())
            embed_his.add_field(name="User", value=self.User.mention, inline=False)
            embed_his.add_field(name="Points", value=self.Amount, inline=False)
            embed_his.add_field(name="Added by", value=interaction.user.mention, inline=False)
            embed_his.add_field(name="Reason", value=self.Reason, inline=False)
            embed_his.timestamp = discord.utils.utcnow()
            embed_his.set_footer(text="Points Management System")
            await self.bot.get_channel(self.history_channel).send(embed=embed_his)
            return

-# using seperate msg cuz char limit

#

However in the button i cannot access self.bot due to it being in the view class i believe.
What should i use instead?

little cobalt
west depot
#

Ty

eternal kite
#

is it possible to have a coroutine in dynamic cooldowns?

#

or is there a way to manually assign cooldowns to a command instead of using the decorator?

errant trout
eternal kite
errant trout
#

i can't guarantee it works, but you can try command_func.__commands_cooldown__ = DynamicCooldownMapping(cooldown_func, bucket_type)

#

it can't be an async function, so you'll have to work around that

#

ah

#

command decorators also support the cooldown kwarg

#

probably easier

eternal kite
errant trout
#

Eh you can use bot.loop.run_in_executor

eternal kite
errant trout
#

Not particularly

#

The "efficient way" is changing the entire context to async, if you care to rewrite that part of your library files

fresh sierra
fresh sierra
#

I was in the wrong for all those year…

#

Thanks tho

sage tendon
lapis dock
viscid depot
#

No problem. I'll see what I can do with the documentation available. Thanks for the reply!

prime hill
#

my slash commands are not showing up, using debug_guilds and application.commands scope enabled

sly karmaBOT
#

Application Commands Not Showing Up?

  • Refresh Discord by restarting or pressing Ctrl+R (or Command ⌘ + R)
  • Uninstall libraries that conflict with the discord namespace (e.g. discord.py).
  • Invite your bot with the application.commands scope.
  • Load cogs before bot.run() (e.g. not in on_ready).
  • Do not override on_connect.
  • Update to the newest version of py-cord (see ?tag install).
  • Turn off User Settings > Accessibility > Chat Input > Use legacy chat input.
  • Share your code and errors.
lapis dock
#

Also debug_commands is not as needed anymore as commands registration no longer takes a long time

sage tendon
#

Just make sure to restart your discord

prime hill
#

still not showing up, I have a working bot already and commands are visible. I created copy of the same bot with different app on developer portal to test my codes to not test on main one

#

removed debug guilds its still the same

sage tendon
#

did you invite the bot with application.commands scope?

prime hill
#

I did

echo wraith
autumn gust
#

how do I change a role color through a bot?

#

I kinda cooked this up but have no idea how to actually tell the bot "hey this is a role"

#

....nevermind

#

nvm I'm still clueless as to how to get the role?

errant trout
autumn gust
#

smth like... ctx.guild()?

errant trout
#

ctx.guild

autumn gust
#

oh interesting, thanks

errant trout
#

or is it always a specific guild ID you need

autumn gust
#

should be fine

errant trout
#

no

autumn gust
errant trout
#

ctx.guild will get the guild the command was run in

#

no ()

autumn gust
#

ooooh

#

thanks

errant trout
#

allgood

#

and it's get_role, this isn't js

autumn gust
errant trout
#

that's not necessarily intents

#

what's the full error

autumn gust
#

that is the full error

errant trout
#

it's likely your bot's top role is below the roles you are trying to edit

autumn gust
#

OH RIGHT

#

I forgot to do that

errant trout
#

pretty sure that's inheriting from something no?

autumn gust
#

lmfao

#

I'm so sorry

errant trout
#

allgood

autumn gust
#

IT WORKED

errant trout
#

nice

autumn gust
#

coding exercise to fix a discord bug over, thank you a lot

sage tendon
autumn gust
#

also for whatever reason I struggle to read/understand docs

sage tendon
#

VSC?

autumn gust
#

ya

sage tendon
#

of course

sage tendon
autumn gust
#

ya, I try to, funnily enough PyCord docs are ones I struggle with the most

sage tendon
#

why? its very well documented

autumn gust
#

oh yeah, it is very well documented, but the layout somehow messes with my brain

#

it's purely a me issue dw

#

I think it's just the fact everything is laid out at once instead of you uncollapsing things you need?

#

so I get distracted reading other entries

sage tendon
#

lol

echo wraith
#

Basedpytight better

round heart
#

That sounds dirty

round heart
#

Anyone else having issues running their bots at the current moment? Was getting outright connection issues, but now pycord just is never going 'ready'

#

(and messages here are slow to post, so I'm guessing there's an overall issue)

wild hill
#

So I was starting up my bot and ran my help command that had worked before but now is not and I am not sure why I did check the code but do not see anything wrong.

Ignoring exception in command helps:
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 122, in wrapped
    ret = await coro(arg)
  File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 825, in _invoke
    await self.callback(self.cog, ctx, **kwargs)
  File "/home/container/cogs/NewHelp.py", line 162, in helps
    await ctx.respond(embed=Help_Embed(), view=HelpOptions())
  File "/home/container/.local/lib/python3.10/site-packages/discord/interactions.py", line 641, in send_message
    await adapter.create_interaction_response(
  File "/home/container/.local/lib/python3.10/site-packages/discord/webhook/async_.py", line 213, in request
    raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components.0.components.0.options.4.emoji.id: Invalid emoji
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.10/site-packages/discord/bot.py", line 1098, in invoke_application_command
    await ctx.command.invoke(ctx)
  File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 331, in invoke
    await injected(ctx)
  File "/home/container/.local/lib/python3.10/site-packages/discord/commands/core.py", line 128, in wrapped
    raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components.0.components.0.options.4.emoji.id: Invalid emoji

That is the error I am getting

#

class HelpOptions(discord.ui.View):
    def __init__(self):
        super().__init__()
        self.add_item(discord.ui.Button(label="Invite Me!", url="Bot invite here", row=1))
        self.add_item(discord.ui.Button(label="Support Server", url="Support server invite here", row=1))

    @discord.ui.button(label="Delete", style=discord.ButtonStyle.red, emoji=":no_entry:", row=2)
    async def delete_button(self, button: discord.ui.Button, interaction: discord.Interaction):
        await interaction.message.delete()

    @discord.ui.select(
        placeholder="Select a Category!",
        min_values=1,
        max_values=1,
        options=[
            discord.SelectOption(
                label="Econamy", 
                description="Econamy commands", 
                emoji=":wrench:"
            ),
            discord.SelectOption(
                label="Config", 
                description="Configure the bot", 
                emoji=":wrench:"
            ),
            discord.SelectOption(
                label="Fun",
                description="View all Fun commands!",
                emoji=":magic_wand:"
            ),
            discord.SelectOption(
                label="Misc",
                description="View all normal and mod commands!",
                emoji=":robot:"
            ),
            discord.SelectOption(
                label="Moderation",
                description="View all MOD commands",
                emoji=":modlogo:"
            )
        ])
    async def select_callback(self, select, interaction: discord.Interaction):
        if select.values[0]:
            await interaction.response.edit_message(
                embed=discord.Embed(
                    title=f"{select.values[0]} Help!",
                    description=cog_help[select.values[0]],
                ).set_footer(
                    text="Use help <command> to get additional help on a specific command."
                )
            )



@slash_command(description="Gives a list of commands and what they do")
    async def helps(self, ctx):
        await ctx.respond(embed=Help_Embed(), view=HelpOptions())
#

There is the code

shell radish
#

:modlogo: is not a default emoji