#Basic Pycord Help

1 messages Β· Page 57 of 1

sage tendon
#

does it basically act like a record in java?

#

(if you know java)

frail basin
#

let me write a quick demo with timeit

sage tendon
#

hm ok

#

but can you change where that decorator would go

frail basin
#

wdym

sage tendon
#

like this decorator you mean
I've never seen that
can you show that in your code

frail basin
#

@attrs.define?

sage tendon
#

yes

frail basin
#

Oh thats the exact same as @frozen in the test, just with with one of the params set to True

sage tendon
#

yes but can you show it in your code lol

frail basin
sage tendon
#

oh i didnt see the paste link as that lol

#

thought it was just yet another image hoster link

frail basin
sage tendon
#

hm interesting, basically a bit like a java record class
and i guess it also provides getters and setters? or is that decorator really only to simplify the init?

frail basin
#

It provides extra functionality

#

Basically an improved version of the builtin dataclasses.define

sage tendon
#

but yea, i guess python shows its ugly side there regarding performance

frail basin
#

I might also try to compile it using CPython, curious how much that improves

sage tendon
#

or use mojo

frail basin
#

Havent heard of that one before

sage tendon
#

i think most of your latency will be unavoidable though

frail basin
#

Yeah, hopefully localhost API calls + DC ping will improve on that though

#

Would be nice if discord disclosed the locations of their API gateways

#

Never going to happen, ik

sage tendon
#

pointless info

frail basin
#

Not really

sage tendon
#

very

frail basin
#

Being in the same DC would improve ping

#

Maybe not that significantly

#

But would improve nevertheless

sage tendon
#

what

#

as long as youre at least on the same continent as the gateway, any difference in location is negligible

#

and as you can see, a single line in your code can add more latency than going half across the world, literally

haughty grove
#

is it possible to get a guild specific banner?

#

fetching the user returns the normal banner and member.banner is always None

sage tendon
#

not yet, but 2.7 i think

#

or wait, are you on 2.6.1?

haughty grove
sage tendon
#

yea then its in 2.7 when it releases

#

or wait, user app?

haughty grove
#

nope

sage tendon
#

ah ok

haughty grove
marsh nymph
#

is there a way if a bot joins in a guild with manage roles perms, within the event on_guild_join to edit the self_role ?

sage tendon
#

you cant edit your highest role

marsh nymph
#

i thought maybe theres another way to edit the role of the bot like the color or name

sage tendon
#

no

#

not sure if bots can edit their role if they have a higher role, might work then

#

but thats usually not the case

tiny fractal
#
        banr = self.bot.get_guild(BANR_ID)
        await ctx.send(f'{banr.members}')

am I high? this is only returning two members myself and a bot, did something change. this worked for ages

sly karmaBOT
# tiny fractal ```python banr = self.bot.get_guild(BANR_ID) await ctx.send(f'{b...

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.

tiny fractal
#

yea its not cache

#

i've tried both

#

with fetch it returns zero members

errant trout
tiny fractal
#

i've got it set to all

#

actually... you know what.. im an idiot

#

i forgot the part in bot = discord.Bot(intents=intents) where you pass intents

sage tendon
#

a good IDE should've warned you about that

tiny fractal
#

yea, vscode normally does. but i think its because im remoting to a linux server to do work

opal swan
#

slash_command in logic don't need an help ? bcs all cmds are in slash

lapis dock
#

Please rephrase your question.

opal swan
#

a bot with somes slash commands don't need an help

#

?

#

(bcs all commands are show in slash)

lapis dock
#

It is your preference. But I do not use a help command. I just make sure to give each slash command a description

opal swan
#

ye me too

mossy star
#

is it possible to have a custom embed and a link embed (an embed auto-generated by discord from a link) in the same message?

sage tendon
#

yea

#

i think a message can have 10 embeds

mossy star
#

because when i try, the link embed doesn't show up when i have a custom embed

sage tendon
#

show how it looks like in discord

mossy star
#

this is the result of this command:
r = await c.send(f"https://imgur.com/jTduCVL",embed=discord.Embed(description='custom embed'))

#

the imgur will load if i remove the other embed, but doesn't if there is

sage tendon
#

ah yea i see the issue

#

it should work if you send an empty message and edit the link in later

#

the issue is that you are passing embed= which basically tells discord to only show that embed

lapis dock
#

I am pretty sure that a message has to only have the link for it to render

#

https://google.com/ extra chars

sage tendon
#

no

lapis dock
#

Nevermind Im dumb

sage tendon
#

what you're thinking of is that it hides image links if the message consists only of the link

lapis dock
#

yeah your right

