#Basic Pycord Help

1 messages · Page 43 of 1

fresh sierra
#

Especially if u use a GitHub

little cobalt
#

I dont really use GitHug

fresh sierra
#

but a config.py like you can set variable and remove that file

#

so you havbe to keep ur token inside so not really secured

dense isle
#

how to add flag emoji to SelectOption
with country code (us,gb)

filter_value = country code
dislay value = country name

dense isle
#

how can i turn filter_value to the emoji

#

or use like flag_x

fresh sierra
#

🇺🇸

#

i dont really understand ur issue im sorry

dense isle
#

got a list of countries right

#

its wider that that

#

and i just want to add the countries emoji next to the option

#

got it its fine

little cobalt
#

keep in mind that the limit is 25 for a string select

dense isle
#

yeah looked that up

#

had to just add the top 25 countries i guess

#

maybe got users from max 5 of those

#

thanks anyway guys

jagged ledge
#

Hi! Sorry to bother.```py
query("INSERT INTO strife (name, clouder, ID) VALUES (%s, %s, %s)", (name, clouderID, strifeID))

I'm trying to get this statement to work. However, I keep getting this error (passing in `('dfshfk', 315220045141770241, 'd35f21')`):```
Could not process parameters: str(dfshfk), it must be of type list, tuple or dict

What could it mean? I've tried making tuples out of different elements but i can't figure it out

#

For reference, these statements still work:```py
query("SELECT * FROM strife WHERE name = %s AND clouder = %s", (name, clouderID))

query("SELECT * FROM `strife` WHERE `name` = %s", (name))
```
sage tendon
#

That isn't py-cord related, you'd be better off in the python support server

jagged ledge
#

My bad, thank you

marble hinge
#

#1252187716473327686 help me here pls

red mist
#

Resolved?

rapid jackal
#

Hi there. I have a problem that my code runs multiple times, but there are only two messages in the channel:

    async def fetch_messages(sellf, channel):
        return [message async for message in channel.history()]

    @commands.Cog.listener()
    async def on_ready(self):
        on_ran = False
        with open('json/bot.json', 'r') as f:
            data = json.load(f)

        if not on_ran:

            channel_id = data["marketplace_channel"]
            channel = self.bot.get_channel(channel_id)

            messages = await self.fetch_messages(channel)

            for message in messages:
                for embed in message.embeds:
                    title = embed.title
                    print(f"Embed Title: {title}")

                for component in message.components:
                    for button in component.children:
                        print(f"Button Label: {button.label}")
                        print(f"Button ID: {button.custom_id}")

            on_ran = True

This is my code. instead of 6 prints the bot prints them over and over again. Why is that?

fresh sierra
#

and like at infinity ? or only a number of time

#

because channel.history also show some message that u cant really see like defer (and maybe ephemeral but im not sure)

rapid jackal
#

Yes, but only a über of times

#
Button Label: Mehr Informationen
Button ID: buy_player-Fritz_jigl
Embed Title: :gloves: |⭐️ alm do ⭐️
Button Label: Mehr Informationen
Button ID: buy_player-alm_do
Embed Title: :crossed_swords: |⭐️ Fritz jigl ⭐️
Button Label: Mehr Informationen
Button ID: buy_player-Fritz_jigl
Embed Title: :rm: |⭐️ ani kaki ⭐️
Button Label: Mehr Informationen
Button ID: buy_player-ani_kaki
Embed Title: :crossed_swords: |⭐️ Fritz jigl ⭐️
Button Label: Mehr Informationen
Button ID: buy_player-Fritz_jigl
Embed Title: Schicke das Bild des Spielers
Embed Title: :gloves: |⭐️ alm do ⭐️
Button Label: Mehr Informationen
Button ID: buy_player-alm_do
Embed Title: :gloves: |⭐️ alm do ⭐️
Button Label: Mehr Informationen
Button ID: buy_player-alm_do
Embed Title: :crossed_swords: |⭐️ Fritz jigl ⭐️
Button Label: Mehr Informationen
Button ID: buy_player-Fritz_jigl
Embed Title: :crossed_swords: |⭐️ Fritz jigl ⭐️
Button Label: Mehr Informationen
Button ID: buy_player-Fritz_jigl

this is a part of the prints

fresh sierra
rapid jackal
#

no, only one time

rapid jackal
#

solved the problem. I just restarted discord and resettet the config state of my bot

#

But I have another problem. I am trying to make my view persistent.

this how the head of my view looks like:

class SendPlayerView(discord.ui.View):
    def __init__(self, vorname, nachname):
        super().__init__(timeout=None)
        self.vorname = vorname
        self.nachname = nachname
        self.send_player_callback.custom_id = self.generate_card_custom_id()

    def generate_card_custom_id(self):
        return f'buy_player-{self.vorname}_{self.nachname}'

    @discord.ui.button(label='Mehr Informationen', style=discord.ButtonStyle.green, emoji='🛒')
    async def send_player_callback(self, button, interaction):

the view has only one button, the timeout is set to none and the button has a custom_id, but I still get this error:

ValueError: View is not persistent. Items need to have a custom_id set and View must have no timeout

Is it because of the way how I set the custom Id?

rapid jackal
#

but then I can't pass a function. I can't do custom_id=generate_card_custom_id

shell radish
#

That’s not how persistent views work

rapid jackal
#

wdym?

shell radish
#

pycord will only use the custom ids that were added to the bot. Any other will not work

rapid jackal
#

only when they are in here: @discord.ui.button(label='Mehr Informationen', style=discord.ButtonStyle.green)?

fresh sierra
#

.tag persistent

sly karmaBOT
#

The Issue

When you send a message with a view, button for example
if your bot restarts, you will lose the ability to use this button.

How To Fix This

  1. Set your view timeout to None
  • By default, the view timeout value is set to 300 seconds
  1. Pass a custom_id value to the view
  • Custom ids must be unique
  • Chose a custom id that has a meaning in relation to your view
  1. Add the view to the bot
  • You can use the method Bot.add_view(YourViewClass())
  • Make sure to add the view when the bot begin ready
rapid jackal
#

I know that, but I need parts of the class parameters in my custom id

#

I need the custom ID have this format buy_player-{self.vorname}_{self.nachname}

#

but that I can't do where I need to set the custom_id for the persistent

rapid jackal
#

Unresolved reference 'self'

fresh sierra
#

Dont use the decorztir

#

Decorztor

#

Decorator

rapid jackal
#

how should I do it then?

fresh sierra
#

button = discord.ui.Button()
button.callback = self.callback
self.add_item(button)

rapid jackal
#

sorry, but I don't understand what you mean

fresh sierra
#

Do like that

rapid jackal
#

in the init of the view?

fresh sierra
#

class Backup_Config_View(discord.ui.View):
def init(self, bot):
super().init(timeout=None)
self.bot: Lumabot = bot
button = discord.ui.Button(emoji="✅", style=discord.ButtonStyle.green, custom_id=)
button.callback = self.button_callback
self.add_item(button)

async def button_callback(self, interaction: discord.Interaction):
#

I can’t do better on phone

#

You will need to do that according to ur code it’s just for u to understand a little bit

rapid jackal
#

yeah, now I understand

lost ocean
#

anyone know how to get an animated banner on my bot? ive seen a lot of vids that use js but none with python as of now

fresh sierra
fresh sierra
#

in the edit

#

bot.edit(banner=...)

lost ocean
#

alr

fresh sierra
#

using the master yes

#

is that possible to typehint that without using option or Option ?
async def load(self, ctx: LumabotContext, backup_id: discord.Autocomplete):

sage tendon
#

wdym typehint that

#

what
no lol

fresh sierra
#

well after thinking yeah it make no sense at all, what i was meaning it do autocomplete(funct)

#

but i will have to use option or Option

#

anyone has an autocomplete example ?

sage tendon
#

for item in list
if item.startswith(userinput)
output.append(item)

#

its literally that simple for a dumb, non fuzzy search

fresh sierra
#

like it choose 1/1298U8U389/20 jun 2024
it will then choose 1

sage tendon
#

what

#

you can read the other selected options within an autocompletecontext if you mean that

fresh sierra
#

so

#

when the user will select an option in the autocomplete, i want it return something else

#

f"{backup['id']}|{backup['guild_id']}|{formatted_time}"

so this will appear in the autocomplee

#

