#Basic Pycord Help

1 messages Β· Page 48 of 1

sage tendon
#

like this would be cool

#

I started with js when making discord bots and js has that

#

example?

errant trout
#
embed = (
  discord.Embed(title="wow")
  .set_image(url="...")
  .set_footer(text="...")
)```
sage tendon
#

oh neat

quartz umbra
#

thanks, it works great!

errant trout
#

allgood

unkempt cipher
#

And I love automod

haughty grove
#

yes

#

it works fine if delete_existing is True tho

quartz umbra
jagged ledge
#

Hi, all! Weird question:

  • Given the ID of a thread, what's the best way to determine the sent date of the latest message in it?
lofty parcel
jagged ledge
#

Oh, that's class. Thanks much!

#

And to retrieve a thread object based on the string ID - what would I use?

lofty parcel
jagged ledge
#

Magnifique

errant trout
#

Uhhh btw every channel/thread has a last_message_id attribute

#

So you can just pass it into discord.Object and get created_at

#

(There's also last_message, but it's cache reliant)

hazy turret
#

On Discord it is not possible to prevent the user from downloading a video. Is there a way to track when a user downloads a video?
Or do you have any suggestions on how I can embed a video on Discord without a user being able to download the video but still watch it?

little cobalt
hazy turret
sage tendon
#

You can't

#

your only shot is finding a video hosting site that does this, and even that is trivial to bypass

#

why are you even trying to stop them from downloading them

hazy turret
sage tendon
#

ever heard of patreon

#

or idk any other paid content lock service

echo wraith
#

Vimeo is quite hard to download from if you disable downloads

#

I know it cuz I spent time hacking it

#

and it wasn't easy

hazy turret
sage tendon
#

I don't see any reason why you'd ever wanna watch a video in discord

#

just link it

#

people have browsers for a reason

hazy turret
#

Okay okay thanks πŸ˜„

echo wraith
#

Can you have sub sub command groups

#

ie

#

/test group1 group2 help

sage tendon
#

no

#

there is no way you ever need that

viscid depot
#

Do we have functions to easily manage emojis that have been uploaded directly on our bot?

sage tendon
#

manage how?

viscid depot
#

Get a list, covert an emote name to an emote id, and things like that.

sage tendon
#

Well, it came out after 2.6 released, so its certainly not in pycord yet

#

if you dont have like 400 emojis you can just put it into a class or something in an emoji.py file and map the names to their pasteable strings you can get from the developer website

#

thats what id do anyway

lean garnet
#

Hi, How do I make an option that accept only categories ?

#

please

sage tendon
#

channel_types=[discord.ChannelType.category]

#

you dont need required=True btw

#

or the slashcommandoptiontype might work there too

#

and also, type is the second positional argument, so you can just remove the type= and save some space lol

lean garnet
#

like that ? I still have the channels that appear

#

because of that maybe ?

sage tendon
#

no, the typehint in the function header is ignored if you use the decorator

#

make sure to restart discord

viscid depot
sage tendon
#

btw, @lean garnet, i think if you pass channel_types the input type is ignored completely so you can also completely delete it

lean garnet
sage tendon
#

np

red mist
#

You're trying to prevent piracy but- we all know that's not possible :)

quartz umbra
#

Anyone know why this command ain't loading?

from discord.ext import commands
import discord
from helpers import config_helper, firebase_helper


class TesterManagement(commands.Cog):
    def __init__(self, bot) -> None:
        super().__init__()
        self.bot = bot

    @commands.slash_command(description="test")
    async def list_test(self, ctx, list_test: int):
        await ctx.respond(str(list_test))


def setup(bot):  # this is called by Pycord to setup the cog
    bot.add_cog(TesterManagement(bot))  # add the cog to the bot

I don't see it appear in the list, I think I've added the cog correctly, just can't see the issue:```py
cogs_list = [
"config_cog",
"info_cog",
"ranks_cog",
"stats_cog",
"ticketing_cog",
"tester_cog",
]

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

bot.run(TOKEN)

quartz umbra
little cobalt
#

mhm

#

did you refresh discord

#

after you run the bot

quartz umbra
#
.
β”œβ”€β”€ LICENSE.txt
β”œβ”€β”€ README.md
β”œβ”€β”€ __init__.py
β”œβ”€β”€ assets
β”œβ”€β”€ cogs
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ config_cog.py
β”‚   β”œβ”€β”€ info_cog.py
β”‚   β”œβ”€β”€ ranks_cog.py
β”‚   β”œβ”€β”€ stats_cog.py
β”‚   β”œβ”€β”€ tester_cog.py
β”‚   └── ticketing_cog.py
β”œβ”€β”€ config.json
β”œβ”€β”€ database.db
β”œβ”€β”€ helpers
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ 
β”‚   β”œβ”€β”€ config_helper.py
β”‚   └── firebase_helper.py
β”œβ”€β”€ main.py
β”œβ”€β”€ requirements.txt
quartz umbra
sage tendon
#

why do you have an __init__ in your cogs folder

sage tendon
quartz umbra
valid panther
sage tendon
#

theirs isn't

quartz umbra
#

so i added the guild_ids param and its loaded now, maybe I didn't give discord enough time to register the command? Someone told me it takes less than like 2 minutes on 2 servers (I've waited at least 10 i'd say)

sage tendon
#

its close to instant

#

never takes more than 1-2 seconds for me

quartz umbra
#

yeah, same here.

valid panther
#

close and open

sage tendon
#

we already went over that

quartz umbra
sage tendon
#

you need to restart discord

quartz umbra
#

so anyways, i did have another question, if I can ask:
What's the best way to take a list as an argument? Not a mutable sized list, but just a fixed size. Is having an option for each element the only option?

sage tendon
#

i use | in my own personal bot to make one option take multiple things

#

just seperate the things by | when typing the option, and handle it in your code

#

(thats kinda ugly and i wouldnt do that for a public bot tho)

#

apart from that, yea, you can only really do multiple options

valid panther
#

A question guys.

I'm using the @discord.default_permissions(ban_members=True) decorator so that users who don't have ban permissions can't execute commands. But is there a special decorator for when the bot has not been given the necessary permissions?

quartz umbra
#

interesting. Cuz my particlar issue is sort of like a "check the options that apply to you" issue. Atm, i was thinking just bools for each possible option, but i was wondering if anyone had any cleaner solutions

sage tendon
errant trout
sage tendon
#

oh

valid panther
sage tendon
errant trout
#