mossy star
#
time.sleep(1)
y = await c.fetch_message(r.id)
await y.edit(content='https://imgur.com/jTduCVL')```
sage tendon
#

probably wont work but can you try doing embeds=[your embed] instead of embed=

#

you need the brackets btw

mossy star
#

just tried it, no luck

sage tendon
#

then i think you're out of luck
it might work differently because its a media embed and not like, a normal embed
i think it should work with e.g. google.com if you put that in there

#

can you try that rq

mossy star
#

still using the embeds=[] method

#

well, it's not too big of a deal if i have to send two messages, but a little annoying

lapis dock
#

If that does not work you can put the link in its own embed by using
Embed.set_image()

mossy star
#

well, the reason i ended up down this rabbit hole was to handle video links, which that can't handle

sage tendon
#

yea i think video embeds are reserved for some sites

lapis dock
#

Ah, ok

sage tendon
#

or at least cant be manually made afaik

mossy star
#

i also tried doing the embed first and then editing a second embed in later, which kinda works but screws up the link embed and strips out videos

lapis dock
mossy star
sage tendon
#

this might be very forceful but you MIGHT be able to make videos work with

embed = discord.Embed()
embed.video = discord.EmbedMedia(video_link)
mossy star
#

from my testing, pycord/discord will ignore any video data you try to send in an embed, i've tried

sage tendon
#

f

errant trout
#

users/bots cannot send videos in embeds

mossy star
#

yeah, which is why i'm trying workarounds lmao

#

even just editing a message with a functional link/video embed will break it

errant trout
#

well.. the only "workarounds" are using gifs or sending a site that embeds videos itself

#

websites are able to configure video embeds using opengraph

sage tendon
#

proxy it through your own VPS and abuse it as CDN

#

lmao

#

that would work but itd probably be unreasonable effort

mossy star
#

basically, the only thing that works in my testing is a regular text message with a link/video embed generated by discord. which means i can't use embed decorators for my text which is annoying, so that's why i figured i'd ask

#

anyways, thanks

lament totem
#

How does autosharding work? Does it spawn multiple processes and handle ipc or does it still use a single process but use multiple gateway connections? This is a bit confusing

lament totem
lament totem
lofty parcel
#

It is multiple gateway connections.

#

At least what it says in the source code.

#

"Instead of a single websocket, we have multiples. The key is the shard_id"

little cobalt
lapis dock
sage tendon
#

i think its forced at 2500 so yes you should do it

lament totem
#

I'm just trying to understand this, so for example if I do autoshardedbot.guilds will I get all the guilds where the bot is installed? or all the guilds corresponding to the shards in the current process being run?

sage tendon
#

it will show all the bot's guilds

#

the only real difference is that not all guilds run on the same shard / websocket connection

round heart
lapis dock
#
  1. add your bot to about 10k more servers
  2. Use autosharded bot
    easy :)
lament totem
sage tendon
#

you can do that but theres little point if its on the same machine

lofty parcel
#

Why would you run two processes tho

#

The point of autoshardedbot is to avoid you the frustration of handling IPC

lament totem
#

Later on ofc, assuming the bot gets installed in more and more servers

#

If I understand, it's still a single process but receiving guild events through multiple gateway sockets, no?

sage tendon
#

30% is nothing

lament totem
sage tendon
#

No

#

And you arent suddenly getting 3x as many servers to handle

lament totem
lament totem
# sage tendon No

so every shard gets a new process? I feel like there's something I'm missing

sage tendon
#

no lol

#

its just a new gateway connection

lament totem
sage tendon
#

not 100% of your CPU usage is variable

#

there'll be some % that remain even if you have 0 servers in your bot

lament totem
sage tendon
#

yea okay then i overestimated it

#

but still, 30% is nothing, you'll have long until you reach high percentages still

lament totem
#

but I think I understand a bit better now, I guess I should give the source code a good look sometime soon

sage tendon
#

it wont become unresponsive until it reaches literally 100%

lament totem
#

I guess what I meant was, like being late to defer or respond to interactions (buttons / slash commands, etc) not really unresponsive in the strict sense

sage tendon
#

same thing there

#

its not slower at 95% CPU usage than it is at 5%

#

well, it is, but thats about a few nanoseconds at best

lament totem
#

If that's the case then I must be doing something wrong πŸ‘€

sage tendon
#

why?

lament totem
#

well if the bot is being late here and there on defering stuff then something must be blocking for longer than 3 secs or its just too slow to do the stuff ahead in the queue

sage tendon
#

yea, but thats unrelated to CPU usage

#

thats just because you have blocking code that adds up

#

may or may not be unavoidable

agile oar
#

Is there no way to handle a ratelimit on channel edits? I know the limit it 2 edits per 10 minutes, but im not getting any errors raised on a try except.

How am I supposed to know if the bot is ratelimited on editing a channel before trying an edit if it does not return anything?

lapis dock
#

In general the library will handle rate limits like that. With how discord is set up you cannot check if you are going to hit a rate limit. You have to hit it and then wait the timeout.
When rate limited the library will queue your request to be sent when unratelimiter.

stuck oar
#

I understand that to add tags after creating a thread in a forum channel, I should use ForumChannel#edit(applied_tags=[]), but I don't know what values to put in discord.ForumTag. I tried using discord.ForumTag(name="Plugin", emoji="πŸŒ™"), but it doesn't work (even though it's an actual tag).

errant trout
stuck oar
#

oh Thanks!! TeddyLove

agile oar
frail basin
#

Is there a way to get the message that a view is attached to, from within the view's code? self.message is not None, but raises an Unknown message error when I try editing it, even though I can still clearly see it on my client and even use the view's buttons.

little cobalt
frail basin
#

all

little cobalt
frail basin
fresh sierra
#

As far as I know

#

Try again without the defer

frail basin
#

did not work

sage tendon
#

is your view in an ephemeral message?

frail basin
sage tendon
#

that is the problem

frail basin
#

Any workarounds?

sage tendon
#

dont think so
just do an ephemeral followup instead of editing it

frail basin
#

That wont prevent the original issue, of the user pressing the buttons multiple times

sage tendon
#

then disable the buttons once clicked

frail basin
#

And since I dont have the original message, I cant disable the button

sage tendon
#

self.disable_all_items()

frail basin
#

Dont I have to edit the message with view=self for that?

sage tendon
#

not sure, p sure if you disable all items itll still reject any interactions sent to them

#

let me check my code

frail basin
#

Well yea it will reject them, causing an "interaction failed" thing

#

iirc to disable the buttons you have to edit the message

sage tendon
#

yea, i dont think you can properly disable the buttons in an ephemeral message

frail basin
#

Well thats dumb

sage tendon
#

i mean, discord limitation
ephemeral messages are really barely messages at all lol

frail basin
#

I am aware that this is discord's bs

sage tendon
#

actually lemme check smth

#

okay forget what i said, wtf
I just remembered a bot i use has ephemeral messages that can be edited

#

sorry lol

#

but i have no idea how that's done

#

have you tried editing both self.message (by passing it from the original view) and self.original_response() with ephemeral=True passed?

frail basin
#

I fixed it

#

not sure how lol

#

I am not touching this

#

seems like its actually editing it though

sage tendon
#

hm

#

using the top or bottom path

frail basin
#

top

#

luckily

sage tendon
#

but didnt you do exactly that before

frail basin
#

Yes.. Yes I did

#

Oh

#

You know what I changed? Removed ephemeral=True from the defer

#

But the message is still somehow ephemeral

#

So I dont know wtf is going on

echo wraith
#

wat

frail basin
#

Exactly πŸ˜‚

sage tendon
#

thats not even possible

#

if you respond non-ephemerally the response cant be ephemeral

frail basin
#

Oh I know why,

Slashcommand -> ephemeral view -> non ephemeral defer -> ephemeral edit_original_response

sage tendon
#

wow

frail basin
#

And it stays ephemeral all the way

sage tendon
#

yea i had a brain lag

#

we figured it out now, somewhat

errant trout
#

ephemeral messages are full messages (to the point they appear on different clients)

sage tendon
#

but explicitly passing ephemeral=True to the defer shouldnt break it lol, since its all forced ephemeral anyway apparently

frail basin
#

Not sure why it did that. I bet if I passed it now, it wouldn't break.

errant trout
# frail basin

this should have been interaction.response.edit_message

frail basin
#

Whats the difference between that and edit_original_response?

sage tendon
#

this is why i hate views, honestly

#

way too much shit that sounds samey

errant trout
#

response.edit_message is for the initial interaction

frail basin
#

so thats basically interaction.message.edit()?

errant trout
#

edit_original_response is for editing the response you already made later

#

(and again, we implemented interaction.edit to simplify it)

#

more or less yeah

frail basin
# errant trout this should have been interaction.response.edit_message

How would I make the 3rd message replace the 2nd one then? The 2nd message's "send" button triggers the 3rd message.

I tried:

  • interaction.response.edit_message -> raises InteractionResponded (I'd assume cause the defer?)

  • interaction.edit -> makes a 3rd ephemeral message

  • interaction.edit_original_response -> same as above

  • interaction.message.edit -> Unknown Message

  • interaction.followup.edit_message(message_id=interaction.message.id, ...) -> Nothing happens

errant trout
#

if you defer with invisble=False, discord explicitly creates a new message

frail basin
#

ah

#

That was the missing piece of info here

#

Thanks

errant trout
#

allgood

round heart
#

wait, what? What takes an invisible kwarg?

sage tendon
#

defer of a button interaction

#

doesnt show the thinky dots

round heart
sage tendon
#

wdym?

round heart
#

You say it's used when receiving a button press. The discussion above was about disabling the button once pressed (which it doesn't generally do). So I'm wondering if not having it 'invisible' brings that behavior with it.

sage tendon
#

no clue

frail basin
errant trout
#

opposite, but yeah

#

invisible was introduced so you could respond to components without having to make a new message

#

i.e. before that, you ALWAYS had to respond to them with a new message (but this was very early on)

#

on discord's end, this is referred to as DEFERRED_UPDATE_MESSAGE - the library defaults to this behavior because, for the vast majority of use cases, it's more useful

full ore
#

Hello,

I often have issues with Discord rate limits when programming a bot. I have to restart it frequently to apply changes, and I probably restart it five times or more within 10 minutes.

Here’s my GitHub link to the bot:
https://github.com/DerTarzan/AuraCity

Can someone explain to me why I keep getting rate limited? Is there a way to prevent this, as it's nearly impossible to program a bot under these conditions?

GitHub

Contribute to DerTarzan/AuraCity development by creating an account on GitHub.

sage tendon
#

you still didnt send your ratelimit message

full ore
# sage tendon you still didnt send your ratelimit message

I have no one but my commands dont sync...

in the morning yestady i have a message like this:

2024-09-28 15:05:48,363 - AuraCityBot - ERROR - ❌ Failed to sync commands: 429 Too Many Requests (error code: 30034): Max number of daily application command creates has been reached (200)

sage tendon
#

yea, dont edit your command metadata so often

#

names, descriptions, options

full ore
sage tendon
#

the limit is 200 commands per day, impressive that you managed to reach that lol

full ore
sage tendon
#

yea, but it adds up whenever you edit their data

full ore
sage tendon
#

just dont edit the names, options and descriptions of your commands so often

#

thats all there is to it

full ore
#

ahh okay

But i have to look if my changes work...

#

yk ?

sage tendon
#

the changes of the command functions doesn't count, i never mentioned that

full ore
#
    @slash_command(name="abmeldung", description="/abmeldung - Melde dich ab von AuraCity-Team.")
    async def deregistration(self, ctx: discord.ApplicationContext):
        user_id = ctx.author.id

        # Fetch the last deregistration timestamp from the database
        last_deregistration = await self.database.get_last_deregistration(user_id)

        # Ensure we get a datetime object from the query result
        if last_deregistration:
            # Since the result is a tuple, extract the first element (the datetime)
            last_deregistration_time = last_deregistration[0] if isinstance(last_deregistration, tuple) else last_deregistration

            # Check if last_deregistration_time is a string and convert it to datetime if necessary
            if isinstance(last_deregistration_time, str):
                last_deregistration_time = datetime.strptime(last_deregistration_time, "%Y-%m-%d %H:%M:%S.%f")

            # Ensure last_deregistration_time is timezone-aware
            if last_deregistration_time.tzinfo is None:
                last_deregistration_time = last_deregistration_time.replace(tzinfo=timezone.utc)

            # Check if the user has deregistered within the last 48 hours
            time_since_last = (discord.utils.utcnow() - last_deregistration_time).total_seconds()
            if time_since_last < 48 * 3600:  # Allowing deregistration every 48 hours
                await ctx.respond("Du kannst dich nur alle 48 Stunden abmelden.", ephemeral=True)
                return

        # Update the last deregistration timestamp in the database
        await self.database.add_deregistration(user_id, discord.utils.utcnow())
        await ctx.respond("Du hast dich erfolgreich abgemeldet.", ephemeral=True)

full ore
sage tendon
#

again, code changes of the function itself don't count

full ore
sage tendon
#

and if you dont somehow literally edit the options, names or descriptions of your commands 200 times before hitting the ratelimit you are doing something weird
show your main bot file

sage tendon
#

yea, this is the issue

#

dont do that

#

or this in your on ready

full ore
sage tendon
#

and you cannot load cogs in your on_ready, it doesn't do anythig unless you have prefix commands

sage tendon
sage tendon
#

before on ready

#

lol

#

before your bot start

full ore
sage tendon
#

yea

full ore
sage tendon
#

where did you get that code from btw

#

thats most certainly not from the pycord guide

full ore
sage tendon
#

all of it

full ore
#

I have write this...

#

this my bot im currently working on

sage tendon
#

yea but you must've gotten the general concept of how to load cogs etc from somewhere

full ore
#
cogs_list = [
    'greetings',
    'moderation',
    'fun',
    'owner'
]

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

you mean this ?

sage tendon
full ore
# sage tendon you have to do that before running bot.run, yes
def load_cogs(self, directory: str, is_root: bool = True) -> None:
        """Loads all cogs from the specified directory."""
        if is_root:
            logger.info(":package: Loading Cogs...")

        for filename in os.listdir(directory):
            if os.path.isdir(f'{directory}/{filename}'):
                self.load_cogs(f'{directory}/{filename}', is_root=False)
            elif filename.endswith('.py'):
                try:
                    self.load_extension(f'{directory.replace("/", ".")}.{filename[:-3]}')
                    logger.info(f' - :white_check_mark: Loaded Cog: {directory}/{filename}')
                except Exception as e:
                    logger.error(f':x: Failed to load cog {filename}: {e}')
        if is_root:
            logger.info(":tada: All Cogs Loaded Successfully.")

But this is the same just more complicated

sage tendon
#

yea but also the command syncing stuff etc
thats not in the guide and you dont typically use that

full ore
#

Project Structure:

base -> cogs -> events.py

I also have:

base -> cogs -> TicketSystem -> ticket.py

yk ??

full ore
sage tendon
#

i still dont know where you got all that stuff from lol

full ore
#

my brain tell me write this... and i sayd yes it makes sence...

sage tendon
#

you didnt just randomly think all of that up.... where did you get it from, the guide, the docs, stackoverflow?

full ore
sage tendon
#

alright

#

just remove any manual command syncing

#

its unnecessary

full ore
#

its only for global bots like mee6 or rythm ?

sage tendon
#

i dont see why those would inherently need it either

#

and with how many commands they have, they probably couldn't

full ore
#

okay wait i make my changes i hope im not currently ratelimitet...

Today i have to wait for 5 hours

#

yeah my commands dont show up i have restart my discord...

#

Bot says cogs been loaded outsite the on_ready func...

sage tendon
#

show your main file and also one of your cogs

full ore
#

okay wait

#
from dis import disco

import discord

from base.bot import AuraCityBot
from base.logger import AuraCityLogger

logger = AuraCityLogger("AuraCityMain").get_logger()

class AuraCity(AuraCityBot):
    def __init__(self):
        super().__init__()
        self.config.DEV_MODE = True

    @staticmethod
    def setup():
        if os.name == "nt":
            pass
        elif os.name == "posix":
            pass

    def start_bot(self):
        try:
            self.load_cogs("base/cogs")
            self.run(self.config.TOKEN)
        except discord.LoginFailure:
            token = self.config.TOKEN
            if len(token) != 59:
                logger.error("UngΓΌltiger Token. Bitte ΓΌberprΓΌfe den Token in der Konfiguration.")
                return
            logger.error("Fehler beim Einloggen. Bitte ΓΌberprΓΌfe den Token in der Konfiguration.")

if __name__ == "__main__":
    AuraCity.setup()
    aura_city = AuraCity()
    aura_city.start_bot()
sage tendon
#

how do you even have so much command code without ever being able to test it lol

full ore
#
class Moderation(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.config: AuraCityBotConfig = bot.config
        self.embeds = AuraCityEmbeds()

    @has_permissions(administrator=True)
    @slash_command(name="clear", description="LΓΆsche eine bestimmte Anzahl von Nachrichten.")
    async def clear(self, ctx: discord.ApplicationContext, amount: int = 1):
        await ctx.channel.purge(limit=amount + 1, check=lambda m: not m.pinned)
        embed = self.embeds.clear_embed(amount, ctx.guild.icon.url)
        await ctx.respond(embed=embed, delete_after=5)

    @has_permissions(administrator=True)
    @slash_command(name="sync", description="Synchronisiere die Befehle mit Discord.")
    async def sync(self, ctx: discord.ApplicationContext):
        await ctx.defer()
        await self.bot.sync_commands()
        embed = self.embeds.sync_embed(ctx.guild.icon.url, [c.name for c in self.bot.commands])
        await ctx.respond(embed=embed, delete_after=5)

    @clear.error
    async def clear_error(self, ctx: discord.ApplicationContext, error: commands.CommandError):
        channel = self.bot.get_channel(self.config.ERROR_LOGS_CHANNEL_ID)
        embed = self.embeds.clear_error_embed(ctx.guild.icon.url, str(error))
        await ctx.respond(embed=embed)
        await channel.send(f"Failed to clear messages. [{error}]")

    @sync.error
    async def sync_error(self, ctx: discord.ApplicationContext, error: commands.CommandError):
        channel = self.bot.get_channel(self.config.ERROR_LOGS_CHANNEL_ID)
        embed = self.embeds.sync_error_embed(ctx.guild.icon.url, str(error))
        await ctx.respond(embed=embed)
        await channel.send(f"Failed to sync commands. [{error}]")

def setup(bot):
    bot.add_cog(Moderation(bot))`