but i want only to return the backup['id'] as option chosen

sage tendon
#

sure

#

autocomplete takes optionchoices too

fresh sierra
#

how can i do that ?

sage tendon
#

construct optionchoices instead of appending plain strings into your output list

fresh sierra
#
    async def backup_id_autocomplete(ctx: discord.AutocompleteContext):
        suggestions = []
        for backup in result:
            formatted_backup = f"{backup[0]}|{backup[1]}|{formatted_time}"
            if ctx.value.lower() in formatted_backup.lower():
                suggestions.append(formatted_backup)
        
        return suggestions
#

so i should edit this part

#

like the value

sage tendon
#

yea just change the thing you append to your suggestions into an optionchoice with a value and whatever the display value is called

fresh sierra
#

oooooo i will look at that

fresh sierra
#

anyways i will need to make a better func because if the user put a number it not really relevant

#

did that but first doing start_with and then if in

fresh sierra
#

can bot put on the camera / sharescreen ?

lean garnet
#

Hi, how can I check if a member is timed out ?

        if member.timeout is None:
            embed = discord.Embed(
                description=f"**🎯 {member.display_name} n'est pas mute.**",
                color=0xDF013A,
            )
            await ctx.respond(embed=embed)
            return
                
        await member.remove_timeout()

The bot don't return even if the member is not timed out.

lofty parcel
#

.rtfm discord.Member

lean garnet
#

didn't see anything about checking if a member is timed out

fresh sierra
#

But agree that is not the best

#

Why does not call it timeout_until since it’s remove_timeout, timeout everywhere

lofty parcel
#

.rtfm Member.timed_out

sly karmaBOT
lofty parcel
fresh sierra
#

Why put communication_disable_until while everywhere else it’s timeout

warm falcon
#

whoops sorry, not ready to send that yet

#

so this doesn't throw any errors, but it also does not respond with anything. i did read the docs for on_message, but i'm still struggling to figure out why i'm not getting a response.

`import discord
import os
from dotenv import load_dotenv

load_dotenv()
bot = discord.Bot()
intents = discord.Intents.all()

...

@bot.event
async def on_message(message: discord.message):
if message.author == bot.user:
return
trigger = "suck it trebek"
if trigger in message.content:
await message.channel.send("Wonderful.")`

fresh sierra
#