(this will raise CheckFailure, it's not a discord sided thing)

#

specifically, BotMissingPermissions

sage tendon
#

yea i just thought of the good old
try:
ban()
except ...:
ctx.respond("No")

valid panther
#

thxx

sage tendon
#

could also write a global error handler that handles that, so you dont have to duplicate that everywhere

#

does commands.CommandNotFound apply to slash commands?

sage tendon
#

what about commands.MemberNotFound

little cobalt
#

that should work

sage tendon
#

probably if you pass a random user ID

#

how tf does this shadow any variable?

#

the class has nothing called "member"

#

okay.. apparently the for member in members BELOW was the problem

errant trout
# viscid depot Do we have functions to easily manage emojis that have been uploaded directly on...

we have a functional draft PR if you wish to install
https://github.com/Pycord-Development/pycord/pull/2501
pip install -U git+https://github.com/Pycord-Development/pycord.git@refs/pull/2501/merge
Main Client additions:

stoic patio
#

does the on_disconnect event get fired if my bot gets auto-disconnected because of this

errant trout
#

yes

little cobalt
echo wraith
#

Is there an even listener or a method to override that would allow me to run some code EVERY time a command is run, including application bridge and prefix commands

errant trout
#

there's a few

#

on_command, on_application_command, and on_bridge_command all fire BEFORE the command runs.

#

if you want after, then add _completion to the end

#

(note that on_bridge_command fires ALONGSIDE the other two listeners - make sure you're not doubling events)

hollow plank
#

I do the following command message.poll.duration for polls, but it only returns None and not the poll duration?

errant trout
#

you should use expiry instead

hollow plank
#

oh, ok thank you

vague plaza
#

what's the limit of characters a bot can send in a message?

little cobalt
#

keep in mind that a space is also a character

rough heron
#
import discord
import asyncio
from discord.commands import option, Option
from discord.ext import commands
from datetime import datetime, timezone, timedelta
import re

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

bot = discord.Bot(intents=intents)

@bot.event
async def on_message_edit(before, after):
    print("Author id " + str(after.author))
    print("Message id " + str(after.id))
    if after.author.id == 713484585874227220:
        print(after.channel.id)
        if after.channel.id == 935343526626078850:
            await process_voyage_data(after)

Question. I've got the following code. My bot seems unable to sense message edits from anyone in one, specific channel... except for a bot (carlbot).

Every other channel it senses fine for everyone, and it has administrator, and I can clearly see it on the sidebar for that channel, so I'm confused on why it wouldn't be sensing the message for users in that channel.

rough heron
valid panther
# errant trout ext.commands.bot_has_permissions

Would the use of bot permissions be like this?

from discord.ext.commands import bot_has_permissions

@bot_has_permissions(ban_members=True, kick_members=True, manage_roles=True)
    @discord.slash_command(name="user", description="πŸ”β― Displays a member's information")
    async def user(self, ctx, user: Option(discord.Member, description="Information", required=True)):
errant trout
#

command decorator is ALWAYS first, but yes

rough heron
errant trout
#

if the bot doesn't have all of these permissions, BotMissingPermissions will be raised - handle this in on_application_command_error

errant trout
rough heron
#

Okay, whats the best method to sense all messages edited?

errant trout
#

you probably want on_raw_message_edit instead, but note you may have to fetch messages on request

rough heron
#

I'll look into it. Thank you.

errant trout
#

(please read the docs on that)

hybrid fossil
#

Hi there!
I'm having trouble pinpointing the error even with explanations from Chat GPT or rereading the code.
Could you explain it to me in a few words?

Traceback (most recent call last):
  File "C:\Users\xxxx\Documents\GitHub\Bot.Dystopia\.venv\Lib\site-packages\discord\ui\modal.py", line 342, in dispatch
    self.remove_modal(value, user_id)
  File "C:\Users\xxxx\Documents\GitHub\Bot.Dystopia\.venv\Lib\site-packages\discord\ui\modal.py", line 322, in remove_modal
    self._modals.pop((user_id, modal.custom_id))
KeyError: (000000000000000, 'c47212bb6f180e78220674cc91b4f160')
sage tendon
#

i doubt user_id is 00000000

#

keyerror means a key you're trying to access doesnt exist usually

errant trout
#

(i.e. whatever modal you sent)

sage tendon
#

oh wait i didnt realise that thats in pycord code

valid panther
hybrid fossil
# errant trout what's the code causing this
class SteamID64(discord.ui.Modal):
    def __init__(self, user_whitelist, modal_title):
        # Initialize the modal with a title and an input field for Steam ID 64
        super().__init__(timeout=None, title=modal_title)

        self.add_item(
            discord.ui.InputText(
                label="STEAM ID 64",
                placeholder="00000000000000000",
                style=discord.InputTextStyle.short,
                max_length=25,
                required=True
            )
        )

        self.user_whitelist = user_whitelist

    async def callback(self, interaction: discord.Interaction):
        # Suppress HTTP exceptions when sending the initial response
        try:
            await interaction.response.send_message()
        except discord.HTTPException:
            pass

        # Stop the voice service if it is currently active
        await serviceVoice.voice_stop(self.user_whitelist.voice_state)

        self.user_whitelist.steam_id = None
        steam_api_key = settingAddon.steam_api_key
        embed = interaction.message.embeds[0]
        steam_id = self.children[0].value
        pattern = r"^\d+$"

        # Reset the thumbnail in the embed
        embed.set_thumbnail(url=None)

        # Validate if the input is a proper Steam ID 64
        if not re.match(pattern, steam_id):
            await self.handle_invalid_steam_id()
            return

        # Fetch user profile using the Steam API
        user_profile = apiSteam.PlayerSummaries(steam_api_key, steam_id)

        # If the profile is not found, update the embed fields accordingly
        if not user_profile.is_found():
            await self.handle_profile_not_found(embed, steam_id, interaction)
            return

        profil_visibility = user_profile.get_visibility()
        # If the profile is not public, update the embed fields accordingly
        if profil_visibility != 3 or user_profile.user_games is None:
            await self.handle_private_profile(embed, steam_id, interaction)
            return

        # Set the user's avatar in the embed
        embed.set_thumbnail(url=user_profile.get_avatar_full("avatarfull"))

        steam_name = user_profile.get_steam_name()
        creation_date = datetime.datetime.fromtimestamp(user_profile.get_creation_date()).strftime("%d/%m/%Y")

        # If the user does not own the game DayZ, update the embed fields accordingly
        if not user_profile.has_game(221100):
            await self.handle_no_dayz_game(embed, steam_id, steam_name, creation_date, interaction)
            return

        # Get the user's playtime in DayZ and update the embed fields based on the playtime
        time_dayz = user_profile.get_game_time(221100) / 60
        if time_dayz < 50:
            await self.handle_insufficient_playtime(embed, steam_id, steam_name, creation_date, time_dayz, interaction)
            return

        await self.handle_valid_steam_id(embed, steam_id, steam_name, creation_date, time_dayz, interaction)

        # Update the user's whitelist with the Steam ID
        self.user_whitelist.steam_id = steam_id
errant trout
sage tendon
#

that is GPT generated code if i ever saw it

errant trout
#

(yeah)

#

the fuckin try-except empty response???

#

voice???

sage tendon
#

no mostly just

# Very descriptive comment
code that does exactly whats described

#

for every block of code

hybrid fossil
#

This is code I made myself, but I asked chat gpt to redo the form of the code.

errant trout
#

oh yeah, i just thought those two in particular was very funny

#

is it when you submit the modal

hybrid fossil
errant trout
#

wtv works, but again i'm asking about the error...

hybrid fossil
#

So...

sage tendon
errant trout
#

i am TRYING to help, but literally can't if i don't know where it fails

hybrid fossil
#

Just a moment, I'm trying to apologize for using chat GPT to correct my error.

So, this error only appears when arriving at handle_valid_steam_id() after passing another handle.

For example:
handle_profile_not_found() -> Change steam ID -> handle_valid_steam_id() = Error

handle_valid_steam_id() -> Change steam ID -> handle_profile_not_found() = No error

#
    async def handle_valid_steam_id(self, embed, steam_id, steam_name, creation_date, time_dayz, interaction):
        # Update embed fields and play success sound for valid Steam ID
        self.update_embed_fields(embed, steam_id, status="βœ… Trouvable", visibility="βœ… Public", steam_name=steam_name, creation_date=creation_date, dayz_time=f"βœ… {time_dayz:.0f} heures")
        await interaction.message.edit(embed=embed)
        if not self.user_whitelist.dev:
            await serviceVoice.voice_say(self.user_whitelist.voice_state, "./addons/DSTP_Whitelist/sounds/step04_steamid/success.mp3")
        else:
            await serviceVoice.voice_say(self.user_whitelist.voice_state, "./addons/DSTP_Whitelist/sounds/soundBeep.mp3")
#
    async def handle_no_dayz_game(self, embed, steam_id, steam_name, creation_date, interaction):
        # Update embed fields and play error sound if user does not own DayZ
        self.update_embed_fields(embed, steam_id, status="βœ… Trouvable", visibility="βœ… Public", steam_name=steam_name, creation_date=creation_date, dayz_time="❌ Non possΓ©dΓ©")
        await interaction.message.edit(embed=embed)
        if not self.user_whitelist.dev:
            await serviceVoice.voice_say(self.user_whitelist.voice_state, "./addons/DSTP_Whitelist/sounds/step04_steamid/error_has_game.mp3")
        else:
            await serviceVoice.voice_say(self.user_whitelist.voice_state, "./addons/DSTP_Whitelist/sounds/soundBeep.mp3")
#

The problem is that, for the moment, the code remains exactly the same for both functions.

#

So I asked chat GPT to rewrite the code for me to check whether I'd made a mistake in the way I handled functions or the sending of audio messages.

errant trout
#

could you perhaps try changing the first block py try: await interaction.response.send_message() except discord.HTTPException: passto a simple await interaction.response.defer()

#

and then, replace all interaction.message.edit to just interaction.edit

hybrid fossil
errant trout
#

so that's not in the actual code?

#

(it's probably worth deferring anyway)

hybrid fossil
#

I'll film you how it works for a moment.

#

This problem also occurs when I use voice messages. If I play a short beep I don't have the problem.
So it's probably related to the audio. What I don't understand is that I turn it off at the beginning to avoid any problems.

errant trout
#

ohhhhhhhhhhhhhhhhhh

errant trout
#

(also to be clear, you can completely ignore the error with no side-effects, but it would be good to deal with)

hybrid fossil
errant trout
#

right, so can you show the code used there

hybrid fossil
#
class SteamID(discord.ui.Button):
    def __init__(self, user_whitelist):

        super().__init__(
            label="SteamID 64",
            style=discord.ButtonStyle.blurple,
            custom_id="steamID64Button"
        )

        self.user_whitelist = user_whitelist
        self.modal = modalSteamID.SteamID64(self.user_whitelist, "SteamID 64")

    async def callback(self, interaction: discord.Interaction):
        await interaction.response.send_modal(self.modal)
        await self.modal.wait()
errant trout
#

instead, define modal inside callback

#

(in retrospect this is a silly error, but it's how you would get rid of it)

hybrid fossil
#

Great, it works!
I'm still struggling with these little details!
I tested the defer and it also works perfectly, I used it for commands but I didn't know it existed for modals.
I'd go to bed less stupid.

Thanks for your help

errant trout
#

allgood

viscid depot
errant trout
red mist
#

Aaaaand discord chat only now updated again

#

Fkin shite

errant trout
#

:3

jagged ledge
#

How do I override on_error? Like, for every command in a bot. I have a custom Exception type which I'd like the bot to print to the console and ignore.

errant trout
jagged ledge
errant trout
#

if you've subclassed bot, you can just define it inside that

#

otherwise, use the @bot.event decorator

jagged ledge
#

Ah. I have not subclassed bot. Is it as simple as @bot.event(on_application_command_error)? And do I only need to speciy it once?

errant trout
#

no brackets, you name the function

#

and that will cover every error inside an application command

jagged ledge
#

Just individual commands, though? So I'd need to subclass bot if I wanted to write a one-and-done for all of them?

errant trout
jagged ledge
#

...Oh! Could you show me a rudimentary example?

errant trout
jagged ledge
#

Lemme read

stoic patio
#

do those automatic reconnects from discord fire the on_ready event

errant trout
#

maybe we need a dedicated error handling example

jagged ledge
#

Oh! This is just what I need! Thank you, @errant trout!

errant trout
#

allgood

stoic patio
#

so it doesn't always happen?

errant trout
#

it generally shouldn't, but there are some cases where it has

#

i think it's higher chance after major disconnects, but discord's own behavior on the event is a bit finicky

stoic patio
#

is that for the on_resumed event

errant trout
#

you could prevent it from triggering multiple times by setting once=True

stoic patio
#

i actually need it to trigger multiple times

errant trout
#

resumed and ready are indeed different, where resumed is the one that's meant to fire multiple times, but it is also possible for ready

#

on_resumed i think would be more reliable?

stoic patio
#

so when a bot receives those reconnect things and reconnects, the on_resumed event is the one that always fires, right?

errant trout
#

it should, yes. We have very little processing related to it, but discord describes it as such

Used to replay missed events when a disconnected client resumes.

stoic patio
#

where does the "Used to replay missed events when a disconnected client resumes." description come from

stoic patio
#

why is it called "replaying"

errant trout
#

if your bot misses events, it can still receive them after resuming

#

(probably)

stoic patio
#

interesting

#

cuz i run a db connection thingy whenever the thing goes live

jagged ledge
# errant trout allgood

I may be a doofus.

I made a custom Exception (superclass Exception) which the new method doesn't seem to be catching. It just says this:
discord.errors.ApplicationCommandInvokeError

class PreconditionError(Exception):
    def __init__(self, message):
        super().__init__(message)


async def assertOrSay(cond, msg, ctx, ephemeral=False):
    if not cond:
        await ctx.respond(msg, ephemeral=ephemeral)
        raise PreconditionError(msg)
``````py
# The objective
@bot.event
async def on_application_command_error(
    ctx: discord.ApplicationContext, error: Exception
):
    if isinstance(error, PreconditionError):
        pass
    else:
        raise error
errant trout
#

ok so, funny quirk about that one

#

if it's of type ApplicationCommandInvokeError, re-run the error handler with error.original

jagged ledge
#
@bot.event
async def on_application_command_error(
    ctx: discord.ApplicationContext, error: Exception
):             #       vvvvvvvvv   This worked!
    if isinstance(error.original, PreconditionError):
        pass
    else:
        raise error
#

Thank you!

errant trout
#

allgood

#

though uh, note that that will break for other exceptions

#

because original only exists on ApplicationCommandInvokeError

#

(and CommandInvokeError i guess)

warm linden
#

for modals is there a way i can choose a custom character limit or no?

shell radish
valid panther
#
class TeamNameModal(discord.ui.Modal):
    def __init__(self, *args, **kwargs):
        super().__init__(title="Enter Team Name", *args, **kwargs)
        self.opponent_name = None
        self.add_item(discord.ui.InputText(label="Team Name", placeholder="Type the name of your team here"))

    async def callback(self, interaction: discord.Interaction):
        self.opponent_name = self.children[0].value
        await interaction.response.send_message(f"Match accepted, you are now in the second team: `{self.opponent_name}`",
                                                ephemeral=True, delete_after=60)
        self.stop()

I'm making a modal that the idea is to return the opponent_name

await interaction.response.send_modal(modal)
await modal.wait()
opponent_name = modal.opponent_name

If I do not return a text message in the modal, the popup does not close correctly, but if I set it, it closes correctly. Is this the only way to close the popup?

#

Good morning by the way!

fresh sierra
#

You can try to pass it as a class variable so not inside the init but upper

#

class… :
oppenent_name = None
Def init () :

valid panther
# fresh sierra class… : oppenent_name = None Def init () :

I understand that your idea would be to do something similar to this, right?

class TeamNameModal(discord.ui.Modal):
    opponent_name = None

    def __init__(self, *args, **kwargs):
        super().__init__(title="Enter Team Name", *args, **kwargs)
        self.add_item(discord.ui.InputText(label="Team Name", placeholder="Type the name of your team here"))

    async def callback(self, interaction: discord.Interaction):
        TeamNameModal.opponent_name = self.children[0].value
        self.stop()
valid panther
#

There is something about the modal that I am not understanding

fresh sierra
#

You should do … = TeamModal.opponent_name

valid panther
fresh sierra
#

Because modal is the class initialized, you should do return TeamNameModal.opponent_name

#

Without initializing the class

valid panther
#
    
async def accept_match(self, interaction: discord.Interaction):
        modal = TeamNameModal()
        await interaction.response.send_modal(modal)
        await modal.wait()

        # ----------------- CODE -----------
        return  TeamNameModal.opponent_name
fresh sierra
#

Did it work @valid panther ?

valid panther
#

In the end I solved it with await interaction.response.defer()

fresh sierra
#

Defer has nothing to do with class variable as long as I know

#

But if it works it works

valid panther
weary meteor
#

is there an event that listens for whenever an error is raised anywhere in the bot

errant trout
#

on_error is ONLY for events

little cobalt
#

isnt that enough? command_error and events

#

you could add some try and except to other stuff

errant trout
#

well, my point being that they asked for an event that's raised for any error on the bot - such an event doesn't exist

little cobalt
#

so you really have to use try and except?

weary meteor
#

how do i send a modal?

rugged lodgeBOT
#

Here's the modal dialogs example.

little cobalt
#

@weary meteor

weary meteor
#

ah, why is that not under the views directory 😭

little cobalt
#

because its not at a view

#

use this instead

warm linden
#

hey i'm trying to create a "modlogs" command say a user banned through but the ban was initiated through another bot is a there a way i can still find out who the user was?

sage tendon
#

events

echo wraith
#

Short answer be like

lofty parcel
#

short answer be

sage tendon
#

why waste time say lot word when few word do trick

ebon swift
#

is it normal to be able to call that has the has_role check even if the user doesn't have the role ?

sage tendon
#

show your code

#

and ideally, you dont use these decorators for slash commands
just set up permissions inside your server settings

#

also has the added upside of not being visible to anyone else

#

and if you wanna tie it to a specific permission, there's a decorator specifically for that

ebon swift
# sage tendon show your code
 @commands.slash_command(name="set_color", description="Set your color.", guild_ids=[1265373509455057006])
    @commands.has_role(rolename)
    @discord.option(name="color", description="The color you want to set.", type=discord.Color)
    async def set_color(self, ctx, color: discord.Color):
        guild = ctx.guild
        member = ctx.author
        role = discord.utils.get(guild.roles)
        await ctx.send(f"Setting color for {member.display_name} to {color}")
        self.bot.logger.debug(f"Setting color for {member.display_name} to {color}")
#

Ignoring exception in command set_color:
Traceback (most recent call last):
File "/app/.cache/pypoetry/virtualenvs/bot-9TtSrW0h-py3.12/lib/python3.12/site-packages/discord/bot.py", line 1137, in invoke_application_command
await ctx.command.invoke(ctx)
File "/app/.cache/pypoetry/virtualenvs/bot-9TtSrW0h-py3.12/lib/python3.12/site-packages/discord/commands/core.py", line 432, in invoke
await self.prepare(ctx)
File "/app/.cache/pypoetry/virtualenvs/bot-9TtSrW0h-py3.12/lib/python3.12/site-packages/discord/commands/core.py", line 353, in prepare
if not await self.can_run(ctx):
^^^^^^^^^^^^^^^^^^^^^^^
File "/app/.cache/pypoetry/virtualenvs/bot-9TtSrW0h-py3.12/lib/python3.12/site-packages/discord/commands/core.py", line 460, in can_run
return await async_all(predicate(ctx) for predicate in predicates) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/app/.cache/pypoetry/virtualenvs/bot-9TtSrW0h-py3.12/lib/python3.12/site-packages/discord/utils.py", line 705, in async_all
for elem in gen:
File "/app/.cache/pypoetry/virtualenvs/bot-9TtSrW0h-py3.12/lib/python3.12/site-packages/discord/commands/core.py", line 460, in <genexpr>
return await async_all(predicate(ctx) for predicate in predicates) # type: ignore
^^^^^^^^^^^^^^
File "/app/.cache/pypoetry/virtualenvs/zorsbot-9TtSrW0h-py3.12/lib/python3.12/site-packages/discord/ext/commands/core.py", line 1968, in predicate
raise MissingRole(item)
discord.ext.commands.errors.MissingRole: Role 'Les HabituΓ©s' is required to run this command.

sage tendon
#

well i mean it works exactly as it should

ebon swift
#

can't I make it so the 'non role' user can't even try/see to run the command ?

ebon swift
#

thing is I don't want it to be tied to a specific permission but to a role, the members of this role can do the command the others can't see it ? or at least maybe try to catch the error and show 'you have to be {rolename} to do that. has permission would not make me able to do so

ebon swift
#

didn't knew you could do that

sage tendon
#

server settings > integrations

ebon swift
#

okay thank you very much for your help , also can I catch the error inside the function to send a message like admin should check up on integration permission, you shouldn't be able to see this ? feels off to have the bot just sending 'application doesn't respond'

sage tendon
#
@discord.Cogs.listener()
async def on_application_command_error(self, ctx, error):
    if isinstance(error, discord.MissingRole):
        await ctx.respond..
ebon swift
#

thank you !

warm linden
#

can someone help me make my bot ban users not in the server?

#
if member: 
  await interaction.guild.ban(member, reason=f"...")
  banned_users.append(user_id)
else:
  user = await interaction.client.fetch_user(user_id)
  await interaction.guild.ban(discord.Object(id=user), reason=f"...")
  failed_bans.append(user_id)
errant trout
#

you already fetched the user

#

(or if you don't want to fetch, just do discord.Object(user_id))

#

also in the first part you can just do member.ban, assuming you got them in the correct guild

warm linden
errant trout
#

no...

#

you do one or the other - EITHER fetch user and do ban(user), or DON'T fetch the user and do ban(discord.Object(user_id))

valid panther
#

Good afternoon, sorry for the inconvenience.

I'm making an embed, with an image

base64_image = img_generator.generate_image()
embed = discord.Embed(title="TEST", color=settings.embed_color)
embed.set_image(url=f"data:image/png;base64,{base64_image}")
await ctx.respond(embed=embed)

 (<class 'discord.errors.ApplicationCommandInvokeError'>, ApplicationCommandInvokeError('Application Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body\nIn data.embeds.0.image.url: Must be 2048 or fewer in length. Not a well formed URL.'), <traceback object at 0x0000018CF1CF0200>) 

#

the set_image does not accept base64 ?

sage tendon
#

"url"

little cobalt
#

lol

sage tendon
#

what you put there isn't a url

sly karmaBOT
#
f = discord.File("some_file_path", filename="image.png")
e = discord.Embed()
e.set_image(url="attachment://image.png")
await messagable.send(file=f, embed=e)```
valid panther
sage tendon
#

pass a url or do it like above.

valid panther
#

instead of passing it as base64, create the image and then pass it the path to the file

#

I understand

stoic patio
#

is it possible to clear a discord bot's message cache

rugged lodgeBOT
fresh sierra
#

Put that to []

errant trout
#

Not quite

#

It's bot._connection._messages.clear()

stoic patio
#

i don't see "_connection" as a bot attribute

errant trout
#

In docs? Because it's not documented

#

That goes for any var starting with _

#

(Probably)

stoic patio
#

i see

stoic patio
errant trout
#

Then you don't have a message cache

stoic patio
#

i see

#

i'm stupid LOL

little cobalt
stoic patio
#

lol

little cobalt
#

you also cannot use get_x anymore

noble flax
#

Can I get some eyes on my code please, I'm building another version of a previous bot I created, however for the life of me when I run the bot I can't get ANY slash commands to appear? I've gone through the code line by line vs my old bot and I just don't seem to be able to spot why the slashcommands aren't showing 😦

#

I've been looking at it for days now and accepted defeat, need some help - obviously I'm using py-cord otherwise I wouldn't be here πŸ˜„

sage tendon
#

did you try restarting discord?

noble flax
#

Had several PC reboots since then πŸ™‚

sage tendon
#

then show your code

noble flax
#

It's not a "keep restarting" your bot in debug error

#

its just never started, period.

#

so the slash commands are within a cog

#

I can confirm the cog is loaded via the log file

sage tendon
noble flax
#

sorry bad terminology, the bot starts however the slashcommand in question isn't recognised.

#
import logging
from utils.logger import CustomLogger
import discord
from discord import option
from discord.ext import commands
from discord.utils import basic_autocomplete

customLogger = CustomLogger(__name__, logging.DEBUG)
log = customLogger.get_logger()


class WarYes(commands.Cog):
    def __init__(self, bot: discord.Bot):
        self.bot = bot.user

    # Set slashcommand group and sub groups
    grp = discord.SlashCommandGroup("waryes", "This is a collection of waryes commands")
    unitgrp = grp.create_subgroup("units", "A list of unit commands")

    # mapgrp = grp.create_subgroup("maps", "A list of map commands")

    @staticmethod
    def unitAutocomplete(ctx: discord.AutocompleteContext):
        try:
            with open('./resources/units.json') as f:
                data = json.load(f)

            result = next((unit['name'] for unit in data['units'] if ctx.value.upper() in unit['name']), None)
            return result
        except Exception as e:
            log.error(f"{e}")

    @unitgrp.command(description="Returns an embed with high level unit statistics")
    @option("unit", description="You must use the Eugen stated unit name",
            autocomplete=unitAutocomplete)
    @commands.has_any_role('MEMBER', 'WARYES DEVELOPER')
    async def getunit(self, ctx: discord.ApplicationContext,
                      unit: str):
        unitname = unit.split(':')[0].rstrip()
        print(unitname)
        ctx.respond(f'Selected {unitname}')



def setup(bot):
    bot.add_cog(WarYes(bot))
    log.info("Cog loaded")
#

that is the code from my cog

#

happy to share anything else

sage tendon
#

alright, show your main file as well

noble flax
#
import os

import discord
import dotenv

from commands.replays import ReplayFile
from utils.logger import CustomLogger

# Load Logger
customLogger = CustomLogger(__name__, logging.DEBUG)
log = customLogger.get_logger()

# Load Environment Variables
dotenv.load_dotenv()

# Bot Cogs List
cogs_list = ['waryes']


class YesManBot(discord.Bot):
    def __init__(self):
        self.uptime = discord.utils.utcnow()
        allowed_mentions = discord.AllowedMentions(roles=False, everyone=False, users=True)
        intents = self.set_up_intents()
        super().__init__(
            description="I am a bot written by .lynchie for the WarYes community discord.",
            pm_help=None,
            help_attrs=dict(hidden=True),
            chunk_guilds_at_startup=False,
            heartbeat_timeout=150.0,
            allowed_mentions=allowed_mentions,
            intents=intents,
            enable_debug_events=True,
        )

    @staticmethod
    def set_up_intents():
        return discord.Intents(
            guilds=True,
            members=False,
            bans=True,
            emojis=True,
            voice_states=True,
            messages=True,
            reactions=True,
            message_content=True,
        )

    @staticmethod
    async def handle_exception(message, exception):
        log.exception(f'{message} %s', exception)

    @staticmethod
    async def setup_hook() -> None:
        try:
            for cog in cogs_list:
                bot.load_extension(f'cogs.{cog}')
                return
        except Exception as e:
            log.exception('Failed to load extension: %s', e)

    async def on_ready(self):
        log.info('Ready: %s (ID: %s)', self.user, self.user.id)
        await self.setup_hook()

    async def on_message(self, message: discord.Message) -> None:
        if message.channel.name == 'dev_bots':
            if message.author.bot:
                return
            try:
                if message.attachments:
                    for attachment in message.attachments:
                        if attachment.filename.endswith('.rpl3'):
                            filecontent = await attachment.read()
                            replay = ReplayFile(attachment.filename, filecontent, message)
                            await message.channel.send(embed=replay.getembed())
            except Exception as e:
                log.exception('Failed to process replay: %s', e)


bot = YesManBot()
bot.run(os.getenv(str('DEV_BOT_TOKEN')))
sage tendon
#

sidenote, @commands.has_any_role('MEMBER', 'WARYES DEVELOPER') i dont recommend this, its better to set this up via discord's permission settings for commands

#
async def setup_hook() -> None:
        try:
            for cog in cogs_list:
                bot.load_extension(f'cogs.{cog}')
                return
        except Exception as e:
            log.exception('Failed to load extension: %s', e)

Nope. Cogs have to be loaded before the bot starts, and ive never heard of setup_hook

noble flax
#

shit just realised, could it be the intents?

noble flax
sage tendon
#

just do bot.load_extensions("cogs") right before bot.run

noble flax
#

and I do an await in on_ready to run set_hooks

sage tendon
#

yea but you are loading the cogs too late

sage tendon
noble flax
#

ah ok

#

Copy that, will change now

#

of course On_Ready is the END of the process of loading

sage tendon
#

it works for prefix commands because they essentially just use on_message, but slash commands are only synced once during startup, and if there's no slash command currently loaded, it never syncs to discord

little cobalt
#

slash commands get synced at the on_connect event

sage tendon
#

which appens during startup
:3

noble flax
#

Thank you so much

#

Restarted discord and away I go.

sage tendon
#

np

noble flax
#

To be honest my startup process is different to my v1, I never bothered with putting it on "on_ready" I originally did just a function

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

    cogs_list = ['maintenance', 'waryes', 'warno', 'match']
    for cog in cogs_list:
        bot.load_extension(f'cogs.{cog}')
    return bot

logger = setup_logging()
bot = setup_bot()```
#

and then bot.run

#

never occured to me the issue was that

#

Lesson learn't about how the cogs/extensions load though.

sage tendon
#

my startup is

bot.load_extensions("cogs")
bot.run(config.token)
noble flax
#

Every day is a school day

sage tendon
#

thats it

#

some people have like 30 lines just to start their bot and im like why

noble flax
sage tendon
#

yes

#

im not sure how it works if you have foreign / non-cog files, but i dont have that

#

can also load them in subfolders with that

noble flax
#

Thank you once again, been a stumbling block for a while that has.

#

should of came here earlier, just figured I'd try and work it out myself.

little cobalt
#

because of the twitch bot

sage tendon
#

yea well that doesnt count lol

#

i forgor, does python have syntax to do like

object.do_this()
    .and_this()
    .and_this()
    .and_this()
echo wraith
#

to allow chained calls

sage tendon
#

yea i know that

#

but multi-line chaining?

shell radish
#

yeah. People can do that with embed creation

vital bramble
#

Are role mentions disabled by default for followup messages?

shell radish
#

yes

vital bramble
#

why?

shell radish
#

and they can’t be turned on

#

because it’s a webhook

vital bramble
vital bramble
#

using allowed_mentions=discord.AllowedMentions.all(), I was pinged

shell radish
sage tendon
#

uh, for what i know, webhooks do support everyone tho

shell radish
#

probably so you can’t ping everyone or something accidentally

sage tendon
#

i've witnessed a few servers being taken over and spammed by webhooks, and im p sure @ everyone works

#

but yea role mentions are off by default i've noticed that too

vital bramble
sage tendon
#

yea

vital bramble
sage tendon
#

oh wait you mean followup after the initial reply

#

hm, idk there

vital bramble
#

yes

#

initial reply was interaction.edit though...

#

and then a interaction.followup.send

shell radish
#

I was referring to the follow up not being able to be in a different ephemeral state than the original reply. idk why I said that. Probably because I like just woke up

vital bramble
#

oh, ok. Thx

sage tendon
#

lol

hasty meadow
#

Anyone know why these suddenly stopped working for me?

server = await bot.fetch_guild(discord_server_id)
members = server.members # now returns empty list
category = discord.utils.get(server.categories, name="my-category") # now returns None
hasty meadow
#

bot = Bot(command_prefix="!", intents=discord.Intents.all())

#

this works: members = await server.fetch_members().flatten()

#

but I couldn't find any alternative to find categories

fresh sierra
#

its not in the cache thats strange

fresh sierra
#

you can fetch it

hasty meadow
#

using which method?

fresh sierra
#

self.bot.fetch_channel(id)

sage tendon
fresh sierra
#

channel is textchannel, voice channel and categories

#

(with also the other things forum...)

sage tendon
hasty meadow
#

I was using members but it suddently started returning an empty list.

fresh sierra
sage tendon
#

in short:
why do API request when cache do trick

fresh sierra
#

because cache does not ?

sage tendon
#

it should

sage tendon
#

that is the problem that needs to be investigated

#

did you change anything since it last worked properly

hasty meadow
#

I was having other issues too, I had to re-add my app to the channel. I was thinking maybe Discord rolled out some changes to app permisions

sage tendon
#

why?

hasty meadow
#

Yesterday I suddenly couldn't connect to my server at all

sage tendon
#

wdym "connect to your server"

hasty meadow
#

server = await bot.fetch_guild(discord_server_id)
This line would return None if I remember correctly

sage tendon
#

if you have a test server, did it happen for that too?

hasty meadow
#

I don't have a test server

sage tendon
#

hm

#

but now fetching works?

#

or still no

hasty meadow
#

yea, but only after I re-added to my server using a new link. And I noticed the creation process was a bit different from last time

sage tendon
#

didnt really change in the past years for all i remember

#

are you sure the bot is installed on your server and not on your account as a user app lol

hasty meadow
#

ok it is possible I don't remember that well

sage tendon
#

can you print bot.guilds

hasty meadow
#

hmm ok it seems like that works and I can run members on the guild from there fine

sage tendon
#

then get guild should work fine as well

hasty meadow
#

yes seems to work

sage tendon
#

then fetch should also work

#

lmao

hasty meadow
#

that works partially, those certain properties of the guild won't be there

#

members, member count, etc

sage tendon
#

no idea then lol
but if get works, use that
you should always use get if possible

hasty meadow
short rivet
#

Why is guild.name being None sometimes in on_guild_remove ?

stoic patio
#

how can i get a bot to be able to detect presence updates without caching ppls activities?

hoary cradle
#

if im importing functions from a different file in my cog and update that file, is it possible to reload my cog including that file?

lofty parcel
hoary cradle
#

yeah that would be one case, or if im updating one of the imports

royal spindle
#

Guys quick help why this name=f"{ctx.author.name}-zestaw" gives me for example @coarse yoke instead of the actual ping @royal spindle

sage tendon
#

ctx.author.mention

royal spindle
#

same

#

*sometimes works

sage tendon
#

screenshot

royal spindle
#

but sometimes it gaves me just the id instead of the ping

sage tendon
#

show your code and what you see in discord

royal spindle
#

embed = discord.Embed( title="abc", description=f"Results for {ctx.author.mention}", color=discord.Color.green() )

sage tendon
#

that's normal

#

pings in embeds don't fetch the user

#

so if your discord doesn't have that user in cache it won't show the ping properly

#

the only workaround is to ping the user in the message content

royal spindle
#

Is it possible to make it show the nickname without ping? like "results for Kaygoo"

sage tendon
#

ctx.author.display_name

royal spindle
#

ok im trying

#

works

stoic patio
#

how do i turn it off

sage tendon
#

turn what off

stoic patio
#

discord caching user activities

#

i saw that stuff in the objgraph.show_growth() output

errant trout
#

there is no fine-tuned cache

round heart
#

Dumb question - how can you use once for cog listeners?
My listeners are done with @commands.Cog.listener(), and would want my on_ready method to just fire once.

sage tendon
#

isnt it just once=True ?

round heart
sage tendon
#

kwargs can't be suggested automatically

round heart
#

No, but I wasn't seeing it at first even when trying it. It just needed a little persuasion is all

deft kestrel
#

why its giving None?

for command in self.bot.walk_application_commands():
            print(command.id, command.qualified_name, command.description)

output:
None setup antilink the antilink Logs
None setup autorole The autorole system
None setup feedback-costumer the feedback system
None setup giveaway the giveaway system
None setup logs every thing for you that related to logs
None setup ticket Ticket menu
None setup verify_v2 the verify v2 system
None setup welcome-v2 sets up the welcome message

sage tendon
#

im surprised it doesnt fail you completely and instead returns None

deft kestrel
deft kestrel
#

for everything or to make an if?

sage tendon
#

everything

deft kestrel
#

ok

sage tendon
#

the problem is that you're trying to print the IDs of subcommands
and subcommands arent commands by themselves

#

so qualified_id will print the ID of the parent command as described in its documentation

deft kestrel
#

ok got it

sage tendon
#

on a low level, subcommands are considered options for the parent command

short rivet
#

in on_member_remove why am i getting member.guild None sometimes and sometimes member.guild.me as None

sage tendon
#

any pattern as to when you get None for both?

short rivet
#

idk i am having this problem at multiple places in multiple events

#

another event being on_wbhooks_update i get the channel and from the channel i get channel.guild and use the guild.audit_logs iterator and start getting Unkown guild

deft kestrel
sage tendon
#

command.mention

sage tendon
deft kestrel
#

ok

short rivet
#

Traceback (most recent call last):
File "C:\Users\iyadf\Downloads\mekov1\venv\Lib\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "C:\Users\iyadf\Downloads\mekov1\PrefixCommands\Logging\LoggingEvents\MemberLogs\UserLeft.py", line 18, in on_member_remove
if not guild.me.guild_permissions.view_audit_log:
^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'guild_permissions'

#

this is the traceback

deft kestrel
sage tendon
#

gives the bot's member object in a guild

short rivet
#

is it maybe because these events fire in the time when there is a resume and py-cord doesnt get stuff from the cache properly or something ?

sage tendon
#

wdym where there is a resume

short rivet
sage tendon
#

oh god shards

#

yea no idea what that means

short rivet
fresh sierra
#

so you need to itinerate through it using for example subcommand for command.subcommands and then do subcommand.id

sage tendon
#

luma, we already solved this

fresh sierra
sage tendon
#

subcommands dont have ids for all i know

#

because they count as options

fresh sierra
#

maybe i will double check

#

cos if they dont that a new thing that i will learn

#

ok so it work like so
</name of subcommand:id of group>

#

good to know thanks

sage tendon
#

yes

#

i think sub groups do count as their own commands though

sage tendon
#

wat

fresh sierra
#

group / subgroup are not considered as command

#

wrong screen

#

wait

sage tendon
#

but the group is a command

#

lol

fresh sierra
#

i mean it will still all refere to the same thing

#

i might have not understand ur first sentence

#

if you prefere all of those are considered as options of the first one for what i understand

sage tendon
ebon swift
#

how can I get a role id from its str value ?

sage tendon
#

what do you mean?

ebon swift
#

something like roleid = ctx.guild.get_role_id_from_name("Admin role")

sage tendon
#

first of all, why do you only have the name?

ebon swift
#

cause and error returned it to me ^^"

sage tendon
#

show the code then

ebon swift
#

I'm sorry you must hate me sm rn ^^"

@discord.Cog.listener()
    async def on_application_command_error(self, ctx, error):
        message_beginning = f"An error occurred while executing the command {ctx.command}."
        match type(error):
            case commands.MissingRole:
                rolename = error.missing_role
                role_id = ctx.guild.???????
                await ctx.respond(f"You don't have the required role <@{role_id}> to execute this command and "
                                  f"shouldn't be able to see it. Please contact an admin.")
                self.bot.logger.error(
                    f"{message_beginning} - MissingRole: {error} for {ctx.author}, that shouldn't happen check the "
                    f"integration settings and make sure this command is only visible to the right role.")
            case _:
                await ctx.respond("An error occurred while executing the command.Please contact an admin.")
                self.bot.logger.error(f"{message_beginning} - Error: {type(error)}")
sage tendon
#

no, why lol

#

MissingRole exceptions have a .missing_role attribute

ebon swift
#

hoooo the union ! so I should use missing_role[1] !

sage tendon
#

no

#

missing_role

ebon swift
#

missing_role returns the str of the role not the id

lofty parcel
#

Why do you even wanna mention the role

#

Just use the name

fresh sierra
#

if you have only the name u can use the discord.utils.get

ebon swift
#

you're right I might mention people that would rather sleep ^^

But I'm still curious if there is a way for me to mention the role from it's name

fresh sierra
ebon swift
#

hoooo can you please give me a link to the doc ? or explain a little more ?

sage tendon
fresh sierra
#

using that

sage tendon
#

You shouldn't use has_role() anyway unless you use prefix commands only

ebon swift
ebon swift
#

I was able to did it it works perfectly thank you all

flint talon
#

hi

#

throwing error

#

missing perms

#

I have all the intents and role hierachy set right

#

when i timeout it keeps saying missing permissinos

#

and im owner

#

and im not timeouting myself

stoic patio
#

maybe the bot doesn't have perms to do wtv?

rancid arrow
#

Check if the bot has the explicit permission β€œtimeout members”

flint talon
#

I fixed it

#

so apparently I can't timeout administrators...

#

but hey!

#

new problem to solve

#

get this error:
Error: 'str' object has no attribute 'to_dict'

edgy nest
#

code?

flint talon
#

newembed.add_field(name = "Server ID", value = f"{serverid}")
newembed.add_field(name = "Creation date", value = f"{createdate}")
newembed.add_field(name = "Owner", value = f"{owner}")
newembed.add_field(name = "Member Count", value = f"{membercount}")
newembed.add_field(name = "Channel Count", value = f"{channelcount}")

edgy nest
#

traceback?

flint talon
#

sorry little late

#

hold up gimme a sec

edgy nest
#

no problem

flint talon
#

wait sorry this will take 1 minute

#

its not giving me a traceback

edgy nest
#

i'm assuming you made a custom error handler?

flint talon
#

yeah

#

I did

edgy nest
#

can you remove it or have it print out the traceback

flint talon
#

how can i print out traceback

#

?

edgy nest
#

one sec

#
tb = "".join(
    traceback.format_exception(type(error), error, error.__traceback__)
)
#

make sure you add import traceback

flint talon
#

running now

#

not printing

#

ughh

#

@edgy nest

#

I'm going to delte custom error handling

edgy nest
flint talon
edgy nest
#

Β―_(ツ)_/Β―

flint talon
#

now it's just straight up not giving me an error

#

@bot.command()
async def serverinfo(ctx):

membercount = discord.Guild.member_count
channelcount = discord.Guild.channels
createdate = discord.Guild.created_at
owner = discord.Guild.owner
rolenum = discord.Guild.roles
icon = discord.Guild.icon
serverid = ctx.guild.id


newembed = discord.Embed()
newembed.color = 880808
newembed.timestamp = datetime.datetime.now()
newembed._thumbnail = icon
newembed.add_field(name = "Server ID", value = f"{serverid}")
newembed.add_field(name = "Creation date", value = f"{createdate}")
newembed.add_field(name = "Owner", value = f"{owner}")
newembed.add_field(name = "Member Count", value = f"{membercount}")
newembed.add_field(name = "Channel Count", value = f"{channelcount}")

await ctx.send(embed = newembed)
edgy nest
#

oh goodness

flint talon
#

yeah

edgy nest
#

alright well this is your problem line

#

newembed._thumbnail = icon

#

embed has set_thumbnail

flint talon
#

omg

edgy nest
#

but also you can't use discord.Guild like that

#

you should be referring to ctx.guild

flint talon
#

for all of them?

edgy nest
#

yeah

flint talon
#

ok lets see

#

what it gives us

#

literally

#

nothing

edgy nest
#

i think

#

your error handling is fucked somehow

flint talon
#

it just wont throw an error

#

wtf python

edgy nest
#

but you can have it send the traceback in discord

flint talon
#

how to do that

edgy nest
flint talon
#

i did await ctx.send but it don't send tracepback with it

edgy nest
flint talon
#

ok lemme try

#

ok we r about to see

#

YES YES YES

#

Traceback (most recent call last):
File "c:\Users\NishanPC\Desktop\vscodeprojects\pythonbot2\main.py", line 158, in serverinfo
membercount = ctx.Guild.member_count
^^^^^^^^^
AttributeError: 'Context' object has no attribute 'Guild'. Did you mean: 'guild'?

edgy nest
#

lowercase g

#

(it even tells you!)

flint talon
#

ik

#

aight we about to see

#

Traceback (most recent call last):
File "c:\Users\NishanPC\Desktop\vscodeprojects\pythonbot2\main.py", line 170, in serverinfo
newembed.set_thumbnail = icon
^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'Embed' object attribute 'set_thumbnail' is read-only

#

tf

edgy nest
#

it's a method

#

not an attribute

flint talon
#

so how can I set the thumbnail

rugged lodgeBOT
#
Sets the thumbnail for the embed content.

This function returns the class instance to allow for fluent-style
chaining.

.. versionchanged:: 1.4
    Passing `None` removes the thumbnail.

Parameters
----------
url: :class:`str`
    The source URL for the thumbnail. Only HTTP(S) is supported.```
edgy nest
#

set_thumbnail(url=...)

#

do note though that icon can be None, but if it's an asset you will need to use icon.url

flint talon
#

sounds good

#

do i await it

edgy nest
#

no

#

it is a normal method

flint talon
#

wait im confused

#

whats the path

#

like blah.blah.set_thumbnail()

edgy nest
#

your embed.set_thumbnail

flint talon
#

mb i just saw on the docs

edgy nest
#

same thing as your add_fields

rugged lodgeBOT
flint talon
#

it has to be a url huh

edgy nest
#

yes

flint talon
#

how can i get pfp url

shell radish
#

user.avatar.url

flint talon
edgy nest
#

which you can then use icon.url with since it's an Asset

flint talon
#

running rn

#

Traceback (most recent call last):
File "c:\Users\NishanPC\Desktop\vscodeprojects\pythonbot2\main.py", line 169, in serverinfo
newembed.set_thumbnail = ctx.guild.icon
^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'Embed' object attribute 'set_thumbnail' is read-only

shell radish
#

it's a method...

fresh sierra
#

is there something im missing ?

sage tendon
#

that's not how subcommands work

edgy nest
sage tendon
#

Oki sorry :3

fresh sierra
#

i think it can be because the cache is not updated at this time or something else

sage tendon
#

if your bot doesn't have it's own commands cached I'd be worried

#

what happens if you just get the command group

fresh sierra
#

and depends sometime it works and other time it return Noen

deft kestrel
#

there's any example of how to use SKU's? I want when a user buy something the bot send a DM to him with "hi"

vague plaza
#

can I use HTML as a formatting option for sending messages from my bot?

red mist
echo wraith
#

you can use embeds tho

#

and markdown

#

yeah

vague plaza
vague plaza
red mist
#

@vague plaza

red mist
red mist
#

Ah- so actual buying using apps

deft kestrel
#

yep

red mist
#

Uff ok hold on gotta fill myself in-

#

Ah- ok so apparently you can introduce webhook logic by adding a webhook to your application via the discord dev portal

#

But then you'll also need to handle the webhook events so you should create a webserver like fladk

#

*flask

#

So pretty much discord makes a webhook requests once somebody buys something on your SKU- which you can then handle on your flask web server to then trigger a bot event to dm the user

#

user purchase information should be passed trough the webhook

#

(I am not certain of this in any way tho as I have not tested any of this myself)

#

@deft kestrel

red mist
#

I think so im not sure scrolling trough docs and guides rn but having a hard time-

sage tendon
#

pretty sure that'd break your bot

red mist
#

well if it actually switches everything over then yes πŸ’€

deft kestrel
sage tendon
#

you can fetch the bot's current skus

#

I'm not sure if that's the only way or if there's an event, but if nothing else works, you can fetch them like once a minute and check for changes

red mist
#

Best I could find

#

But I don't think that does anything

#

Towards your needs

sage tendon
#

oh yea entitlements

#

I'm not sure if SKUs and entitlements are the same or how they're connected, that's beyond what I know lol

red mist
stoic patio
#

do objects still get saved in memory when a discord bot disconnects before resuming a session? (thinking of on_resume)

sage tendon
#

no

errant trout
edgy nest
#

an entitlement grants access to an sku

sage tendon
#

confusing+

edgy nest
#

not really

#

but ok

#

an entitlement just says that you're entitled to an sku

viscid depot
#

Hi! Is it possible to use emojis in the strings returned for the autocomplete?

sage tendon
#

no

viscid depot
#

Ok. Thanks for the on reply!

shell radish
sage tendon
#

"stock keeping unit" is a dumb af name

edgy nest
#

industry standard

stoic patio
#

is it normal for these kinds of objects to linger in memory

shell radish
#

yeah, because member cache

stoic patio
#

how about things like timerhandle, ordereddict, list, etc

#

(i'm using asyncpg as well)

shell radish
#

list could be anything

#

Β―_(ツ)_/Β―

edgy nest
#

probably parts of cache

#

members have role lists attached to them

#

channels have permissions

#

this and that

stoic patio
#

i see

stoic patio
shell radish
#

because there's other lists that are snowflakes like guilds and channels

edgy nest
#

Β―_(ツ)_/Β―

stoic patio
shell radish
#

maybe they just don't have roles

stoic patio
#

so if they don't have roles they just don't have a role list attached to them at all, rather than a []?

shell radish
#

list is different from SnowflakeList

#

and i have no idea how SnowflakeList works

stoic patio
#

lol

#

i have a feeling that asyncpg may be leaky

#

for some reason

shell radish
#

is memory an issue for you?

stoic patio
#

yes

#

i'm noticing that my memory usage is increasing gradually

#

by an average of about 2-3 mb an hour

#

according to pm2

shell radish
#

that's like normal

stoic patio
#

how

#

and the thing is, my bot's running on an ec2 free tier with 1gb ram, and the thing goes offline about once per week as a result of the memory growth

#

it's being used by 7.5k users, not including bots

shell radish
#

oh so it doesnt go down. I see

stoic patio
#

it doesn't

stoic patio
edgy nest
#

easiest solution is disabling member cache

stoic patio
#

can't

#

my bot needs to be able to access members

#

and fetching them all the time isn't exactly an option

edgy nest
stoic patio
#

for example, it has a ban command

#

i tried running it with member cache disabled

#

didn't work

edgy nest
#

if it's a slash command you should recieve the full member object as a parameter

#

if not you can query/fetch members by name

stoic patio
#

it is

edgy nest
# stoic patio it is

so it should provide a full member (or at least a user) object for your parameter

#

if not a member, you can use guild.ban with a discord.Object

stoic patio
#

and i assume i disable member cache using discord.membercacheflags.none()?

edgy nest
#

yup

#

you can also disable guild chunking too

#

fetches member lists

#

though if you're running a moderation bot, and you have logging cache is probably better off enabled

stoic patio
#

yes that's waht i'm doing

stoic patio
edgy nest
#

your error logging is broken then

stoic patio
#

oh wait i do get an error

#

it's Application Command raised an exception: AttributeError: 'NoneType' object has no attribute 'id'

maiden bloom
#

I'm not using the delete() method for any messages yet I'm getting the error below on v2.5.1. I do use the delete_after argument when sending some messages through. Is this a known bug or do I need to handle it somehow?

2024-07-28 02:19:25,891:ERROR:asyncio: Task exception was never retrieved
future: <Task finished name='Task-2540795' coro=<Webhook.send.<locals>.delete() done, defined at /usr/local/lib/python3.10/site-packages/discord/webhook/async_.py:1799> exception=NotFound('404 Not Found (error code: 10008): Unknown Message')>
Traceback (most recent call last):
  File "/usr/local/lib/python3.10/site-packages/discord/webhook/async_.py", line 1801, in delete
    await msg.delete()
  File "/usr/local/lib/python3.10/site-packages/discord/webhook/async_.py", line 967, in delete
    await self._state._webhook.delete_message(self.id, thread_id=thread_id)
  File "/usr/local/lib/python3.10/site-packages/discord/webhook/async_.py", line 2030, in delete_message
    await adapter.delete_webhook_message(
  File "/usr/local/lib/python3.10/site-packages/discord/webhook/async_.py", line 220, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10008): Unknown Message
weary meteor
#

how does one tag a category

sage tendon
#

not possible

scenic crescent
#

The way importing and creating slash commands in cogs has changed or is it still the same way?
Having a bot running with py-cord version 2.4.1 that uses the import from discord.commands import slash_command but the example https://github.com/Pycord-Development/pycord/blob/master/examples/app_commands/slash_cog.py shows how to import it with from discord.ext import commands and using it with @commands.slash_command()
Dont see in changelog that this behaiviour has changed

sage tendon
#

just use @discord.slash_command()

#

behavior didnt change, there just many ways to import the same thing in pycord

red mist
#

#1017401122031419463 β†’ #1017401122031419463

stoic patio
sage tendon
#

because you disabled member cache

#

so you don't have the guild owner cached

stoic patio
#

but the members themselves are not none

sage tendon
#

You mean ones passed via options?

stoic patio
#

member1 is ctx.author, member2 is the one passed

sage tendon
#

I mean yea, you were already told member objects passed via options work even without cache of course

#

but guild.member just isn't cached and not explicitly passed either

#

disabling (member) cache is simply a pain you should try to avoid

#

and you said you were running on a free vps with 1GB right?
maybe with 7k+ members you should consider renting an actual VPS with more ram instead of trying to get around it with brute force

stoic patio
#

i see

#

i'll have to convince my dad to do it (i'm almost 17)

sage tendon
#

oracle has a free vps tier with like 4GB or more of ram
but you need a credit card to sign up

echo wraith
#

what is the listener to catch exceptions in views / other interactions?

#

on_error dosen't seem to do the job

sage tendon
#

dont ever use Bot.on_error

echo wraith
echo wraith
#

feels wierd imo but fair enough

sage tendon
sage tendon
#

just dont use it, there's no point

echo wraith
#

@Cog.listener ?

sage tendon
#

you cant listen to on_error :)

#

read the docs

echo wraith
#

thanks

upper flint
#

I'm using bot.walk_application_commands() iterator that iterates over all bot commands. How can I differenciate between an actual command and command group? e.g I have math group and 2 commands in it: add and subtract. Iterator will walk through 3 commands: math add, math subtract and math

flint talon
#

so I have a command for timing someone out

#

The command is ?timeout (days int) (hours int) (minutes) username

#

so a command could look like

#

?timeout 5 0 0 billybobjoe

#

but what happens is

#

If I don't set the timeout to some obscenely large value

#

it won't timeout the user

#

so if I set it for like 20 mins

#

nothing happens

#

try:
target = member
duration = datetime.datetime.now()
time_delta = timedelta(days = days, hours = hours, minutes = minutes)
timeout_until = duration + time_delta
timeout_until = timeout_until.
replace(tzinfo=datetime.timezone.utc)
print(str(timeout_until))

        await target.timeout(timeout_until, reason = f"Ordered by {ctx.author}")
        await ctx.send(f"β˜‘οΈ {target} was timed out for {days} days, {hours} hours, {minutes}, minutes")

except Exception as e:
await ctx.send(f"Error: {e}")

deft kestrel
sage tendon
#

no clue

lofty parcel
#

.rtfm fetch_entitlements

sly karmaBOT
#

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

lofty parcel
#

Well its called that. Bot method.

#

You also got events for creation, update and deletion.

#

And you also receive the entitlements data on each interaction.

deft kestrel
#

how to "consume" a SKU? because if i want buy much products in the store like 2/3 subscriptions what i can do?

shell radish
#

A consumable is like buying coins. You bought 100 coins and you get it in your profile

edgy nest
#

Or an item you can use

errant trout
#

groups are SlashCommandGroup

upper flint
errant trout
#

that is correct

#

SlashCommandGroup is also a subclass of ApplicationCommand

upper flint
#

Oh, so that's why.. Now I know

#

Thanks =)

normal iris
#

Hi got a small question. When calling discord.VoiceClient.play i can define with the after= parameter a finalizer function. Usually this finalizer function only receives an error parameter from the play function. Is there a way to pass more than just the error parameter to the finalizer function without using global vars, for example the ctx?

stoic patio
#

overall, how frequent are username changes on discord? cuz my member cache is disabled but sometimes i need to get a member object from a user object when username changes for every mutual guild, what's the best way to do it?

sage tendon
#

fetch the member in the guild

stoic patio
#

so they're infrequent enough that you can do that?

sage tendon
#

..what

#

guild.fetch_member(id)

stoic patio
#

i know, but that's an api call

#

and those have ratelimits

sage tendon
#

you have cache disabled

#

you have to do API calls

stoic patio
#

so there is literally no way around it right

sage tendon
#

No

#

I told you, disabling cache will get you into a world of pain

stoic patio
#

true

#

but ever since i disabled member cache, my memory's been pretty stable

ebon swift
#

Hey I learned that giving guild_ids to my functions would help with discord syncing. I had a question is there any way for me to make an environement variable that will be passed to the 'guild_id' parameter or not ?

shell radish
ebon swift
#

it may be a short comprehension , but while develloping i found my commands to appear quicker if i gave a guild_id

shell radish
#

that was true 4 years ago

red mist
#

if you give a guild it just makes the commands sync to a specific guild

#

But it doesn't mean your commands sync quicker as usually it would sync to all guilds

#

Now it'll still be shitty on all other guilds except the one in the guild_ids

#

And it would still need to resync and take a lot of time when syncing to all guilds once you're done testing on your guild_ids

ebon swift
#

ok thank you

sage tendon
#

as always, restart discord when changing any command metadata

edgy nest
#

press ctrl+r

ebon swift
#

ho didn't knew it'd work with ctrl+r

#

thank you

ebon swift
#

is it possible to register the same command name with multiple input types ?

/choose_color <red> <green> <blue>
/choose_color <hex_color>
/choose_color <color_name_list
lofty parcel
#

No

#

Application command names must be unique.

ebon swift
#

okay thank you !

warm linden
#

hey is there any reason why my prefixed commands are running twice, my slash commands are normal - there's no duplicated on_message events and the cogs are only being loaded once

lofty parcel
rotund quarry
#

Very quick question, is more efficent to make a bridge insted of copy paste?

sage tendon
#

obviously

ebon swift
#

hey all how to you make a respond private ?

echo wraith
ebon swift
#

ho ok thank you I'll read it in the doc , I couldn't find it

ebon swift
#

thank you

upbeat lintel
#

Hi,
Let's say I've got a user who boosted my server and received the booster role. Gave them a reward by using the on_member_update listener. I'd like to give them another reward for the second boost. Any way I could do that? Booster role isn't given to the user twice, so which event listener should I use? OR is there a boost counter somewhere available?

edgy nest
upbeat lintel
#

Hmm... right, I'll do that. Thank you!

sage tendon
#

that ofc requires those to be enabled

#

isnt the case on all servers, if your bot is public

upbeat lintel
#

Isn't public yet, but will be. Is there a shortcut to retrieve the channel these messages get sent to?

sage tendon
#

docs save lives :)

upbeat lintel
#

Thank youu

deft kestrel
#

@sage tendon

[2024-07-29 08:25:38] [INFO] >> Loading cogs...
[2024-07-29 08:25:38] [INFO] >> Loaded cog: cogs.misc_cog
[2024-07-29 08:25:38] [INFO] >> Loaded cog: cogs.economy_cog
[2024-07-29 08:25:38] [INFO] >> Loaded cog: cogs.moderation_cog
[2024-07-29 08:25:38] [INFO] >> Loaded cog: cogs.administration_cog
[2024-07-29 08:25:38] [INFO] >> Loaded cog: cogs.staffapps_cog
[2024-07-29 08:25:38] [ERROR] >> Failed to load cog cogs.gamble_cog: Extension 'cogs.gamble_cog' raised an error: TypeError: Invalid class <class 'NoneType'> used as an input type for an Option
Traceback (most recent call last):
  File "/home/container/.local/lib/python3.10/site-packages/discord/cog.py", line 784, in _load_from_module_spec
    spec.loader.exec_module(lib)  # type: ignore
  File "<frozen importlib._bootstrap_external>", line 883, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "/home/container/cogs/gamble_cog.py", line 12, in <module>
    class Gamble(commands.Cog):
  File "/home/container/cogs/gamble_cog.py", line 561, in Gamble
    async def coinflipbet(
  File "/home/container/.local/lib/python3.10/site-packages/discord/commands/options.py", line 438, in decorator
    func.__annotations__[resolved_name] = Option(itype, name=name, **kwargs)
  File "/home/container/.local/lib/python3.10/site-packages/discord/commands/options.py", line 243, in __init__
    raise exc
  File "/home/container/.local/lib/python3.10/site-packages/discord/commands/options.py", line 238, in __init__
    self.input_type = SlashCommandOptionType.from_datatype(input_type)
  File "/home/container/.local/lib/python3.10/site-packages/discord/enums.py", line 810, in from_datatype
    return cls.from_datatype(datatype.__args__)  # type: ignore
  File "/home/container/.local/lib/python3.10/site-packages/discord/enums.py", line 795, in from_datatype
    datatypes = [cls.from_datatype(op) for op in datatype]
  File "/home/container/.local/lib/python3.10/site-packages/discord/enums.py", line 795, in <listcomp>
    datatypes = [cls.from_datatype(op) for op in datatype]
  File "/home/container/.local/lib/python3.10/site-packages/discord/enums.py", line 852, in from_datatype
    raise TypeError(
TypeError: Invalid class <class 'NoneType'> used as an input type for an Option

The above exception was the direct cause of the following exception:
Traceback (most recent call last):
  File "/home/container/bot.py", line 86, in <module>
    raise e
  File "/home/container/bot.py", line 82, in <module>
    bot.load_extension(cog_path)
  File "/home/container/.local/lib/python3.10/site-packages/discord/cog.py", line 918, in load_extension
    self._load_from_module_spec(spec, name)
  File "/home/container/.local/lib/python3.10/site-packages/discord/cog.py", line 787, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.errors.ExtensionFailed: Extension 'cogs.gamble_cog' raised an error: TypeError: Invalid class <class 'NoneType'> used as an input type for an Option```
#

mind helping?

#

i literally have no clue why its doing this

sage tendon
#

holy balls

deft kestrel
#
    @option(
        "choice", description="Choose 'Heads' or 'Tails'.", choices=["Heads", "Tails"]
    )
    @option(
        "challenger",
        description="Challenge another user to a coin flip bet.",
        required=False,
    )
    async def coinflipbet(
            self,
            ctx: ApplicationContext,
            bet_amount: int,
            choice: str,
            challenger: discord.Member = None,
    ):```
#

its just that

#

it worked yesterday and no commits have been made

sage tendon
#

try explicitly setting str as input type for both options

stoic patio
#

how do i prevent thread members from being cached

#

membercacheflags is set to none

sage tendon
#

dude stop disabling each and every cache ever

#

please just get a VPS lol

stoic patio
#

i've only disabled member cache

deft kestrel
#

thanks i guess lol

#

idk where the fuck that came from

sage tendon
#

if i had to guess, discord API update

deft kestrel
#

waking up with 400 errors and a down bot is NEVER a good thing 😭 πŸ™

deft kestrel
sage tendon
#

are you on 2.5.0?

#

or master

deft kestrel
#

whatever is the latest on pop

#

pip

sage tendon
#

very weird

#

yea i can really only imagine a discord api update then, or rather, discord api bug

deft kestrel
#

is there a way to make it so if a cog crashes instead of the ENTIRE bot killing itself it will post in my staff chat and then keep the bot up but disable the cog

echo wraith
deft kestrel
#

or is that not possible

#

i would assume id need to run in a seperate thread or sum

sage tendon
echo wraith
#

that's my point

echo wraith
#

the id is set not the channel object

sage tendon
deft kestrel
sage tendon
#

yes.

echo wraith
#

There must be a bug then

#

the guild's .system_channel was none but not the id

sage tendon
lofty parcel
deft kestrel
#

that would be hella convienient

echo wraith
deft kestrel
#

cuz this literally happened overnight and i do have error handling for when they load and in every command

edgy nest
sage tendon
#

also, @stoic patio, can i ask why you are hosting on like the most expensive service possible when you're clearly budget-restrained?

lofty parcel
# deft kestrel does it?

It is store.
If True returns a dict with all the errors, if False it just raises the exception and closes the bot.