sage tendon
full ore
little cobalt
sage tendon
#

has_permissions shouldnt be used for slash commands anyway but thats not the issue rn

full ore
sage tendon
full ore
#

i have test it

#

wait

#

ahh i cant show you my commands dont show up HHAA i forget it

sage tendon
full ore
#

idk why

#

so my commands were visible

sage tendon
#

because a syncing error doesnt magically unsync your commands
im kinda confused why they dont show up at all now but Shrug_3

full ore
#

everything else goes

#

like on_message event

sage tendon
full ore
#

omg my commands show up ahhhhhhh

#

thank you, you are really good guy...

solid sapphire
#

hey,
I've discovered that if a bot sends a message with a link, the link gets a preview
but if it sends exactly the same message but with an embed attached, the link doesn't get a preview
is there a way to send a message with a link with both link preview and embed?

sage tendon
#

dont think you can change that

solid sapphire
#

okay, thanks

civic moon
#

I'm have trouble getting an event to fire when someone leaves the guild. Is there something I'm missing? This code is not executing:

async def on_raw_member_remove(payload):
    print(payload.user.name + " left: on_raw_member_remove")

async def on_member_remove(member):
    print(member.name + " left: on_member_remove")

My intents are active (on_member_update executes fine). I am seeing another bot (ProBot) activate when a member leaves the guild. No way it would absorb the event right? Btw I may have handled the payload incorrectly, I don't have any errors though.