So discord.Bot(intents=

warm falcon
#

ahhh okay, thank you!

#

hmm now i'm getting a typeerror

#

TypeError: intents parameter must be Intent not <class 'builtin_function_or_method'>

fresh sierra
#

intents = discord.Intents.all()
bot = discord.Bot(intents=intents)

warm falcon
#

that was the ticket

#

definitely misunderstood what i needed to pass, thank you!

fresh sierra
#

should be report doc issue also on pycord ?

sage tendon
#

yes

fresh sierra
#

done

fresh sierra
#

does someone has an idea ? at the startup of my bot

limber terrace
#

Try to change the token

#

But cannot tell if its u or discord who is messin up

fresh sierra
#

tried with a complete different seems to not have this

#

i guess the issue come if something is rate limit

#

then when u restart it told u that tasks before got removed

#

and when putting again the other token i got this issue and the cpu raise to 100

#

seems like a known issue

sage tendon
fresh sierra
#

completely change -> other bot

#

reset -> same bot

young sedge
#

can someone take a look at this

lofty parcel
#

You opened a discussion, a thread, and now you're asking here

sage tendon
#

You don't understand, they really want help

young sedge
young sedge
lofty parcel
sage tendon
#

it's not even officially released and you're acting like the world is going down if your issue doesn't get solved yesterday

young sedge
#

🙂

lofty parcel
sage tendon
#

Exactly
that's why I said not released

lapis dock
glossy tide
#

Why I have this error?

Error in TicketsSelector select_callback: 'Webhook' object has no attribute 'defer'

In this code

# Ticket Reason Selector
class TicketsSelector(discord.ui.View):
    def __init__(self, bot):
        super().__init__(timeout=None)
        self.bot = bot

    @discord.ui.select(
        custom_id="reason",
        placeholder="Sélectionnez une raison...",
        options=[
            discord.SelectOption(label="Communication Services", description="Order a Communication Service!", emoji="🌐", value="communication"),
            discord.SelectOption(label="TikTok Services", description="Order a TikTok Service!", emoji="📱", value="tiktok"),
            discord.SelectOption(label="Development Services", description="Order a Development Service!", emoji="💻", value="developpement")
        ])
    async def select_callback(self, select, interaction: discord.Interaction):
        try:
            guild = self.bot.get_guild(guild_id)
            category = self.bot.get_channel(ticket_category_id)

            await interaction.response.defer()

            if "communication" in select.values:
                ticket_channel = await guild.create_text_channel(f"🌐・ticket-{interaction.user.name}", category=category)
            elif "tiktok" in select.values:
                ticket_channel = await guild.create_text_channel(f"📱・ticket-{interaction.user.name}", category=category)
            elif "developpement" in select.values:
                ticket_channel = await guild.create_text_channel(f"💻・ticket-{interaction.user.name}", category=category)

            if ticket_channel:
                await ticket_channel.set_permissions(guild.default_role, view_channel=False)
                await ticket_channel.set_permissions(interaction.user, view_channel=True, send_messages=True)
                await ticket_channel.set_permissions(guild.get_role(ticket_staff_id), view_channel=True, send_messages=True)

                tickets_form = TicketsForm(ticket_channel, self.bot)
                await interaction.response.send_modal(tickets_form)

        except Exception as e:
            print(f"Error in TicketsSelector select_callback: {e}")
fresh sierra
#

Wait

frail basin
#

How would I go about creating double nested slash command groups?
eg. /tournament admin create

rugged lodgeBOT
#

Here's the slash groups example.

frail basin
#

that doesnt have a double nested example

fresh sierra
#

defer actually réponse to the interaction so u can’t do it again

frail basin
fresh sierra
rugged lodgeBOT
#

Here's the slash cog groups example.

fresh sierra
#

in this one

fresh sierra
#

like that’s just not possible

edgy nest
#

then make ticket channels second

fresh sierra
#

i mean his code looks like ir will be less than 3s

#

so just remove the defer should be okay

glossy tide
lapis dock
#

can you show the full traceback

#

I think you can do e.traceback or something in the exception.

#

not 100% sure tho

echo wraith
#

How would I subclass a View to run a specific function every time a button is pressed? Something like on_interaction but for a button in a view.

sage tendon
#

with the button decorator on a function

#

check the guide

echo wraith
# sage tendon check the guide

Yeah no ik that. But the idea is to run that on all interactions with any component of the view, abstracting what component is used.

#

Basically in my peristent view I wanna load some stuff asyncrounously before doing something, and I don't wanna do that in every function for every button

sage tendon
#

then do that in the init

echo wraith
sage tendon
#

asyncio

echo wraith
#

wont that block the event loop?

sage tendon
#

no idea, probably

#

cant you load it where you need the view?

lapis dock
#

2 options, you run the async stuff before making the view and pass the results as arguments or you use

#

.tag rie

sly karmaBOT
#

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

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

sage tendon
#

if not, make an async loader function that is called by the callback(s), unless it was already run before

#

just save it as self.run = True
and if that is true, dont call load() again in a callback

lapis dock
#

or this ^

glossy tide
echo wraith
#

oh well

#

I'll probably make a decorator

lapis dock
echo wraith
#

I was just trying to find a way to write that only once

echo wraith
#

Another question, with persistent views, is a view recreated for every interaction or is the one that is initialized kept forever

lapis dock
#

You initialized it and it is kept alive forever.

echo wraith
#

Ok thanks that's all I need hopefully

faint heath
#

I am currently using pycord version 2.0.0 (<t:1657537200>). Is there any way to find out if updating to the latest version (2.5.0) includes any breaking changes? Thank you.

__init__.py
version_info: VersionInfo = VersionInfo(major=2, minor=0, micro=0, releaselevel="final", serial=0)
lapis dock
#

There should be very few breaking changes but looking through the changelogs will help. Let me check

sage tendon
#

unless you use bridge there are no breaking changes I know of

#

Besides, if pycord adheres to semver, there can't be any breaking changes on minor versions

faint heath
#

I haven't used bridge. If I remember correctly, the only change I made was adding a type to enums.py for StickerFormatType.

echo wraith
faint heath
#

I will check the removed/changed in CHANGELOG.md.
Hope the robot will continue to operate normally after the update.
Thank you.

little cobalt
shell radish
upper flint
#

Do bots need a special intent or permission to display their presence?

#

My friend's bot is active on 4 servers 1 of which doesn't display bot's presence

fresh sierra
#

nope, it’s just discord bug

#

bot can’t display presence of some server en some not in this case

little cobalt
#

So.... I want to try to use logging and dont want to see the token stuff at the file

#

is there a was to remove it?

#

I tried to play with the lvl and if I use WARNING I dont get it anymore

#

but warning is just the wrong one for it

mellow spire
#

when running bot and use any command for the first time it's gives me unknown interaction error

#

but when run the command again it works

little cobalt
mellow spire
little cobalt
#

is the database asyncio?

mellow spire
little cobalt
#

uh

mellow spire
# little cobalt uh

help me
out of 20 times it shows unknow interaction error
and 1 time it runs without any error

fresh totem
#

GMGM!

class subscriptionCommands(commands.Cog):

    subscription = SlashCommandGroup("subscription", "Update Server Subscription Settings", guild_ids=adminServer, default_member_permissions=discord.Permissions(administrator=True))

    @subscription.command()
    async def view(self, ctx: discord.ApplicationContext):
        "View Subscribed Servers"```

I'm using Slash Command Group. Can I lock this set of commands to a specific role?
fresh totem
little cobalt
#

.rie

sly karmaBOT
#

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

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

little cobalt
#

I would use this instead

#

@fresh totem @mellow spire

fresh totem
little cobalt
#

with commands.has_role()

fresh totem
#

gotcha, thanks!

sage tendon
#

@fresh totem better way is to do it inside discord, so it's actually hidden for everyone else

fresh sierra
#

And also if u use in ur code logger.info it will not appear

little cobalt
#

So I gonna write my own logging...

fresh sierra
#

Im doing that since i don’t want info from discord about shard etc and i want my own one from event

little cobalt
#

I just gonna create my own one

fresh sierra
#

I added a custom level higher than info but lower than warning to then get everything about important discord

#

If u create a custom logging and not level else than discord u will not received rate limit info or things like that

lapis dock
#

.rtfm defer

warm falcon
#

what's the best way to wait for a response from a guild member, in the context of a slash command? i see there's client.wait_for, but i don't believe that's what i want for this, right?

fresh sierra
lofty parcel
#

You could also use modals.

warm falcon
#

hmmm

warm falcon
#

for context, i'm writing a jeopardy bot

#

my vision is that the bot asks a question, and then the user has 15 seconds~ to respond with the correct answer

#

but others can answer

#

so it would be looking at every message that replies to the original question

fresh sierra
shell radish
#

the only other way without mci is to either DM the bot or ping the bot with the answer

warm falcon
#

mci?

#

oh, the intent

#

i've already got that enabled

shell radish
#

but it won’t be a valid use case for the intent so it will be difficult to grow pass the verification barrier

warm falcon
#

i see

shell radish
#

You could have a separate command like /answer

#

and wait for a response

warm falcon
#

that's a good idea

#

i'll have to store the question/answer in a global scope variable

#

then blank it out

#

i'm still figuring out how i want to structure it

#

my larger goal is to build something similar to an actual game of jeopardy, but i'm starting out with basic question/answer functionality

#

because that's a lot of data to process and also a lot of complicated functionality

shell radish
#

you need some way to organize questions and answers

#

and also some way to have an answer still be correct without it being verbatim

warm falcon
#

right

#

i've already got a database sorted

#

and i figure i can just set the message's content to lower and check it against the answer, lowered

wild tartan
#

any examples on how to incorporate Threads or multiprocessing? Trying to figure out how to record and play audio in a voice channel, but that would need to be run constantly and not just on commands.

pastel knot
#

hey, so i m using client + interactions + tree com,mands, is there anyway to make cogs work with that? i m kinda on 3500+ lines i cant just go back and redo xd

shell radish
shell radish
wild tartan
#

I would love to have a pointer to where i can find examples of such

#

Even just trying to play a Queue of audio while the bot is still responsive to commands is making my head turn

#

for example Queue.get() is forever blocking

wild tartan
#

havent exactly found anything I can use thats not tasks which is limited to 1 seconds minimum

pastel knot
# shell radish discord.py

oh that makes sense(got confused), is there an easy way to just switch? :" i really wanna use cogs, etc

i have been switching every command ,etc

but i have some stupid questions xd
can i still use interactions while dealing with slashcommands or do i need to use ctx?

#

i m really confused between both

shell radish
#

but most interaction attributes have a ctx shortcut

#

e.g. ctx.followup.sendinteraction.followup.send

pastel knot
#

i was using tree with client in discord.py
thats gonna be alot to switch
thank you btw

sage tendon
#

not really tbh

pastel knot
sage tendon
#

well, show your command code including the decorators

little cobalt
#

@pastel knot do you want to use discord.py or py-cord?

pastel knot
#
from discord.ext import commands, tasks

intents = discord.Intents.all()
intents.guilds = True
intents.members = True
intents.voice_states = True
intents.messages = True

class MyBot(commands.Bot):
    def __init__(self, *, intents: discord.Intents):
        super().__init__(command_prefix="/", intents=intents)

client = MyBot(intents=intents) #here i m honestly just lazy to change names 


@client.slash_command(name="hello", description="Says hello")
async def hello(ctx:commands.Context):
    try:
        await ctx.respond("Hello!")
    except Exception as E:
        print(E)



#my old client code (discord.py)

class appcomm(Client):
    def __init__(self, *, intents: Intents):
        super().__init__(intents=intents)
        self.tree = app_commands.CommandTree(self)
        

client = appcomm(intents=intents)

#with @client.tree.command(name="hello", description="Says hello")```
sage tendon
#

noooo make it back into a codeblock

pastel knot
#

like this?

sage tendon
#

no

#

do three back ticks followed by py to open it, and then three at the end

#

```py

#

hm

little cobalt
sage tendon
#

I think they know that lol

pastel knot
sage tendon
#

do you need prefix commands?

pastel knot
little cobalt
#

You can switch

#

But you gonna have to rewrite some code

sage tendon
#

Well if you wanna switch to pycord with slash only, delete all of the bot definition stuff except for the intents, and then do bot = discord.Bot(intents=intents)

#

and then it's @bot.command()

#

unless you use wanna cogs then it's a bit different

rugged lodgeBOT
#

Here's the slash basic example.

#

Here's the slash cog example.

pastel knot
#

okay let me try

#

oh it worked! thank youu

#

so would it make a diffrence if i did that?

async def hello(interaction:discord.Interaction):
    try:
        await interaction.response.send_message("Hello!")
    except Exception as E:
        print(E)```
#

i mean used interaction instead?

#

because it worked for me and gave me a response

fresh sierra
#

you have an event that gather all command error

echo wraith
#

If I define my slash command option with @discord.option can i then have a custom decorator on my command that uses *args and pycord will still know the command options because of @discord.option?
In other words, can I use *args, **kwargs on a slashcommand if options are specified with discord.option?

fresh sierra
fresh sierra
echo wraith
#
def load_guild_or_raise(func: Callable[[Any, ...], Coroutine]) -> Callable[[Any, ...], Coroutine]:
    async def wrapper(self, ctx: discord.ApplicationContext, *args, **kwargs):
        guild: GuildAdapter = GuildAdapter(ctx.guild.id)
        await guild.load()

        if not guild.exists:
            raise NotFoundError
        await func(self, ctx, *args, guild, **kwargs)

    return wrapper

then


# this is in a cog
@commands.slash_command(name="ping")
@discord.option(name="enable",
        description="Enable or disable the ping feature",
        type=bool,
)
@load_guild_or_raise
async def(self, ctx, enable: bool, guild: GuildAdapter):
  await guild.disable_ping()
#

can I do this or will pycord crash?

fresh sierra
echo wraith
#

that's a shame

fresh sierra
#

ooooo i just understood

#

you should do like so :

echo wraith
#

Because right now what I am doing is having a predicate check ant I hijack ctx to give him a .guild_obj

#

but that's messy and my type checkes gives warning everywhere

fresh sierra
#
def load_guild_or_raise(func: Callable[[Any, ...], Coroutine]) -> Callable[[Any, ...], Coroutine]:
    async def wrapper(self, ctx: discord.ApplicationContext, *args, **kwargs):
        guild: GuildAdapter = GuildAdapter(ctx.guild.id)
        await guild.load()

        if not guild.exists:
            raise NotFoundError
        return True

    return wrapper


then
# this is in a cog
@commands.slash_command(name="ping")
@discord.option(name="enable",
        description="Enable or disable the ping feature",
        type=bool,
)
@load_guild_or_raise
async def(self, ctx, enable: bool, guild: GuildAdapter):
  await guild.disable_ping()
#

ooo

#

i think i just understood

#

you want to pass the guild attr

#

from the @local right ?

echo wraith
#

yes

fresh sierra
#

load*

#

not local

echo wraith
#

The problem is that I believe that will give pycord a function whoose signature is self, ctx, *args, **kwargs) aka wrapper

fresh sierra
#

but yeah that's should be possible

#

maybe you should use the invoke

#

.rtfm invoke

fresh sierra
#

i will not do it like so tbh so i dont really know how to do that but yeah you can do a funct that basically run everytime before

#

discord.Bot.invoke_application_command

#

this one

echo wraith
#

I'll try

echo wraith
#

this is wrong

#

I'll open a more general post in #969574202413838426

echo wraith
sage tendon
#

what even is the use case of using a decorator to add an option
just.. add the option

echo wraith
#

like it dosen't add the option to the discord command

#

but in the end I subclassed context and everything works fine

sage tendon
#

ah

broken pivot
#

if the bot is available on two servers, it sends 2 messages

#

(not 2 bot objects)

fresh sierra
#

i think you simply have 2 process_message

#

so the command is done 2 times

fresh sierra
broken pivot
#

1 procces_message

fresh sierra
#

remove

#

since its on a cog you dont need it

broken pivot
#

i will try it

#

thx

little cobalt
broken pivot
little cobalt
#

its (self, message: discord.Message)

#

its a message event....

#

not a slash command

broken pivot
#

I didn't write the code

little cobalt
#

lol

#

who wrote it?

broken pivot
little cobalt
#

F

fresh sierra
#

stop paying for that

broken pivot
sage tendon
broken pivot
little cobalt
broken pivot
#

ctx in on_message?

sage tendon
sage tendon
sage tendon
#

Uh, no, not normal

#

That doesn't belong there.

lofty parcel
#

They said they didnt write the code

#

So blame the dumbass dev they hired.

sage tendon
#

I'm well aware, just wanna clear it up

lofty parcel
sage tendon
#

Nope

#

I'm not talking about that

lofty parcel
#

My brain decided to find other message

sage tendon
#

yea, but judging from their responses it isnt clear yet

#

I have my reasons for saying stuff

wild tartan
#

Is there any examples on how to stream voice channel audio to the bot?

fresh sierra
#

I think i saw somewhere that bridge bot cant have sub sub commands

#

is that's true ?

#

out

fresh totem
sage tendon
#

I mean it allows you to completely customise who and which roles can and can't use the command
isn't that exactly what you want

fresh totem
#

Yes I could lock it to admins only and then override the other roles from within discord, you're right.

#

Thanks!

#

How can I await a send_modal after ctx.defer()

sage tendon
#

you cant

fresh totem
#

I have an if condition which slightly delays the send_modal and often it results in the: Unknown interaction error

sage tendon
#

yea you can't
modals have to be instantly responded to for all I know

fresh totem
#

Aight, thanks!

lapis dock
#

Discord when they don't love modals enough rooSob

deft kestrel
#

Calling ctx.respond() without parameters will just acknowledge the response?

little cobalt
#

So you should send a message

deft kestrel
#

I just want to acknowledge the response

#

as the message changes components

fresh sierra
deft kestrel
#

woah didin't know that existed

#

I did self.message.edit

deft kestrel
#

If I want to both edit the message and respond with a modal, do I do self.message.edit instead of ctx.response.edit_message? and then ctx.response.sendmodal

lofty parcel
#

So yes, you respond with the modal and do self.mesaage.edit

fresh sierra
#

what does trigger the event on_bridge_command

#

because basically no command of my bot trigger bridge

#

because i did create my own function to create a multicog and a bridge support, however now those event are not triggered

#

so i think i should add something to these function for the bridfge event to work

#

and i did not change the invoke_application_command that should be the one to dispatch that

#

bridge error seems to work everywhere, bridge command completetion only for prefix

#

and on bridge command does not work at all

fresh totem
#

Hi, I'd like to lock down a command to a list of User IDs, what's my best course of action?

fresh totem
#

Is there a way I could make it so it doesn't appear for others in the server?

little cobalt
#

wait

#

for others not really

fresh totem
#

Okay thanks, will have to go with predicate I guess!

little cobalt
#

only with permissions

little cobalt
fresh sierra
#

I misread

#

I though he said and it only appear on some server

umbral musk
#

Are user apps supported in pycord and are there any code examples on them?

fresh sierra
#

.tag user_app

sly karmaBOT
#

Tag not found.

fresh sierra
#

Idk the tag

umbral musk
fresh sierra
#

This one

fresh sierra
umbral musk
#

Doope thanks ❤️

errant trout
umbral musk
lapis dock
shadow bear
#

Is there a way to query a set of members without the members intent matching a specific criteria?

umbral musk
deft kestrel
#

how to disable the help command?

tidal vessel
deft kestrel
tidal vessel
deft kestrel
lapis dock
fresh sierra
#

.rie

sly karmaBOT
#

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

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

fresh sierra
maiden bloom
#

Any estimates on when the next stable version will be released?

fresh sierra
#

i think i read maybe 26 or 28

#

but will maybe be delayed of a weeks

fresh sierra
#

If i have some pillow in an async def funct,
does this will block my own bot ?

async def blocking_funct()
    pillow...

@commands
async def command():
    await blocking_funct()
#

does this will block

sage tendon
#

Yes?

fresh sierra
#

how can i do for i does not block ?

sage tendon
#

use an async version of it if it exists or put it into its own thread

fresh sierra
#

i did check at the

#

.rie

#

but this only work with def funct, and in my code with pillow i also need some async func

sage tendon
#

Google how to do threading in python

fresh sierra
fresh sierra
#

and my func is async with some pillow in it

#

how to use run_in_executor as async if u prefer

#

welli will move to a post

umbral musk
sage tendon
fresh sierra
sage tendon
#

??

#

you make no sense

fresh sierra
#

so i will try to expplain u better

#

the function is like so
-> async query
-> pillow
-> async query
-> pillow
-> async query
-> pillow

  • 10
#

so my goal is first to see if i can not make a function for each single time im using pillow and just wrap everything in a func

sage tendon
#

yea, do it all in one function, and call the pillow shit using asyncio

fresh sierra
#

here a little part of it :

async def funct():
    for channel_id in top_text_channels:
        try:
            channel = await bot.get_or_fetch_channel(channel_id[0])
            async with Database() as db:
                message = (await db.execute(f"SELECT SUM(msg_count) FROM stats_data WHERE guild_id = %s AND channel_id = %s AND timestamp >= UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL {max_time} DAY))", (guild.id, channel.id)))[0]
            channel_name = channel.name
            with Pilmoji(card) as pilmoji:
                text_width = draw.textlength(channel_name.strip(), font=medium_25)
                if text_width > 170:
                    while text_width > 170:
                        channel_name = channel_name[:-1]
                        text_width = draw.textlength(channel_name.strip(), font=medium_25)
                    channel_name = channel_name.strip() + "."
                #pilmoji.text((80, [510, 572, 634][count]), channel_name.strip(), font=medium_25)
                draw.text((300, [510, 572, 634][count]), translator.stats.guild.message.channel.value.format(number=message), font=italic_25)
            
            count += 1
            if count >= 3:
                break
        except:
            pass
#

im like maybe just im not understanding what ur saying

#

so can you explain what here i should call with async

#

each draw.text and pilmoji.text ?

sage tendon
fresh sierra
#

because this call a func def

#

and not an async one

sage tendon
#

???????

fresh sierra
#

and as you can see here im using async and also def in the same one

#

so i will need to change anything

sage tendon
#

dude

fresh sierra
#

to create sub func for each

sage tendon
#

run the pillow function in an executor then

#

it's not that difficult to grasp

fresh sierra
#