sage tendon
#

what are your intents?

civic moon
#

intents=discord.Intents.all()
with all intents active on the developer portal

lapis dock
#

You do not have the listener decorator

#

@bot.listen()

civic moon
lapis dock
#

:)

civic moon
#

Do you know if that payload is handled correctly for the on_raw_member_remove?

errant trout
#

looks fine

lapis dock
red mist
#

Did I get pin

#

*ping?

twilit socket
#

ban in Member.ban is maximum of 7 days of message deletion? is this an API call for all messages? I want to delete a large history from years ago, do I really need to fetch each message with API calls?

lofty parcel
#

The max being 7 days is an api limitation

#

And I wouldn't recommend you fetching and deleting the messages one by one, you'll get ratelimited very quickly if they're actually too many

twilit socket
#

I need to wipe my own messages from my own server

#

what do you recommend?

#

I can't delete the channels

lapis dock
#

I dont think that is a valid usecase of the API
You can request that discord deletes all of your data (including your account and messages on all servers) but i doubt this is what you want

twilit socket
#

I would want that, but I don't want to lose my bots/apps

#

I want to get off discord

#

but my bots needs to be kept running

lapis dock
#

You can transfer the bots ownership to another user

#

If they are verified you will have to contact support to do this

twilit socket
#

there's an option on my account to just disable it, not delete

#

disabling it would hide my messages or something?

lapis dock
#

You can disable your account but I dont think this will delete messages

twilit socket
#

what a tricky situation

lapis dock
#

It does not make a whole lot of sense why you want to get rid of your account but still have bots

twilit socket
#

it has been said that i'd be rate limited, but what are the numbers? I've downloaded messages before in the millions, and it's been pretty fast, but not deleted it

#

deleting it is an api call by itself

twilit socket
lapis dock
#

Discord does not post what numbers cause rate limits. It depends on a case by case basis. In generally the library should handle the rate limits for you but I am unsure if it would be able to with the quantity of requests. There is a hard limit of 50 requests per second though.

My recommendation is to transfer the bots to a trusted person or a account that you will not use. And then request discord deletes your data.

#

In my opinion deleting your messages is not worth it. You have already sent them so deleting them will not make much of a difference.

twilit socket
#

does'nt need to be in seconds

#

I can wait all day

#

I'll back it up anyways

#

I'll first download it

#

thanks for all the help

errant trout
#

i'd just go with what wolfy said, transferring your bot to a team under another account and then requesting discord to wipe and anonymize your data would be significantly easier

echo wraith
lofty parcel
#

The clickbait πŸ’€

sage tendon
#

NTTS is pure misinformation in that disregard

#

its high level clickbait to lure in kids

echo wraith
#

removed the embed

deft kestrel
#
discord.http.Route.BASE = ""
client = discord.Client()

This works on pycord?

errant trout
#

i can see what it's doing in dpy... but i fail to understand why you'd ever want to

#

if you mean to change the api version then you modify discord.http.API_VERSION, which is an int, but note that if you change the version from the default then it may be harder to debug certain issues
most of the time people only want this to force v6 for message content... but i don't really think it's worth it considering how old v6 is

edgy nest
delicate wedge
#

I am trying now and I only did slash cmds so far but no prefix and I can't get the to work.

@bot.command()
async def test(ctx):
    await ctx.send("Returned Test")
bot = discord.Bot(
    intents=intents,
    debug_guilds=[idthatIwontshow],
    status=status,
    activity=activity,
    command_prefix="."
    )
intents = discord.Intents.default()
intents.members = True
import discord
import os
from dotenv import load_dotenv
from ezcord import commands
```![criii](https://cdn.discordapp.com/emojis/1217764089078611999.webp?size=128 "criii")
deft kestrel
errant trout
round heart
loud kayak
#

Why is it that channel.send (sometimes) sends multiple messages when only being fired once? Is it just an API bug?

#

It’s usually in button callbacks or timers for me

proven valley
#

is there some guide on testing, so I can auto test commands and views?

sage tendon
#

Not that i know of
typically discord bots arent so complex that you cant quickly test a command yourself in 2 minutes

full ore
sage tendon
#

i just dont get why people do it like that

#

loading cogs is a single line if you do it the normal way

round heart
proven valley
sage tendon
#

i mean just send / duplicate all those messages to a channel instead ig

#

or your own dms

lapis dock
sage tendon
#

it really isnt hugely feasible given you entirely rely on a foreign API

torn barn
lapis dock
#

They are also using discord.Bot instead of ext.commands.Bot so prefix commands will not work anyways

sage tendon
#

already solved in a thread made by them later

delicate wedge
delicate wedge
sage tendon
#

here.

#

so that means you made minimum three threads for one issue reading the guide would've prevented

loud kayak
#

Why is it that channel.send (sometimes) sends multiple messages when only being fired once? Is it just an API bug? It’s usually in button callbacks or timers for me

fresh sierra
#

is there a built in way to do that ?

    async def flip(self, ctx: LumabotContext, bet: int | "all"):

fresh sierra
#

set the type as int or a specific text

frail basin
#

If you are talking about slash command options, I doubt you can.

fresh sierra
frail basin
#

I dont think it will allow you to mix int and string

fresh sierra
#

thanks for the help

fresh sierra
#

For the user has to put either an int either all in str

sage tendon
#

so take a string, check if it says "all", if no, cast it to int

fresh sierra
#

So u just made a custom converter so its easier

sage tendon
#

which is how many lines?

#

you keep overcomplicating absolutely everything you do once you hit anything you can't solve with the most simple things
and from what I saw it makes your code extremely overcomplicated and hard to maintain

fresh sierra
sage tendon
#

It's the sum of everything

#

the fuck do you need a custom converter for? it's literally 2 lines if you do it compactly

fresh sierra
#

Im just doing the type hint

sage tendon
#

wtf do you need to raise an exception for

fresh sierra
sage tendon
#

take str
check if Str says all
if no, cast to int

fresh sierra
#

And if the user put neither ?

sage tendon
#

then for all I know the cast will be 0

fresh sierra
#

So I would have to handle that

sage tendon
#

you should already check for 0 being entered

fresh sierra
#

And to say the user he should put either all either a number

#

Or I use my custom converter

#

That does everything for me

sage tendon
#

mess up your codebase piece by piece, sure

#

why did you even ask if you already have the solution?

fresh sierra
#

True that does
bet: BetConverter

#

Its soooo messy

#

Thats sad

frail basin
#

Why not just use -1 instead of "all" ? πŸ˜‚

sage tendon
#

no that's not really intuitive at all

#

all betting bots I know let you enter all

fresh sierra
sage tendon
fresh sierra
#

Is that messy ?

#

What a messy way to handle the typehint of a command

#

It’s so more logic to add the same thing at the beginning of all command

sage tendon
#

and it makes your code less clear, is way longer, and introduces additional complexity as opposed to doing it exactly where you need it or even just moving it into a seperate function if youre lazy

fresh sierra
#

How is that less clear ?

fresh sierra
#

So ur saying adding the same function at the beginning of each command is more clear and shorter that using a custom converter ?

fresh sierra
sage tendon
#

That is unfortunate

#

good luck

fresh sierra
#

I mean I prefer to listen to danny than to listen to make making the same function again and again inside each command

sage tendon
#

and instead you're doing the same but in an unexpected code without even documenting it meaning any outside person reading your code can't intuitively know what the fuck that even does

fresh sierra
#

Why the fuck would I care about reading my code ?

sage tendon
#

I feel like sometimes you're compensating for lack of something with your overly complicated code for literally the most simple things ever

frail basin
fresh sierra
#

Also if I want to make my converter more clear to the user I can use comment

#

I don’t see how a function inside the command that will do the same thing is more clear

sage tendon
#

Because then you have a properly named function that ideally already describes what it does in the name, you leave the typehint proper, etc

fresh sierra
#

I mean it convert the bet option so

sage tendon
#

That is a substantive for a name, functions are named by actions using verbs.

fresh sierra
#

Yeah but that’s not a function but a class

#

So I understand ur point

#

I understand that ur point work if u are many user using this code

#

But since im the only one I don’t teallly need to put comment explaining what it does since I know what I just code

#

But using a custom converter is still more appropriate that make a fonction after since you are converting the arg

#

Also what danny make a guide using custom converter rather thzn runction inside the command

errant trout
fresh sierra
errant trout
#

nice

fresh sierra
#

Yep here it is

#

But if you have advice tell me ;)

errant trout
#

nah looks good to me

fresh sierra
#

Ok thanks

wheat field
#

how do i stop a await ctx.respond if a if statment comes back true?

#

if condition?

#
    async def warn(self, ctx, user: Option(discord.Member, "User to warn"), reason: Option(str, "Reason for the warning")):
        # Check if the bot has permission to manage messages
        if not ctx.guild.me.guild_permissions.manage_messages:
            timeout_on_bot = discord.Embed(title="Error ", description=f"I don't have permission to warn members.", color=discord.Color.blue())
            await ctx.respond(embed=timeout_on_bot, ephemeral=True)
            return

        # Check if the user has permission to manage messages
        if not ctx.author.guild_permissions.manage_messages:
            timeout_on_bot = discord.Embed(title="Error ", description=f"You don't have permission to warn members.", color=discord.Color.blue())
            await ctx.respond(embed=timeout_on_bot, ephemeral=True)
            return
        
        if user == ctx.bot.user:
            embed = discord.Embed(title="Error", description="You cannot warn the bot")
            await ctx.respond(embed=embed)
            return
        ```