if i understand

fresh sierra
torpid umbra
#
async def finished_callback(sink, channel: discord.TextChannel, *args):
    recorded_users = [f"<@{user_id}>" for user_id, audio in sink.audio_data.items()]
    await sink.vc.disconnect()
    files = [
        discord.File(audio.file, f"{user_id}.{sink.encoding}")
        for user_id, audio in sink.audio_data.items()
    ]
    await channel.send(
        f"Finished! Recorded audio for {', '.join(recorded_users)}.", files=files
    )

I also want to save file on local machine in current directory , how to do that?

shell radish
#

audio.file...

torpid umbra
little cobalt
shell radish
torpid umbra
#

it's wrong

shell radish
#

because that's blatently wrong

torpid umbra
#

it required IO data as argument

little cobalt
#

and I send the files other ways xd

torpid umbra
shell radish
#

what is sink.encoding?

torpid umbra
shell radish
#

i mean the value

torpid umbra
#

wav

shell radish
#

you want to use aiofiles

torpid umbra
shell radish
#

it's a library

#
async with aiofiles.write("filename.wav", "w") as f:
    await f.write(audio.file)
torpid umbra
#

Alright , I'll try

upper flint
#

How to fetch message from the api and not from bot's cache? bot.get_message(id) doesn't work after restart

fresh sierra
#

.rtfm fetch_message

shell radish
#

await bot.get_partial_messageable(channel_id).fetch_message(message_id)

upper flint
#

And If ID is not bound to a particular channel or guild? Is it possible to fetch it?

shell radish
#

no

upper flint
#

I see. Thanks!

shell radish
#

unless you brute force it

upper flint
#

How to change voice channel's rtc region?

#

Found it. VoiceChannel.edit(rtc_region=...)

sage tendon
#

discord should handle that fine automatically

vestal folio
#

If that in pycord?

sage tendon
#

Maybe if you ask a full question someone can answer it

vestal folio
sage tendon
#

Polls aren't yet in stable

weary meteor
#

is there anyway for me to restart my bot.py file via a command? ik its weird as a question but sorta need it

red mist
#

There is

#

Hold on

#
os.execv(sys.executable, ['python'] + sys.argv)
weary meteor
#

nvm, its because i started my bot thru pycharm

red mist
#

o

weary meteor
#

starting it via cmd fixed it

#

appreciate the help

red mist
#

yw ig

#

O just make sure

#

You're now not running multiple

#

Bot instances

weary meteor
#

yep

fresh sierra
#

im doing exit()

#

it restarts well

weary meteor
fresh sierra
#

Since I’m using pterodactyl

#

When something stop like exit it restart automatically

weary meteor
#

ahh

echo wraith
#

How would you implement a healtcheck for a bot running in a docker container?

#

(basically can be any command that fails if the bot is down)

sage tendon
#

just check if the process is still running lol

deft kestrel
#

how to timeout someone for 7 days?

fresh sierra
#

.rtfm timeout

devout glacier
#

how do i link slash commands in embeds like so:

lofty parcel
#

</command name:command id:>

fresh sierra
shadow bear
#

Can you get reaction events to the bot's own messages without the messages intent?

#

messages, not message content

fresh sierra
keen relic
#

what is the work of this function-- add_bridge_command(command)

sage tendon
#

adds a bridge command to the bot

fresh sierra
#

how can i put the max_value as infinity for the discord.ui.Select() ?

lapis dock
#

The maximum is 25. According to ddev docs 25 is still the maximum for role/user/channel selects as well

fresh sierra
#

if for example there are 23 options i cant put max_values 25 or it will raise an error

lapis dock
#

I think just using a len would work fine max_values=len(options)

fresh sierra
#

yeah so i will need to move the options outside the discord.ui.Select()

#

but if there is no other solution

prime pumice
#

Hi there,
I cant get reactions working properly.
Is there a specific intent or permission im missing? This script hangs its self after the adding the first (out of 5) reactions. (It starts to send Heartbeat failed error messages)

for reaction in [...]:
    await message.add_reaction(reaction)

Any tip is welcome

#

bot is admin

#

the function does not raise an error

prime pumice
#

a video file with a text
message: Message = await channel.send(content="sometext", file=File(filename))

prime pumice
kindred lava
#

how can I create a comamnd that I can use anywhere in discord

fresh sierra
kindred lava
#

How kann I install the latest reales of pycord?

little cobalt
#

.master

sly karmaBOT
#

pip install -U git+https://github.com/Pycord-Development/pycord

kindred lava
lapis dock
#

.logging

sly karmaBOT
lapis dock
oblique fern
#

Am I missing something in the docs, or isn't it possible to get all "suspected of spam activities" members of a server?

sage tendon
#

don't think so

#

I think it's just not on the discord api

fresh sierra
oblique fern
#

Hmmm, so nothing that gives me just a list of them from a Guild, I'll have to loop over all members?

oblique fern
#

Shame... I want to kick those people from servers, not ban them straight up like Discord only allows you to do in bulk...

fresh sierra
#

dont kick all those poor guy, maybe some have done nothing

oblique fern
#

hence the kick with a message 🙂

#

and not straight up banning

fresh sierra
#

u might have an issue with that

#

if u kick all memebr and dm them

#

if ur bot isnt certifed there is a lot of chance he gets flag

oblique fern
#

It is verified

fresh sierra
#

so it should be okay

#

well it depends

#

but if u dont have hundred and hundred

#

it should be okay

oblique fern
#

Well yeah, I'm not looping over 58k members 😛

lapis dock
#

And you could just message before the kick and have slightly better chance of not getting flagged

frail ocean
#
WARNING: discord.gateway: Shard ID None heartbeat blocked for more than 790 seconds.```Whats that
fresh sierra
frail ocean
#

Ah

prime pumice
rough heron
#

Is there an example for default_permissions or however you hide commands from users?

sage tendon
#

@discord.default_permissions(administrator=true)
not more to it

rough heron
#

oke- thanks mate

lapis dock
rough heron
#
import discord
import asyncio
import datetime
from discord.commands import option
from discord.ext import commands

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

bot = discord.Bot(intents=intents)

This is my very small set of imports, what am I doing wrong / how do I fully become pycord

my packages:

aiosignal    1.3.1    1.3.1
attrs    23.2.0    23.2.0
frozenlist    1.4.1    1.4.1
idna    3.7    3.7
multidict    6.0.5    6.0.5
pip    24.0    24.1
py-cord    2.5.0    2.5.0
setuptools    65.5.0    70.1.1
yarl    1.9.4    1.9.4```
#