wheat field
#

this my maint warn command but i wanna check if the user is == the bots user name and if it is send embed saying it is but i need to stop the the bot from editint database info

#
        cursor.execute("SELECT warnings FROM warnings WHERE user_id = %s", (user.id,))
        result = cursor.fetchone()
        if result is None:
            await self.create_warning(user)
        else:
            warnings = result[0]
            warnings += 1
            cursor.execute("UPDATE warnings SET warnings = %s WHERE user_id = %s", (warnings, user.id))
            self.cnx.commit()
            if warnings > 20:
                await user.kick(reason="Exceeded warning limit")
                embed = discord.Embed(title="User Kicked", description=f"{user.mention} has been kicked for exceeding the warning limit", color=discord.Color.blue())
                await ctx.respond(embed=embed)
            else:
                embed = discord.Embed(title="Warning", description=f"{user.mention} has been warned for {reason}", color=discord.Color.blue())
                await ctx.respond(embed=embed)```
#

and stop it from saying warned user wtv

#

i swear i did it on another bot i just cant rember 😭

#

could i use difer?

little cobalt
#

for what?

wheat field
#
            embed = discord.Embed(title="Error", description="You cannot warn the bot")
            await ctx.respond(embed=embed)
            return``` this 

```else:
                embed = discord.Embed(title="Warning", description=f"{user.mention} has been warned for {reason}", color=discord.Color.blue())
                await ctx.respond(embed=embed)```
#

the if statment is checking if user is the bot name and if it is ill send the embed but how do i stop the bot from adding a warn

#

i have alr have return

#

heres little better picture

wheat field
#

i also wanna comepletly that stop the respond

frail basin
#

I dont see what the issue is here?

wheat field
#

permison checks n shit

#

when i try to warn my bot right

#

it will send the failed

#

and it will send the warn added

frail basin
# wheat field

If you return after an if check is true, it wont execute the db stuff

wheat field
#

not true

#

works perfectly fine for everyother comamnd

frail basin
#

The code itself looks fine

wheat field
#

yes ik the code is fine

frail basin
#

Are you sure that the bot is running this code?

wheat field
#

theres no visibal errors

#

but i wanna add error handling as embeds

little cobalt
# wheat field

Keep in mind if you do a if if if its gonna do all the stuff

wheat field
#

oh shit

#

i didnt even know that

hazy turret
#

Is there an easy way to find out which user has invited another user to the server?

wheat field
#
async def on_member_join(member):
    invites_before_join = await member.guild.invites()
    invites_after_join = await member.guild.invites()
    for invite in invites_before_join:
        if invite.uses < [i.uses for i in invites_after_join if i.code == invite.code][0]:
            inviter = invite.inviter
            await member.send(f"You were invited by {inviter.mention}")
            break```
#

?

#

@hazy turret like this?

fresh sierra
#

since ur comparing 2 times the same thing

#

but you can use a database to save each time the invite and they usage, then you can compare

wheat field
#

gonna need a db like he said but u can use mysql

wheat field
#
from discord.ext import commands
import mysql.connector

class InviteTracker(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.cnx = mysql.connector.connect(
            user=
            password=
            host=
            port=
            database=
        )

    async def create_invite_event(self, invite, invitee):
        try:
            cursor = self.cnx.cursor()
            cursor.execute("INSERT INTO invite_events (invite_code, inviter_id, invitee_id, invite_date) VALUES (%s, %s, %s, %s)", (invite.code, invite.inviter.id, invitee.id, invitee.joined_at))
            self.cnx.commit()
        except mysql.connector.Error as err:
            print(f"Error: {err}")


            
    async def create_invite_on_duplicate(self, invite):
        try:
            cursor = self.cnx.cursor()
            cursor.execute("", (invite.code, invite.inviter.id))
            self.cnx.commit()
        except mysql.connector.Error as err:
            print(f"Error: {err}")
            
            
    @commands.Cog.listener()
    async def on_member_join(self, member):
        try:
            invites = await member.guild.invites()
            for invite in invites:
                if invite.uses > 0:
                    inviter = invite.inviter
                    await self.create_invite_event(invite, member)
                    await member.send(f"You were invited by {inviter.mention}")
                    embed = discord.Embed(title="Invite Tracker", description=f"{member.mention} was invited by {inviter.mention}", color=discord.Color.blue())
                    await self.bot.get_channel(1271983219230900224).send(embed=embed)
                    break
        except discord.Forbidden:
            print("Error: Forbidden")
        except discord.HTTPException as err:
            print(f"Error: {err}")

def setup(bot):
    bot.add_cog(InviteTracker(bot))```
#

i tried

elfin inlet
#

if I have integration_types = [both], then how do I check if the command is invoked in a user install?

#

the reason is since bots cant react to user installs, which is what its trying to do, causing an error

#

can I do ctx.integration_type or smth?

little cobalt
wheat field
#

why

little cobalt
#

what do you mean with why?

little cobalt
wheat field
#

fixing rn

#

thanks

elfin inlet
little cobalt
#

I never used user install commands

#

@sage tendon could help with that

wheat field
#

that explained

#

it a;;

#

why my events wouldnt work 😭

sage tendon
#

oh i thought you were asking why = [both] doesnt work lmao

#

i think you need this

#

and then check whether guild is none, that's a user install

elfin inlet
sage tendon
#

well, it could also still be a DM command invocation i think

elfin inlet
#

ik you need discord.IntegrationType.user_install etc

elfin inlet
#

im p sure

sage tendon
elfin inlet
#

oh wait we're going in circles

#

lol

#

the issue is not checking if its in a dm, but if its a user install invoked in a server that doesnt have the bot

#

cause u can do that

sage tendon
elfin inlet
#

oki

#

ty

#

so its if discord.InteractionContextType?

sage tendon
#

No, the context tells you where an interaction happened

#

you need to check if guild is none in ctx.interaction.authorizing..thingy.guild

elfin inlet
#

well yeah I mean if discord.InteractionContextType == discord.IntegrationTypes.user_install

sage tendon
#

thats literally one of the first things i said lol

sage tendon
#
if ctx.interaction.authorizing_integration_owners.guild is None
elfin inlet
#

ohhhhh

#

ok ty

#

im dumb lmao

deft kestrel
#

Any problems with bots?

#

WARNING: Shard ID None heartbeat blocked for more than 10 seconds.

sage tendon
#

do you have a non-async db or a lot of heavy blocking code?

deft kestrel
#

but i got nwo have this problem

sage tendon
#

that doesnt stop code from being blocking lol

deft kestrel
#

no code changes

elfin inlet
#

ctx.defer() just gives your bot more time to respond

#

you can still write blocking code

sage tendon
#

if your DB isnt async you should just switch over to the async version of whatever db you use

#

typically its just changing the import and adding await

elfin inlet
#
ctx.defer()
time.sleep(0.5)
``` will still be blocking
little cobalt
sage tendon
#

If you're new to python its an understandable mistake

deft kestrel
#

nevermind, it's an third party service that cause this error

fresh sierra
#

.tag blocking

sly karmaBOT
#

In asynchronous programming a blocking call is essentially all the parts of the function that are not await. Do not despair however, because not all forms of blocking are bad! Using blocking calls is inevitable, but you must work to make sure that you don’t excessively block functions. Remember, if you block for too long then your bot will freeze since it has not stopped the function’s execution at that point to do other things.

A common source of blocking for too long is something like time.sleep(). Don’t do that. Use asyncio.sleep() instead. Similar to this example:

# bad
time.sleep(10)

# good
await asyncio.sleep(10)

Read more

meager token
#

ctx.author.get_role is allways returning none, how do I find a users role with ApplicationContext from a slash command??

#

ctx.author.roles is none too

#

ctx.user.* is also allways none

#

It works just fine when I use the undocumented *._roles but not *.roles, this is in the first 2 lines and its the copy paste from example??

#

why does .roles even exist when its just a broken frontend of ._roles

deft kestrel
#

What are the best ways to make a temp role command?

shell radish
deft kestrel
shell radish
keen relic
#
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.12/site-packages/discord/ext/commands/core.py", line 180, in wrapped
    ret = await coro(*args, **kwargs)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/container/banking/deposit.py", line 36, in deposit
    try:
  File "/home/container/.local/lib/python3.12/site-packages/discord/abc.py", line 1666, in send
    data = await state.http.send_message(
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/container/.local/lib/python3.12/site-packages/discord/http.py", line 368, in request
    raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50007): Cannot send messages to this user
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.12/site-packages/discord/ext/bridge/bot.py", line 144, in invoke
    await ctx.command.invoke(ctx)
  File "/home/container/.local/lib/python3.12/site-packages/discord/ext/commands/core.py", line 959, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/home/container/.local/lib/python3.12/site-packages/discord/ext/commands/core.py", line 189, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: Forbidden: 403 Forbidden (error code: 50007): Cannot send messages to this user```
#

dm is open

#

of the user

fresh sierra
#

does the bot is in the same server as the user ?

keen relic
#

yeap

fresh sierra
keen relic
fresh sierra
#

try

keen relic
#

user isn't online

keen relic
fresh sierra
#

and you can you dm him / recevied message

keen relic
fresh sierra
rain dune
#

ctx.guild.get_member(config.bot_id).display_avatar

does this thing have any issue? it seems that it dont return anything

sly karmaBOT
# rain dune ```ctx.guild.get_member(config.bot_id).display_avatar``` does this thing have a...

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.

lofty parcel
jolly shuttle
#

Can I have f"<@{user_id}>" inside of an embed?

shell radish
#

not in all fields

jolly shuttle
#

Not at all in fields (i.e. add_field), but maybe in description, author, footer etc?

shell radish
#

seems to work in description and field values

jolly shuttle
#

Im getting no luck with

embed.add_field(name=f"<@{user_id}>", value=f"{val*100:.2f}%", inline=True)

i even made sure to try user_id as an int

shell radish
#

it will only render in the value section

jolly shuttle
#

I just guessed that might be it.. thanks!

shell radish
#

maybe you can try using description instead?

jolly shuttle
#

Nah value should be fine

#

Thank you

silk spire
hexed herald
#

hey can someone help me getting my bot to really stop xD

bot = Bot()

@bot.listen("on_stop")
async def on_stop():
    await bot.api.close()
    await bot.db.close()
    await bot.close()

if __name__ == "__main__":
    try:
        loop = asyncio.get_event_loop()
        print(os.getpid())
        loop.run_until_complete(bot.start(DISCORD_API_KEY))
    except KeyboardInterrupt:
        bot.logger.critical("Shutting down...")
        print("I AM NOT DEAD")
        print("yet")
        bot.dispatch("stop")
        exit_()
        loop.run_until_complete(bot.close())

        # cancel all tasks lingering
    finally:
        loop.close()

I've got this piece of code to start the bot and later stop the bot on KeyboardInterrupt and in the stop dispatch every job with some async connection get's closed (e.g. aiosqlite connections and aiohttp sessions) but the process does not stop I am also closing the bot in the on_stop event even through when I let loop.run_until_complete() it's not completely shutting down this is why I use os.exit() (importet as exit_()) to exit the process. but it's not stopping

#

it' s remaining unresponsive since many minuets now and gave me this traceback

Traceback (most recent call last):
  File "E:\Programming\PyCharm\Dragons-BotV2\main.py", line 90, in <module>
    loop.run_until_complete(bot.start(DISCORD_API_KEY))
  File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 640, in run_until_complete
    self.run_forever()
  File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\asyncio\windows_events.py", line 321, in run_forever
    super().run_forever()
  File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 607, in run_forever
    self._run_once()
  File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 1884, in _run_once
    event_list = self._selector.select(timeout)
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\asyncio\windows_events.py", line 444, in select
    self._poll(timeout)
  File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\asyncio\windows_events.py", line 817, in _poll
    status = _overlapped.GetQueuedCompletionStatus(self._iocp, ms)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
KeyboardInterrupt
Exception in thread Thread-1:
Traceback (most recent call last):
  File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\threading.py", line 1038, in _bootstrap_inner
    self.run()
  File "E:\Programming\PyCharm\Dragons-BotV2\venv\Lib\site-packages\discord\gateway.py", line 166, in run
    f = asyncio.run_coroutine_threadsafe(coro, loop=self.ws.loop)
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\asyncio\tasks.py", line 926, in run_coroutine_threadsafe
    loop.call_soon_threadsafe(callback)
  File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 806, in call_soon_threadsafe
    self._check_closed()
  File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 519, in _check_closed
    raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\threading.py:1040: RuntimeWarning: coroutine 'DiscordWebSocket.send_heartbeat' was never awaited
  self._invoke_excepthook(self)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

please ping me if someone responds to this

little cobalt
sage tendon
#

on_stop isnt even a thing in pycord

#

Or at least it's not documented if it exists

#

so i dont think thats pycord

little cobalt
sage tendon
#

lol

#

what is bro running

little cobalt
#

same for nextcord

sage tendon
#

@hexed herald

lofty parcel
#

He's dispatching his own event

#

bot.dispath("stop")

sage tendon
#

oh i see
but why

#

literally all of that code could be 2 lines

lofty parcel
#

Because they're coros

#

Just kill the process tbh

sage tendon
#

bot = discord.Bot(...)
bot.run(...)
simple as that