(I've been getting this error)

Traceback (most recent call last):
  File "C:\Users\xboxa\PycharmProjects\USNUtilities\USN Util.py", line 9, in <module>
    from discord.commands import option
  File "C:\Users\xboxa\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\__init__.py", line 26, in <module>
    from .context import *
  File "C:\Users\xboxa\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\commands\context.py", line 30, in <module>
    import discord.abc
ModuleNotFoundError: No module named 'discord.abc'
shell radish
#

uninstall everything then re-install everything

rough heron
#

I don't need to install any package other than pycord, correct?

shell radish
#

yeah

rough heron
#

would you say the same thing for this?

Requirement already satisfied: aiosignal==1.3.1 in ./.local/lib/python3.12/site-packages (from -r requirements.txt (line 2)) (1.3.1)
Requirement already satisfied: attrs==23.2.0 in ./.local/lib/python3.12/site-packages (from -r requirements.txt (line 3)) (23.2.0)
Requirement already satisfied: py-cord==2.5.0 in ./.local/lib/python3.12/site-packages (from -r requirements.txt (line 4)) (2.5.0)
Requirement already satisfied: frozenlist>=1.1.1 in ./.local/lib/python3.12/site-packages (from aiohttp==3.9.5->-r requirements.txt (line 1)) (1.4.1)
Requirement already satisfied: multidict<7.0,>=4.5 in ./.local/lib/python3.12/site-packages (from aiohttp==3.9.5->-r requirements.txt (line 1)) (6.0.5)
Requirement already satisfied: yarl<2.0,>=1.0 in ./.local/lib/python3.12/site-packages (from aiohttp==3.9.5->-r requirements.txt (line 1)) (1.9.4)
Requirement already satisfied: idna>=2.0 in ./.local/lib/python3.12/site-packages (from yarl<2.0,>=1.0->aiohttp==3.9.5->-r requirements.txt (line 1)) (3.7)
[notice] A new release of pip is available: 24.0 -> 24.1
[notice] To update, run: pip install --upgrade pip
Traceback (most recent call last):
  File "/home/container/bot.py", line 6, in <module>
    import discord
ModuleNotFoundError: No module named 'discord'
shell radish
rough heron
#

Nope :(

#

Using a terrible free hosting service

shell radish
#

do you have a requirements.txt?

#

can you send that

rough heron
#

vastly shortened it bc I figured I didn't need a lot of the default stuff I got from pycharm

#
aiohttp==3.9.5
aiosignal==1.3.1
attrs==23.2.0
py-cord==2.5.0```
shell radish
#

what can you do the server?

rough heron
#

There's an option to reinstall the server, I've tried several times with deleting the file and reinstalling the entire server, it doesn't seem to change anything.

#

Using bot-hosting.net if you know enough to say something along the lines of "the best way to fix that issue is to not use it"

shell radish
#

if they have a support server, ask them how to uninstall dependencies

#

you want to uninstall discord/discord.py and just install py-cord

rough heron
#

Yeah, I've asked. No response but figured I'd ask here in case it was another issue.

#

Sounds good then, I'll leave yall alone. Thanks mate.

shell radish
#

k

whole needle
#

no defining

little cobalt
#

What is not defined?

whole needle
#

discord.Bot

#

@little cobalt

little cobalt
#

Can you show the pip list pls?

sage tendon
sage tendon
# whole needle

written out, it would be discord.bot.Bot
maybe your "IDE" is just not picking that up

little cobalt
#

or its the wrong env

#

or its not installed

red mist
little cobalt
rancid arrow
#

is it possible for two slash commands in different files to be part of the same slash command group

rancid arrow
#

how?

fresh sierra
#

easier way is to use pycord-multicog

fresh sierra
#

it has some limitation but normally it should be okay for u

rancid arrow
#

i'll take a look ty

rancid arrow
#

is it possible to reload the multicog for updates, it seems that unload_extension and load_extension aren't working

upper flint
#

Discord thinks that this is not a valid number. Why?

@discord.command()
async def delete_lobby(self, ctx: discord.ApplicationContext, lobby_id: int):
  pass
upper flint
#

Via discord.Option()?

#

Or is this discord limitation?

sage tendon
#

discord limitation

#

just take a string and parse it as int

#

discord uses a completely brain damaged kind of int

fresh sierra
rancid arrow
#

So using load and unload extension should work but currently isn’t because discord being bad?

lapis dock
#

Loading and unloading should work but does not work 100% as there is not a good way to remove/re-add commands to discord without hitting ratelimits. This time it is actually more of a pycord issue than discords.

rancid arrow
#

Oh ok prayadge

vital bramble
#

I have the strange problem that the channel object I get from an discord.Interaction has the wrong members attribute. It seems like it's listing every member in the guild instead of just the members that have access to the channel. Fetching the channel again solves that. Any Idea what might cause this?

#

It's in a button interaction

sage tendon
#

interaction.channel.members?

fresh sierra
vital bramble
vital bramble
#

Also why did it work before and why does it work when I fetch the channel?

fresh sierra
#

let me check the code

#
    @property
    def members(self) -> list[Member]:
        """Returns all members that can see this channel."""
        return [m for m in self.guild.members if self.permissions_for(m).read_messages]
#

yep it should check the permission for the channel

fresh sierra
#

the cache is not updated and at this periode all member were able to see the channel

#

and fetching it change the cache

vital bramble
fresh sierra
#

.rtfm self.bot.clear()

sly karmaBOT
#

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

fresh sierra
#

.rtfm clear

fresh sierra
#

Maybe try with the client clear

vital bramble
fresh sierra
#

Tbh this is way above my knowledge so maybe someone will give u a better answer

fresh sierra
#

Pls ping me when u got the answer

shell radish
vital bramble
shell radish
#

I don't see an interaction.members attr in docs

vital bramble
#

interaction.channel.members

shell radish
#

oh yeah. Interactions give the bare minimum information required for the interaction to process. If the guild's members and channels aren't cached, then much of the information, including permissions, is unavailible

vital bramble
shell radish
#

no, I mean permissions

vital bramble
#

But the thing is, that it is in fact available, but wrong.

shell radish
#

it is not availible

vital bramble
#

And I'm still talking about the members

#

Just the list. It's wrong.

shell radish
#

right, but it relies on the GuildChannel's permissions

#

the interaction bears a partial channel object with incomplete information

vital bramble
#

Oh, ok. So if those permissions are missing, it just assumes everyone can see the channel?

vital bramble
#

Ok. And I guess a possible solution would then be to fetch the guild on bot start?

#

Does that fetch the channels too or would I have to fetch the channels manually then?

shell radish
vital bramble
#

Also, I guess that problem does not occur with discord.Context, right?

shell radish
#

discord.Context does not exist

vital bramble
#

I mean slash command. I think it's ApplicationContext xD

shell radish
vital bramble
#

I'm just confused why I never came across this Problem before... This is the first time I hear about it. Before, it just worked...

shell radish
#

cache

vital bramble
#

And that would also mean that I now have to fetch the channel every time I want to access its members...

shell radish
#

you can get or fetch

vital bramble
shell radish
#

the problem is that it isn't cached

#

not that the cache is wrong

frail ocean
#

Can i get and dm members somehow without intents?

fresh sierra
frail ocean
fresh sierra
#

wait maybe not

#

you need member intents to access the on member join etc

#

so i guess so also need it to send dm

#

yeah you will need it help you cant get the member with the get_member

fresh sierra
frail ocean
#

Yes i know

vital bramble
fresh sierra
#

So yeah u should use get or fetch

edgy nest
torn spire
#

Try running this in console

let max = Number.MAX_SAFE_INTEGER;
let _8 = max + 1 , D = max + 2;
console.log(_8===D);
bright stump
#

How I can determine who exactly triggered on_raw_thread_member_remove? As I see in state.py, it just dispatches event with RawThreadMembersUpdateEvent as arg for each removed member id without passing id

shell radish
#

audit log?

bright stump
#

seems, like there's no AuditLogAction for leaving from thread

rancid arrow
#

is it possible to add data to a view that only applies to that specific view

fresh sierra
#

yes

#

by passing arg

rancid arrow
#

where would that argument get passed

#

kinda new to this stuff sorry

sage tendon
#

when you instantiate the object

#

and the init of course needs to actually take it

rancid arrow
#

ill try that out ty

fresh sierra
#

how can i create a class which is an union of 2 others class

#

(for the typehint)

shell radish
#

class1 | class2

fresh sierra
#

yeah but i mean

#

class LumabotContext(Lumabot_Prefix_Context | Lumabot_Application_Context)

#

this will not work

#

and if i put one before the other with a comma it just remove half of the autocomplete

quartz umbra
#

Hello. I would like to rewrite my bot to use cogs. From my understanding currently, they're a way to group commands to reduce the length of main.py, and in discord, you use them eg. if you had a cog called math, you'd do /math add

My question is what determines the first name, i.e. /math?
Is it the name of the cog class or the name of the cog file or what?

Thank's for the assistance

shell radish
#

cogs are not related to command groups

#

you can have a math cog or not and have /add and /subtract and have /math add and /math subtract

quartz umbra
shell radish
#

they just help you organize your code into sections

#

or modularity

quartz umbra
little cobalt
#

yes

tender olive
#

Is there a way to turn the show boost progress bar setting on and off via bot?

lapis dock
#

Guild.edit with premium_progress_bar_enabled looks like what you want

quartz umbra
#

Hi, can someone help me with something?
So my project structure is a bit like this:```py
root:
-main.py
-cogs
--ranks_cog.py
-helpers
--helper.py
--firebase_helper.py

I need to use functions from the helper files from the ranks cog. How can I do this?
#

like how do I import those files?

red mist
#

use from ..helpers.helper import variable

Or from .helpers.helper import variable

#

Or a function in your cade

#

Honestly its much more simpler if you were to just make init.py files

#

Also it is more o less a general python question than pycord but ok

#

@quartz umbra

quartz umbra
deft kestrel
#

how do I actually make my error handling work on my main file? tried adding the code bellow, but it still not handling

@client.event
async def on_application_command_error(ctx:discord.ApplicationContext, error:discord.DiscordException):
        if isinstance(error, commands.CommandOnCooldown):
            await ctx.respond("Este comando está em tempo de espera", ephemeral=True)
        elif isinstance(error, commands.MissingPermissions):
            await ctx.respond("Você não tem as permissões necessárias para usar este comando.", ephemeral=True)
        elif isinstance(error, commands.BotMissingPermissions):
            await ctx.respond("Eu não tenho permissões o suficiente para fazer isso.")
        elif isinstance(error, commands.NSFWChannelRequired):
            await ctx.respond("Este comando só pode ser usado em canais NSFW", ephemeral=True)
        elif isinstance(error, commands.NoPrivateMessage):
            await ctx.respond("Este comando não pode ser usado em mensagens privadas.", ephemeral=True)
        elif isinstance(error, commands.CommandNotFound):
            await ctx.respond("Comando não encontrado.", ephemeral=True)
        elif isinstance(error, commands.DisabledCommand):
            await ctx.respond("Este comando está desativado.", ephemeral=True)
        elif isinstance(error, commands.CheckFailure):
            await ctx.respond("Você não pode usar este comando.", ephemeral=True)
        elif isinstance(error, commands.UserInputError):
            await ctx.respond("Erro no input do usuário.", ephemeral=True)
        elif isinstance(error, commands.CommandInvokeError):
            logger.error(f"Erro ao invocar comando: {error.original}")
            await ctx.respond("Erro ao invocar o comando.", ephemeral=True)
        else:
            logger.error(f"Erro desconhecido: {error}", exc_info=True)
            await ctx.respond("Ocorreu um erro desconhecido.", ephemeral=True)```
junior python
#

hey quick question when attempting to use start instead of run the main event loop gets blocked am i doing something wrong?

junior python
fresh sierra
fresh sierra
#

Does anyone know where I can find all per route emoji rate limit

#

Like 250 per 48 for role creation etc etc

little cobalt
fresh sierra
#

Why does unknow response does not trigger application error ?

#

basic answer, because ur invoke_application_command disptach hybrid_command_errror and not hybrid_command_error

fresh sierra
#

how can i pass a checks for a commands.Group ?

echo wraith
#

Is it normal if ctx.command is none with slash comands?

#

Wait it's because I'm doing it in the overriden context

#

whatever

echo wraith
#

because I was accessing it in the ctx's init

#

when I subclassed ctx

#

and command is set when running invoke not __init__

fresh sierra
#

i was thinking u were talking in a regular thing like in a command or else

balmy dome
#

Can you please advise, what type of database is better to use for a public Discord bot (for many servers)?

fresh sierra
#

.tag database

sly karmaBOT
#

Tag not found.

fresh sierra
#

.tag nojson

sly karmaBOT
#

JSON is a convenient and easy-to-read data storage protocol that's widely accepted by most programming languages. However, we caution against its use for storing and retrieving data in an asynchronous environment like a Discord bot. Don’t use json!

  • It's a file-based data storage, which makes it vulnerable to race conditions
  • You'll need to implement your own synchronization primitives to avoid corrupting data
  • If you're not careful, you could accidentally wipe your entire JSON file.

Solution? Use a database. Recommended schema are SQLite, PostgreSQL, and MongoDB.

  • Async libraries exist on pypi for each of these
    sqlite -- aiosqlite (or Danny's wrapper: asqlite)
    postgresql -- asyncpg
    mongodb -- motor
  • Databases organize your data into tables, and are fast at inserting, retrieving, and removing records
  • You can impose uniqueness constraints to ensure against duplication
  • The Python libraries enforce synchronization for you
  • The query language is intuitive, you can get running with simple queries in just a few hours!
fresh sierra
#

just need to be async else its really badt

junior python
junior python
fresh sierra
#

This block all ur loop

#

that's why

junior python
#

I’m doing some async work b4 hand so bot.run() won’t work

#

This has worked for awhile in discord py

fresh sierra
#

if u are using @tasks.loop you can just do task.start

junior python
#

I removed all my code and same issue

fresh sierra
#

loop = asyncio.get_event_loop()
loop.run_until_complete(client.start('TOKEN'))

#

you can do like this ig

#

i dont really see a reason of why not using bot.run i didnt understand why u cant)

junior python
#

Bc I’m doing async work ahead of time

#

But i removed that and same issue

fresh sierra
#

th async is before the bot run or after

junior python
#

Ik it blocks the after

#

But it’s blocking heartbeat

fresh sierra
#

that is running

#

so it block ur current loop

junior python
#

I legit removed everything except the start

#

And the issue doesn’t happen with run

fresh sierra
#

can you show me ur code ?

junior python
#

But like i said I’ve got work that needs to be setup before the bot runs

fresh sierra
#

.tag past

sly karmaBOT
#

Tag not found.

Did you mean...
paste

fresh sierra
#

.tag paste

sly karmaBOT
#

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

junior python
fresh sierra
#

will be easier to help and understand

junior python
#

Like i said it’s just five lines

#

I removed everything to test

fresh sierra
#

ok so u ust have bot.start

junior python
#

Yeah

fresh sierra
#

well i did got the same issue as u

junior python
#

And that causes the error

#

I believe it’s a py cord bug

#

Bc I’ve used it fine in discord py

fresh sierra
#

If you use asyncio.run(bot.start("tokeb")) it causes this werid behaviour while using loop.run_unitl_complete(bot.start...) does not. Dont know why cause i thought .run does that under the hood but who knows

junior python
#

I’ll try what you said but like i said I’ve been doing it like this for almost 3 years

#

Moved to cord and it’s a issue

fresh sierra
#
if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    try:
        loop.run_until_complete(bot.start(token))
    except KeyboardInterrupt:
        loop.run_until_complete(bot.start(token))
    finally:
        loop.close()
junior python
fresh sierra
junior python
#

yeah that worked tysm!

cloud bloom
#

does pycord have a way to handle authentication for a website?

mild trout
#

I'm trying to create a simple command to test the user-installed apps but im having some trouble.

My code

@bot.slash_command(name="ping", description="Muestra el ping del bot", contexts={discord.InteractionContextType.private_channel}, integration_types={discord.IntegrationType.user_install, discord.IntegrationType.guild_install})
async def ping(ctx: discord.ApplicationContext):
    await ctx.respond(f"Pong! {bot.latency*1000:.0f}ms")

Error:

@bot.slash_command(name="ping", description="Muestra el ping del bot", contexts={discord.InteractionContextType.private_channel}, integration_types={discord.IntegrationType.user_install, discord.IntegrationType.guild_install})
ttributeError: module 'discord' has no attribute 'InteractionContextType'
cloud bloom
#

I should use requests instead right

cloud bloom
#

and for:

contexts={discord.InteractionContextType.private_channel}
#

OH IS THIS FOR THE NEW USER COMMANDS THING

cloud bloom
#

I see!

#

I guess the pycord lib doesn't have InteractionContextType

#

what does that do in particular

mild trout
#

yes a mod was telling me in #general that i need to isntall the PR, its not released yet in the lib

mild trout
#

also lets you use in dms

cloud bloom
#

yea I got no clue

#

probably check the PR

#

it's not in docs yet right

mild trout
#
pip install git+https://github.com/Pycord-Development/pycord@feat/ua
lofty parcel
#

@mild trout

#

?tag install

limber wagonBOT
#

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

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

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

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

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

lofty parcel
#

Last line.

lapis dock
#

@mild trout It was recently added to master. It should now work by installing the last line like dark mentioned.

cloud bloom
#

niceee

mild trout
#

thanx you guys, i never really installed directly from github

lapis dock
#

That is fine. We told you wrong originally as we did not realize that the branch was merged into master.

mild trout
#

i saw the merge and i wrongly believed it meant it was already in the package hehe

lapis dock
#

👍 That is understandable for someone new to working with github 😄

When we say "master" that is the dev version that is not guaranteed to be stable (but is currently). You have to install this directly from github. We will post in #library-updates when there is an update to the pypi package (that you can than install normally)

young skiff
#

Could py-cord have a method to load the cogs from the cogs folder, or load them automatically? I currently have this code but I'm not sure if it's the best way to start the cogs

cloud bloom
# young skiff Could py-cord have a method to load the cogs from the cogs folder, or load them ...

I have something very similar:

    # -- Setup Cogs --
    with open(os.path.abspath("./setup.json"), "r") as setup_json:  # Use the setup folder to get the cogs folder
        cogs_folder = json.load(setup_json)["cogs_folder"]  # Load cogs folder from setup JSON

    with open(os.path.abspath(cogs_folder + "/cogs.json"), "r") as cogs_setup_json:
        cogs_json = json.load(cogs_setup_json)  # Json for the list of cogs

    for sub_folder in cogs_json["sub_folders"]:
        for file in cogs_json["sub_folders"][sub_folder]["files"]:
            print(file)
            file_path = f"{cogs_folder.replace('/', '').replace('.', '')}.{sub_folder}.{file}"
            print(f"Loaded {file_path}")
            bot.load_extension(file_path)```
#

if it works it works

#

only difference is that I have a json I read off of

young skiff
cloud bloom
#

maybe a PR with a helper func would be good

#

On another note,
How accurate is the bot's guild cache?

#

I'm attempting to make a bot panel that integrates the bot but idk whether I should make a fetch request

#

if the bot gets added to a new server, does it get added to the bot's guild cache?

young skiff
cloud bloom
#

To prevent bot rate limiting fetch_guild might be problematic (but hopefully not)

young skiff
#

If you constantly need information about your bot's guilds you could leave it as default and just do a get_guild, anyway I'm not completely sure

cloud bloom
#

ah ty!

young skiff
cloud bloom
#

Ah, I'm not quite getting the user though

young skiff
#

oh yeah

cloud bloom
#

I'm getting the guilds that the user is in

young skiff
#

sorry

cloud bloom
#

for..?

#

nothing to be sorry about

#

but ty!

young skiff
#

I copied the wrong link, no problem

cloud bloom
#

alr I got the following to work:

    for guild in user_guilds:
        # noinspection PyTypeChecker
        for bot_guild in bot.guilds:
            if int(guild['id']) == int(bot_guild.id):
                print(guild)
cloud bloom
#

How would I run my flask app in the background as a thread?

#

I tried:

    flask_thread = threading.Thread(main_flask.start_app(bot))
    flask_thread.start()

However, app commands just break

#

(start_app starts the flask app)

#

wait

#

figured it out

#

just had to change my start command

#
async def start_app(bot_):
    global bot
    bot = bot_

    app_thread = threading.Thread(target = app.run)
    app_thread.start()
#

also the target wasn't set 💀

young skiff
#

I have something like this (I'm using fastapi)

from api import run_api

async def run_bot(loop):
    await bot.start(os.getenv('BOT_TOKEN'))


async def main():
    loop = asyncio.get_event_loop()
    await asyncio.gather(run_bot(loop), run_api())


if __name__ == "__main__":
    while True:
        loop = asyncio.get_event_loop()
        loop.run_until_complete(main())

api.py:

async def run_api():
    server = Server(config=uvicorn.Config(app, host="0.0.0.0", port=25247))
    await server.serve(sockets=None)
cloud bloom
#

thanks!

#

Ok did some testing

#

and the cache does update!

#

which is epic

#

I added the bot and removed the bot from the server and when checking what it prints it prints both states

lofty parcel
#

Should attempt to load all the files in the folder.

young skiff
little cobalt
#

And py-cord is already creating a loop so you dont have to do it again

quartz umbra
# red mist Did you get it to work tho

I did! I asked ChatGPT! I set up my project as a library (using __init__.py everywhere), then say I wanted to use package2.module2 from package1.module1, i could just do (in module1): import ..package2.module2

red mist
#

Glad to hear it worked out :)

quartz umbra
#

My prev host ain't gonna work now

red mist
#

I bought a raspi

frail basin
fresh sierra
#

.tag hosting

sly karmaBOT
#

Need to run your bot 24/7? Get a cheap VPS.
https://www.scaleway.com/ EU https://www.time4vps.eu/ Lithuania.
https://www.digitalocean.com/ US https://www.vultr.com/ US
https://www.ovh.co.uk/ EU/Canada https://www.hetzner.com/ Germany/US
Self-hosting: Free hosting: Kinda free:
Any computer. Heroku dead 🦀 GCP, AWS have one year free micros.

Time4VPS

Affordable and powerful VPS Hosting in Europe. Linux, Windows and Storage VPS available from 1.99 EUR/month.

quartz umbra
fresh sierra
#

hetnzer very good and cheap

shell radish
#

railway if you want a US host

quartz umbra
shell radish
#

or anywhere north america not including mexico

frail basin
#

In my experience

fresh sierra
#

90 ping and not 15

#

can change something depends on ur bot

frail basin
frail basin
#

1usd / month

rain dune
#
WARNING:discord.gateway:Shard ID 2 heartbeat blocked for more than 200 seconds.
Loop thread traceback (most recent call last):
File "/home/container/main.py", line 53, in <module>
bot.run(f"{token}")
File "/home/container/.local/lib/python3.12/site-packages/discord/client.py", line 756, in run
loop.run_forever()
File "/usr/local/lib/python3.12/asyncio/base_events.py", line 641, in run_forever
self._run_once()
File "/usr/local/lib/python3.12/asyncio/base_events.py", line 1987, in _run_once
handle._run()
File "/usr/local/lib/python3.12/asyncio/events.py", line 88, in _run
self._context.run(self._callback, *self._args)
File "/home/container/.local/lib/python3.12/site-packages/discord/client.py", line 400, in _run_event
await coro(*args, **kwargs)
File "/home/container/.local/lib/python3.12/site-packages/discord/bot.py", line 1181, in on_interaction
await self.process_application_commands(interaction)
File "/home/container/.local/lib/python3.12/site-packages/discord/bot.py", line 864, in process_application_commands
await self.invoke_application_command(ctx)
File "/home/container/.local/lib/python3.12/site-packages/discord/bot.py", line 1130, in invoke_application_command
await ctx.command.invoke(ctx)
File "/home/container/.local/lib/python3.12/site-packages/discord/commands/core.py", line 376, in invoke
await injected(ctx)
File "/home/container/.local/lib/python3.12/site-packages/discord/commands/core.py", line 131, in wrapped
ret = await coro(arg)
File "/home/container/.local/lib/python3.12/site-packages/discord/commands/core.py", line 1009, in _invoke
await self.callback(self.cog, ctx, **kwargs)
File "/home/container/commands/commands/login.py", line 41, in login
userData = await auth.login_auth()
File "/home/container/utils/authData.py", line 52, in login_auth
r = requests.put(f"https://riot-geo.pas.si.riotgames.com/pas/v1/product/valorant", headers=header, json=data)
File "/home/container/.local/lib/python3.12/site-packages/requests/api.py", line 130, in put
return request("put", url, data=data, **kwargs)
File "/home/container/.local/lib/python3.12/site-packages/requests/api.py", line 59, in request
return session.request(method=method, url=url, **kwargs)
File "/home/container/.local/lib/python3.12/site-packages/requests/sessions.py", line 589, in request
resp = self.send(prep, **send_kwargs)
File "/home/container/.local/lib/python3.12/site-packages/requests/sessions.py", line 703, in send
r = adapter.send(request, **kwargs)
File "/home/container/.local/lib/python3.12/site-packages/requests/adapters.py", line 667, in send
resp = conn.urlopen(
File "/home/container/.local/lib/python3.12/site-packages/urllib3/connectionpool.py", line 789, in urlopen
response = self._make_request(
File "/home/container/.local/lib/python3.12/site-packages/urllib3/connectionpool.py", line 536, in _make_request
response = conn.getresponse()
File "/home/container/.local/lib/python3.12/site-packages/urllib3/connection.py", line 464, in getresponse
httplib_response = super().getresponse()
File "/usr/local/lib/python3.12/http/client.py", line 1428, in getresponse
response.begin()
File "/usr/local/lib/python3.12/http/client.py", line 331, in begin
version, status, reason = self._read_status()
File "/usr/local/lib/python3.12/http/client.py", line 292, in _read_status
line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
File "/usr/local/lib/python3.12/socket.py", line 708, in readinto
return self._sock.recv_into(b)
File "/usr/local/lib/python3.12/ssl.py", line 1252, in recv_into
return self.read(nbytes, buffer)
File "/usr/local/lib/python3.12/ssl.py", line 1104, in read
return self._sslobj.read(len, buffer)

why im getting this strange error