#

also accounts for keyboard interrupts by the fact that keyboardinterrupts kill programs by default

hexed herald
#

hi again, I am dispatching my own event because I've external connections which need to be closed before the bot shuts down like normal.

class Bot(multicogBot, commands.Bot):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.client_version = VersionInfo(1, 3, 3, "")
        self.api: aiohttp.ClientSession = None  # type: ignore
        self.boot_time = datetime.now()  # Ignoring because it's dynamically allocated
        self.db: ContentDB = None  # type: ignore
        self.sts: ShortTermStorage = None  # type: ignore
        self.ipc = ipc.Server(self, secret_key=IPC_SECRET)
        self.logger = CustomLogger(name="core", start_stamp=self.boot_time)

And since I've attached the db like that, to be able to access it in cogs, the bot does not shut down like a "simple" instance
(the None from the db is later replaced while the on_ready event)

sage tendon
#

but if the bot process dies, so do all the connections

hexed herald
#

yeah, the process is not dying, it's living as a kind of zombie ;-;

#

the bot isn't online but the process is not dead

sage tendon
#

if you ctrl+c?

#

also, what is this

hexed herald
#

legacy code, good you mention it xD

#

does not change the result if I remove it

sage tendon
#

yea i mean i get that but i dont get the overcomplicated start and stop of your bot

#

if you stop it with ctrl+c the process will die completely

#

and thats also the issue, something during your startup (i think)

hexed herald
#

but if I don't do it the complicated way it's taking ages until it stops being online and even longer until the process stops

#

with the complicated way it at least stops being online instantly even through the process is not really dying

sage tendon
#

why? you're starting it the exact same way in both cases

hexed herald
#

I have no clue, that's how I ended up here πŸ˜…

sage tendon
#

remove all this and replace it with a simple bot.run

hexed herald
#

I did, the process is not dying since ~4 minuets

sage tendon
#

did you ctrl+c?

hexed herald
#

yes

sage tendon
#

show

hexed herald
sage tendon
#

i dont see any ctrl+c input

#

because it should print to the console instantly

hexed herald
#

(the cursor stops blinking)

sage tendon
#

also to test it just put all your closing stuff after bot.run

hexed herald
#

current code + console

#

but I still can't reuse the terminal

#

and the process is still listed in the taskmanager

sage tendon
#

i think your cmd is borked lmfao

hexed herald
#

should I try with powershell xDDD

hexed herald
#

I had an Idea that worked o.o

    pid = os.getpid()
    bot.run(DISCORD_API_KEY)
    bot.logger.critical("Exiting")
    psutil.Process(pid).terminate()

Just killing the process after the bot finished running did the job

tiny fractal
#

is there a reason why my bot doesn't generate auditlog entries?

sage tendon
#

for what action

tiny fractal
#

specifically roles

#

it used to make audit log entries when it granted and removed roles. now it doesn't

#

but they generate when i do it my self

sage tendon
#

something in the very far back of my head tells me I had something similar too but I don't really remember

#

not sure, lemme test with my own bot in a bit
if anything it's a discord change or issue tho, nothing to do with your bot or pycord

tiny fractal
#

bummer

#

yea, weird. it shows audit entries when the bot creates and deletes channels and sets overrirdes

keen relic
#

can we set multiple value of command option

sage tendon
#

an option can only have one value passed to it

stray pasture
#

my bot was relying on those audit log πŸ˜„

tiny fractal
#

same lol

stray pasture
#

what is happening πŸ˜„

#

no anoncement about it either

#

not even a warning

#

is there a way to report it to discord ?

sage tendon
#

they actively ignore bug reports, so no

#

don't waste time trying, i've done so numerous times

stray pasture
sage tendon
#

yip

stray pasture
sage tendon
#

i've easily reported 10+ minor-to-severe bugs by now, not a single one has been fixed

#

some are over 2y old

stray pasture
#

damn, my bot will be broken because of this to πŸ˜„

edgy nest
#

since it's an api problem

#

(most likely)

sage tendon
#

good luck

stray pasture
#

Thank you ! I will need luck ahaha yes

lapis dock
round heart
errant trout
#

are you intercepting keyboardinterrupt or something

fossil valve
#

hey, is there a way to catch autocomplete errors (e.g an event like we have for slash commands)?

fresh sierra
#

Hi, my bot rate limit a lot about message, but i dont have any fetch_message so what can be the cause of that ?

fresh sierra
#

but i will wait

#

i think it might be because i just switch version

#

and so the old one already rate limit a lot

sage tendon
#

yea I was also gonna say history and big prunes

fresh sierra
#

might be big prune then

#

thanks

heavy inlet
#

How do I add a button to a message ONLY when a certain condition is True?

little cobalt
sage tendon
#

like what condition

heavy inlet
#

boolean, either True or False

sage tendon
#

Yea thanks I know what booleans are

#

I mean what condition in particular you're checking for

errant trout
deft kestrel
#

for how much time discord caches an image (webp)?

sage tendon
#

wdym?

deft kestrel
sage tendon
#

image links outside of discord are valid for 24h

deft kestrel
sage tendon
#

inside of discord they're fetched even if the link is over 24h old

sage tendon
deft kestrel
sage tendon
#

restart your discord ig

deft kestrel
sage tendon
#

and wdym when you open it

deft kestrel
#

via browser

sage tendon
#

oh you mean you changed what image the link points to?

deft kestrel
#

yep

#

image replace

sage tendon
#

No clue then, the client caches stuff for relatively long

#

really you should just edit the embed if you plan on changing what the image is more often, and create new links

deft kestrel
#

deam

#

so it's only the client cache?

#

not server-side cache right

sage tendon
#

hm no idea actually, try clearing your local cache

fresh sierra
#

my decorator doesnt work and just return true to the command, am i the only one ?

#

(mean everyone can use every single command

#

like it does not even get print

#
    @staticmethod
    def has_perm(perm_level: str | None = None):
        async def wrapper(ctx: LumabotContext):
            print(ctx.command)
            perm = perm_level
        return commands.check(wrapper)
#
    @Lumabot.group("bot")
    @Lumabot.command()
    @Lumabot.has_perm()
    async def ping(self, ctx: LumabotContext):
sage tendon
#

show the entire decorator code

fresh sierra
#

like it does not even print the first line

sage tendon
#

why do you not use the default @commands.check decorator

#

why do you do custom copies of literally everything the library offers

fresh sierra
#

when im doing the help, it does trigger the print of the decorator

#

well the slash trigger the print

sage tendon
#

so when does it not work

fresh sierra
#

using prefix

sage tendon
#

bridge group?

fresh sierra
#

yep

sage tendon
#

oh boy

#

no idea about those

fresh sierra
#

i will check how does it invoke it

#

i thing its a library issue

sage tendon
#

bridge is messy

fresh sierra
#

i did implement my thing

#

cos bridge cant work rn

#

but its still relying on bridge in some part

sage tendon
#

then use normal bridge first to check if it isnt an issue with your code

#

because i think, depending on how custom you made it, you are invoking the command incorrectly and bypass the checks

fresh sierra
#

and i will check which invoke part is use

#

if its prefix one

#

or another one

sage tendon
#

just saying because of this

fresh sierra
#

yeah this is handle before by the

if await self.can_run(ctx, call_once=True):
#

and in my case this return True

#

but it doesnt trigger the decorator

#

which is the issue

sage tendon
#

im not sure if it works that way but can you check the checks attribute of the command?

#

cuz this

fresh sierra
#

which seems to be only the global check

#

which is strange, both part of the code does the same thing

#

only difference is the ctx which is one time a prefix and another time a slash

sage tendon
#

can you change the print to just be a letter instead of ctx.commands

#

maybe that is null somehow? idfk

fresh sierra
#

also tried

#

just the can_run return always true

#

but trigger the decorator only for the slash command

sage tendon
#

no clue then

#

i hate bridge

fresh sierra
#

gonna try to debug that bug it seems to be from the context part

fresh sierra
#

so i will now have to check about the command invoke itself

errant trout
fresh sierra
#

but i dont really understand why the prefix are not submitted to that decorator while the slash is

#

ctx.command class seems to be
<class 'discord.ext.commands.core.Group'>

#

so update now i check the different self.checks for each command, the one for the slash command find the
[<function Lumabot.has_perm.<locals>.wrapper at 0x7f37d120ac00>]
while the prefix return []

#

i fixed it

sage tendon
#

how?

fresh sierra
#

while it should have been a copy AND the checks

vague plaza
#

whats discord bots upload limit?

sage tendon
#

file size?

vague plaza
#

yeah like video

#

they keep changing it for users but idk for bots

sage tendon
#

25MB

vague plaza
#

thanks, and maximum text character limit?

sage tendon
#

4000

little cobalt
sage tendon
#

Discord says so

#

25MiB, actually

hexed herald
#

at least that's my lastest information

sage tendon
#

No.

#

Official Discord Documentation.

hexed herald
#

huh, that's wierd that it's different for normal users and bot's but okay, learned something new

sage tendon
#

Bots have some nitro features to a degree

#

like animated avatars

#

and uhh

#

banners

lofty parcel
#

Or external emojis

sage tendon
#

stickers too right?

fresh sierra
#

80% of cpu usage for a 2k guild bot with 4 shards

#

should i begin to look about it or it seems normal to u

sage tendon
#

80% is usually the threshold to check what you can do

#

aka bigger VPS usually

fresh sierra
#

its on pterodactyl so like its for one of my bot only

sage tendon
#

thats great, but if you have 80% cpu usage you still need to get a bigger VPS sooner or later

fresh sierra
#

i have 4v core so im at like 150 in total out of 400

sage tendon
#

then why do you say 80% lol

fresh sierra
#

80% for one of my bot

#

so like does i have an issue in my code or its jsut normal for a bot with 2k

sage tendon
#

with no info about the CPU it could be anything

fresh sierra
#

i do have a lot of even/loop

sage tendon
#

its probably just the amount of events at 2k guilds

fresh sierra
#

my bot test has less than 5% so yeah might be just number of event

sage tendon
#

limit your intents if possible

fresh sierra
#

yeah cant since i use them, but i will thing about the on_presencd

#

implement more cache i think

#

does on_connect is supposed to be trigger for each shard connect ?

#

same for on_ready

torn barn
#

.rtfm on_connect

torn barn
#

There is on_connect and on_shard_connect

#

So for shards it dispatches the second one

#

And after connecting every shard it dispatches on_connect fron what I read

fresh sierra
#
        self.dispatch("connect")
        self.dispatch("shard_connect", data["__shard_id__"])
torn barn
#

Then thats it

errant trout
#

(but they get 6000 through embeds so eh)

sage tendon
#

bruh right, forgor

#

dumb limit

shadow sigil
#

question, what the heck does this error mean

Ignoring exception in on_application_command_error
Traceback (most recent call last):
  File "...\.venv\Lib\site-packages\discord\client.py", line 409, in _run_event
    await coro(*args, **kwargs)
  File "...\bot.py", line 182, in on_application_command_error
    await ctx.respond(response)
  File "...\.venv\Lib\site-packages\discord\interactions.py", line 616, in respond
    return await self.response.send_message(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "...\.venv\Lib\site-packages\discord\interactions.py", line 957, in send_message
    await self._locked_response(
  File "...\.venv\Lib\site-packages\discord\interactions.py", line 1288, in _locked_response
    await coro
  File "...\.venv\Lib\site-packages\discord\webhook\async_.py", line 222, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
#

the bot just gave a The application did not respond error on discord

#

but running the command a second time worked fine

errant trout
#

initial response took too long, so when it tried to respond discord gave you an error; but your error handler also tries to use the same interaction token to respond, so you errored again

#

then your logs also show that your autocomplete is taking too long

shadow sigil
#

...

#

i'm guessing it's probably due to it being idle for an extended amount of time

#

because basically the first thing the command does is await ctx.defer()

maiden bloom
#

Is there a code example for setting up entitlement checks and such?

fresh sierra
#

anyone experiencing issue with mention command ?

    return f"</{self.qualified_name}:{self.qualified_id}>"
                                self.parent.qualified_id
AttributeError: 'NoneType' object has no attribute 'qualified_id'
clear lark
#

is it possible to setup in app purchases on my bot, SKUs rather

sage tendon
#

sure

sage tendon
fresh sierra
sage tendon
#

100% sure?

fresh sierra
#

seems like something the bot.walk_application_command return []

#

even if the command work

frail basin
#

Am I doing something wrong here?
This is what it prints:

i=0 role.name='@everyone' role.position=0
i=1 role.name='test' role.position=1
i=2 role.name='new role' role.position=1
i=3 role.name='Akos test' role.position=2
i=4 role.name='12345' role.position=3
i=5 role.name='test2' role.position=4
i=6 role.name='----- Client Roles -----' role.position=5
i=7 role.name='Network Support' role.position=6
i=8 role.name='Technical Support' role.position=7
i=9 role.name='Staff' role.position=8
i=10 role.name='Management' role.position=9
i=11 role.name='.' role.position=10
i=12 role.name='LDG Dev' role.position=11
#

How can 2 roles have the same position?

sage tendon
frail basin
#

Oh, thanks

echo wraith
sage tendon
#

no idea

frail basin
frail basin
#

Isn't that only for moving a single channel?

#

I am basically looking for the channel counterpart of Guild.edit_role_positions

sage tendon
#

Don't think that's in pycord
and i'm wondering why the endpoint exists at all, like, with roles it makes sense, e.g. in the UI you can move them around fine and then click save
But channels, you usually only move one-by-one
and typically you dont move enough channels at once to justify a bulk operation

frail basin
#

Seems like the function exists for it actually, after looking into how TextChannel.move is implemented

sage tendon
#

yea but in a private attribute so not really meant to be used
odd

#

oh wait nvm

#

ah idk lol

frail basin
sage tendon
#
  1. why do you have so many channels
  2. just do it in a loop really
frail basin
#

Discord would nuke the IP if I looped over all the channels

shell radish
sage tendon
#

i dont think channel move limits are low

#

its just channel renames that are mega limited

frail basin
#

I am forced to use channel.edit, since in some cases I also need to move the channel to a different category

frail basin
sage tendon
#

no clue if discord specifically applies the rate limit to renames, or all edit operations

frail basin
#

all edit operations

#

even if it doesnt actually do anything

sage tendon
#

damn

shell radish
frail basin
# sage tendon damn

This would ratelimit the bot after the 3rd - 4th cycle, even though nothing actually happens.

sage tendon
#

would this be worth properly putting into the library?

shell radish
#

you can always open a feature request

sage tendon
#

yea i'm just wondering if like, its worth it / has potential or if its a waste of time

#

i never really do feature requests ever for anything

frail basin
fresh sierra
#

and maybe it was a bug and they where lazy to correct it

frail basin
frail basin
#

However I'll only need to send a single request this way.

echo wraith
fresh sierra
ivory wind
#

hello, i have an extension that's made up of a directory. i am able to load it with recursive = True but dont see a way to do that with re/unload

fresh sierra
meager token
#

why is this happening

#

it works for everyone except me

fresh sierra
meager token
#

and theres no error

fresh sierra
#

you are i think

meager token
fresh sierra
#

i think thats what missing perm mean here

meager token
#

and thats only when it runs, its not running because of "missing permissions"

fresh sierra
#

did you check the default permission from discord ?

meager token
#

that exists?

#

how do I control that?

fresh sierra
#

/ try to reload ur discord

meager token
#

Ive allready done that

fresh sierra
#

in the discord server setting

meager token
#

I have permission in discord

fresh sierra
#

you can choose about the permission requiered

meager token
#

why cant it say that

fresh sierra
#

maybe

meager token
#

bruh

fresh sierra
meager token
#

and it doesnt fix when I reload discord