#Basic Pycord Help

1 messages · Page 44 of 1

rain dune
#

does it has something to do with asyncpg?

warm linden
#

are user-installed apps available for pycord?

little cobalt
sly karmaBOT
warm linden
little cobalt
warm linden
shell radish
little cobalt
#

@warm linden ^

warm linden
#

oh thanks guys

#

imma try it now

#

idk why im getting this
```AttributeError: module 'discord' has no attribute 'IntegrationType'``

little cobalt
#

Can you show the pip list pls?

fresh sierra
#

how can from the ctx i can get the command as a group since its a group? (prefix)

upper flint
#

How to properly configure a cog_check method in a Cog?
This code:

def cog_check(self, ctx: discord.ApplicationContext):
    if ...:
        raise NotInHelpForum
    return True

async def cog_command_error(self, ctx: discord.ApplicationContext, error: Exception):
    if isinstance(error, NotInHelpForum):
        await ctx.respond("...", ephemeral=True)

Instead of replying to user that he cannot execute a command throws this in the console:

warm linden
fresh sierra
#

not directly discord

sage tendon
nocturne steppe
#

how to make my slash commands work on any chat with the "Use app anywhere"?

sage tendon
#

You need something that isn't in stable pycord yet

quartz umbra
#

hi i'm using cogs to organise my code for the first time. When making a slash command, i have a few questions that I don't really get from docs:

  1. How do I set description of the command
  2. Can i still pass ctx as an arg?
fresh sierra
#
  1. yes and you will need to do it
quartz umbra
quartz umbra
#

wait 1 more question lol

#

do i need to set guild_ids here aswell?

#

(it's a small bot)

fresh sierra
#

only if u want to have hidden slash

#

in some guild

lapis dock
#

If you only want your commands to be in specific servers yes you will need to add guild_ids

quartz umbra
#

I heard if you don't put it, it takes upto 2 hours for the command to register

cloud bloom
lapis dock
#

not anymore it is only 1-2 min now most of the time

cloud bloom
#

just refresh client side right after to make sure it works

quartz umbra
cloud bloom
#

I have my bot in ~100 servers and it's not that long

#

if you have it in one server I'm sure it'll be pretty fast

quartz umbra
#

lol, last time i made discord bots frequently was when slash commands were just introduced

#

so, i'm not the most updated

cloud bloom
quartz umbra
cloud bloom
#

same same

#

I don't think this is a particularly new thing

#

time wise

quartz umbra
#

damn

cloud bloom
#

idk

sage tendon
cloud bloom
#

How do I check perms based off of the: 'permissions': '2251799813685247', with Pycord?
given from:

{'id': '1044711937956651089', 'name': 'Nestling Bot', 'icon': '494e022f474aa71a77dd55d5322847a9', 'owner': True, 'permissions': '2251799813685247', 'features': ['NEWS', 'COMMUNITY', 'WELCOME_SCREEN_ENABLED', 'MEMBER_VERIFICATION_GATE_ENABLED', 'PREVIEW_ENABLED', 'CREATOR_ACCEPTED_NEW_TERMS', 'CREATOR_MONETIZABLE_PROVISIONAL', 'CHANNEL_ICON_EMOJIS_GENERATED', 'GUILD_ONBOARDING', 'SOUNDBOARD', 'GUILD_ONBOARDING_HAS_PROMPTS', 'GUILD_ONBOARDING_EVER_ENABLED', 'GUILD_SERVER_GUIDE']}

I'm using Oauth2 to get the user's token and then getting what guilds they're in with the bot. Then I want to check if they have at least manage server or higher.
Does Pycord have a way to do this based off of the value given by the API?

lapis dock
lapis dock
#

Note the int vs string there

cloud bloom
#

it'd raise an error if I inputted the wrong thing though right

lapis dock
#

not sure

cloud bloom
#

o

#

does this check overwritten perms like admin

#

if I check for manage server

lapis dock
#

I dont think so

cloud bloom
#

o it works

#

wait lemme test it on another server

upper flint
quartz umbra
#

Hi, can somebody help me resolve this error?

discord.errors.ExtensionFailed: Extension 'cogs.config_cog' raised an error: ImportError: attempted relative import beyond top-level package

This is from trying to use relative imports inside a cog. From the error, i understand that it is not allowed to use relative imports in cogs, but, how else can I achieve the same behaviour?

This is the line: ```py
from ..helpers import config_helper

#

This is my full directory tree: ```
.
├── LICENSE.txt
├── README.md
├── init.py
├── pycache
│ ├── drawer.cpython-311.pyc
│ ├── firebase_helper.cpython-311.pyc
│ └── helper.cpython-311.pyc
├── assets
│ ├── JosefinSans.ttf
│ ├── pycache
│ │ └── drawer.cpython-311.pyc
│ ├── axe_icon.png
│ ├── crystal_icon.png
│ ├── dia_pot_icon.png
│ ├── drawer.py
│ ├── leaderboard.png
│ ├── neth_pot_icon.png
│ ├── smp_icon.png
│ ├── sword_icon.png
│ └── uhc_icon.png
├── cogs
│ ├── init.py
│ ├── pycache
│ │ ├── init.cpython-311.pyc
│ │ └── config_cog.cpython-311.pyc
│ ├── config_cog.py
│ ├── info_cog.py
│ ├── ranks_cog.py
│ └── stats_cog.py
├── config.json
├── database.db
├── helpers
│ ├── init.py
│ ├── pycache
│ │ ├── init.cpython-311.pyc
│ │ ├── config_helper.cpython-311.pyc
│ │ └── firebase_helper.cpython-311.pyc
│ ├── config_helper.py
│ └── firebase_helper.py
├── main.py
├── requirements.txt
└── service_account.json

#

I was calling the above from the ranks_cog

lofty parcel
#

So you use from helpers import config_helper

upper flint
#

How can I make a clickable link in embed like the one in this picture?

upper flint
upper flint
#

I have a message command that can run in public threads. How can I restrict users from running it if thread is archived?

#

When function starts executing it automatically unarchives the thread. How can I prevent that?

edgy nest
#

You can't, if someone sends a message it un-archives the thread

#

unless i'm misunderstanding

upper flint
#

When sending command it just errors with message "Not enough permissions"

edgy nest
#

You can lock the thread

upper flint
#

Lock?

edgy nest
upper flint
#

And this will prevent any messages from being sent?

#

And interrupt command execution?

#

Alright, seems like it. Thanks

tidal zealot
#

is it intended that when creating a command through the @myCommandGroup.command() wrapper, default_member_permissions is ignored? Thonk

#

or are subcommands not able to have default_member_permissions

fresh sierra
fresh sierra
#

since they are considered as 1 command from discord

tidal zealot
#

yeah I think that's probably the case

fresh sierra
#

you can still use a custom check

#

but will not be invisible

tidal zealot
#

yeah that's what I did - it works fine just doesn't hide the command

#

I think people will survive though

upper flint
#

Can bot rename threads created by other people and not himself?

sage tendon
#

what?

fresh sierra
upper flint
#

Threads, sorry

quartz umbra
#

Hi, what is a setup function in a cog?

#

nvm found it in docs, it's this right?

def setup(bot): # this is called by Pycord to setup the cog
    bot.add_cog(Greetings(bot)) # add the cog to the bot```
Not in the cog class though?
little cobalt
#

.tias

sly karmaBOT
little cobalt
#

^^

quartz umbra
#

fr

#

but like i gotta debug bout 100 more bugs till i could so

#

yea

#

thanks tho

#

yay it works, thank you so much!

#

Hello. I am getting another error which is very easy to understand, but I still do not see why it is being caused. Discord is complaining that all my command names are not unique, but I'm pretty sure they all are - I've triple checked! And I've definitely saved every file, so, what?

sage tendon
#

what did you change since it last worked is always the question

quartz umbra
sage tendon
#

spend 2 minutes more finding the issue then :>

quartz umbra
#

0-0

lapis dock
# quartz umbra no never mind i found it - it wasn't between 2 commands, it was between a comman...

Sometimes writing/talking about your issue makes you realize what went wrong.

Rubber duck debugging is a programming technique used to help with debugging—fixing errors in your code. It involves explaining your code and what you are trying to achieve to a rubber duck, in its literal sense.
Why talk to a duck? I mean, a duck can’t engage you in conversation, or pinpoint a missing semicolon!

The whole point here is that you need to explain your code to something or someone.

The “duck” here could be anything or anyone. It could be a friend or colleague at work. If you’re a remote developer, it could be a flatmate or family member.

It could even be a pet—bunnies and stuffed frogs are acceptable, too.

quartz umbra
rough heron
#
async def process_data(message):
    print("processing")
    mentions = message.mentions
    if len(mentions) <= 2:
        return

for message.mentions, I have some questions.

If the same person is pinged twice, so if I were to do @rough heron @rough heron, would the len(mentions) be one or two?

quartz umbra
#

i guess like?

#

idk

rough heron
#

Valid but still

quartz umbra
#

idk

quartz umbra
lofty parcel
#

And looks like it doesn't duplicate the objects. From a quick test.

sage tendon
#

a set can't have duplicates anyway

lofty parcel
#

But the function already returns 1 member object even if multiple mentions of the same one

sage tendon
#

ah

shadow bear
#

Can you have multiple images in a rich embed?

#

not thumbnails

errant trout
sly karmaBOT
# shadow bear Can you have multiple images in a rich embed?

You can make multiple images appear in a single embed by matching their url attributes

first = discord.Embed(url="https://google.com", description=..., color=...)
first.set_image(url=...)
# etc. etc, do whatever you want with your first embed
second = discord.Embed(url="https://google.com")
second.set_image(url=...)  # do NOTHING else with the second embed
await ctx.send(embeds=[first, second])
```This works for up to 4 images at once.
wise harness
#

Are discord.commands.options not dynamically updated? The default value is set to datetime.datetime.now() but it doesn't seem to dynamically update its value when a slash command is run

sage tendon
#

nope

#

choices and default values are static

wise harness
#

That was a quick reply xD. Alright, thanks.

sage tendon
#

just use None as default and if that option is none, set it to now()

lone hound
#

can I make an application command with spaces in its name like this one, just using the core library? (also this bot (Loritta) was made with Kotlin soooo..)

sage tendon
#

thats a command group

lone hound
#

a

#

learned how to use it. anyways thx!

lofty hedge
#

what is the thing called where you can send a certain response depending the user

#

language

little cobalt
lofty hedge
#

thanks

little cobalt
upper flint
#

How to check if I can send a dm to user?

lapis dock
#

I dont think you can. You justhave to try/except it

upper flint
lapis dock
#

I believe that that function checks to make sure that you have permission to send given content not if you have permission to send in the first place.
IE you could check to see if a message containg embeds and files could be sent in that channel

umbral gazelle
#

Is there an event that passes the guild when the bot starts? I tried on_ready and on_guild_available but they are called a few minutes after startup.

fresh sierra
#

And for which use case (will be easier to help u)

umbral gazelle
umbral gazelle
fresh sierra
fresh sierra
# umbral gazelle Startup checks.

so guild avaible will be the first event where the guild are ready, you can maybe check about the on_connect but im not sure this will work

#

.rtfm on_connect

umbral gazelle
fresh sierra
#

and on_connect should also be trigger when the bot is online

fresh sierra
sage tendon
#

Oh i read that
That tells me absolutely nothing and is about as imprecise as their initial message

deft kestrel
#

there's any example about bot payments?

little cobalt
deft kestrel
sly karmaBOT
#

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

deft kestrel
fresh sierra
deft kestrel
fresh sierra
#

discord.Entitlement

fresh sierra
jagged ledge
#

Is there a way to prevent a user from submitting a modal unless an input field exactly matches a given string?

jagged ledge
#

Good grief! Thank you

sage tendon
#

for what purpose?

jagged ledge
#

I'm trying to write something to manage TTRPG fights for a custom system. I want the GM to be able to invite any player they like to a fight, but only if they can type out the target's raw Discord username verbatim as a confirmation prompt (to avoid people spamming everybody with invites).

sage tendon
#

i dont see how that would slow anyone down

lapis dock
#

I think it would be better for the user experience to just but a cooldown on the invite command

rancid arrow
#

you could always just do nothing if they didn't type it right

jagged ledge
errant trout
sage tendon
#

Isn't that for server subscriptions?

lapis dock
#

I thought bot subscriptions were not available to the public. Only select bots?

errant trout
#

entitlements include application premiums

errant trout
#

subscriptions have been public for a while im pretty sure

#

ok yeah, looking through Entitlements are what you buy in a bot's store, and subscriptions would be SKUs

sage tendon
#

but.. what

errant trout
#

the event is used for both

#

or rather, SKUs and Entitlements are interlinked objects where an SKU is the core while an Entitlement is a specific instance

sage tendon
#

im so glad i dont have any monetization

deft kestrel
errant trout
#

which is why i'm suggesting to use the event

#

i don't have monetization so i don't really know how it'll work, but give it a try anyway

#

oh i guess you can test them by creating test entitlements

echo wraith
#

Let's say I have a backend, and in that backend I need to get things about some guild. I don't believe pycord supports this. Is there a library or way of doing things you would recommend?

little cobalt
echo wraith
#

Like calling the api without bot.run?

little cobalt
#

Yes

echo wraith
#

Wait I completely missed that LMAO

#

no but the token is in bot.run

#

so where do I put it then?

little cobalt
#

And?

echo wraith
#

I need to authenticate w the api

#

Like I run the bot somewhere. And in another place, I need to get stuff from the api

#

But not run the bot and connect to the gateway twice

#

That would make no sense

mossy violet
#

Any reason after using the command successfully two times, it says "the application did not respond"

    'red': ('🟥', 'Surnia in RED ALERT', discord.Color.red()),
    'yellow': ('🟨', 'Surnia in YELLOW ALERT', discord.Color.yellow()),
    'black': ('⬛', 'Surnia in BLACK ALERT', discord.Color.dark_grey()),
    'green': ('🟩', 'Surnia in GREEN ALERT', discord.Color.green())
}```

```@bot.slash_command(description="Set alert level")
@option("level", description="The alert level", choices=["red", "yellow", "black", "green"])
async def alert(ctx: discord.ApplicationContext, level: str):
    if level in alert_data:
        channel = bot.get_channel(ALERT_STATUS_CHANNEL_ID)
        if channel:
            new_name, alert_message, alert_color = alert_data[level]
            await channel.edit(name=new_name)
            embed = discord.Embed(description=alert_message, color=alert_color)
            embed.set_author(name="Computer")
            await channel.send(embed=embed)
            await ctx.respond(f'Channel name changed to {new_name} and alert message sent.', ephemeral=True)
        else:
            await ctx.respond(f'Channel with ID {ALERT_STATUS_CHANNEL_ID} not found', ephemeral=True)
    else:
        await ctx.respond('Invalid alert level', ephemeral=True)```

I've tried adding error messages to appear in my terminal but they don't appear.
echo wraith
echo wraith
#

is that it?

mossy violet
# echo wraith add `await ctx.defer(ephemeral=True)` at the top of your command code please

such as

@option("level", description="The alert level", choices=["red", "yellow", "black", "green"])
async def alert(ctx: discord.ApplicationContext, level: str):
    await ctx.defer(ephemeral=True)
    if level in alert_data:
        channel = bot.get_channel(ALERT_STATUS_CHANNEL_ID)
        if channel:
            new_name, alert_message, alert_color = alert_data[level]
            await channel.edit(name=new_name)
            embed = discord.Embed(description=alert_message, color=alert_color)
            embed.set_author(name="Computer")
            await channel.send(embed=embed)
            await ctx.respond(f'Channel name changed to {new_name} and alert message sent.', ephemeral=True)
        else:
            await ctx.respond(f'Channel with ID {ALERT_STATUS_CHANNEL_ID} not found', ephemeral=True)
    else:
        await ctx.respond('Invalid alert level', ephemeral=True)```
?
mossy violet
#

I just get "Bot is thinking..." forever

echo wraith
mossy violet
#

Nope, the only message in my terminal is "Bot##### is online"

deft kestrel
#

ik this is kinda weird but why i cant my pycord code on a VM

sly karmaBOT
deft kestrel
# echo wraith wdym

when i run it in VM while it was putted into pyinstaller it errors with ```
Traceback (most recent call last):
File "aiohttp\connector.py", line 1025, in _wrap_create_connection
File "asyncio\base_events.py", line 1149, in create_connection
File "asyncio\base_events.py", line 1182, in _create_connection_transport
File "asyncio\sslproto.py", line 578, in _on_handshake_complete
File "asyncio\sslproto.py", line 560, in _do_handshake
File "ssl.py", line 917, in do_handshake
ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1000)

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

Traceback (most recent call last):
File "bot.py", line 92, in <module>
File "discord\client.py", line 766, in run
File "discord\client.py", line 745, in runner
File "discord\client.py", line 708, in start
File "discord\client.py", line 562, in login
File "discord\http.py", line 420, in static_login
File "discord\http.py", line 285, in request
File "aiohttp\client.py", line 1197, in aenter
File "aiohttp\client.py", line 581, in _request
File "aiohttp\connector.py", line 544, in connect
File "aiohttp\connector.py", line 944, in _create_connection
File "aiohttp\connector.py", line 1257, in _create_direct_connection
File "aiohttp\connector.py", line 1226, in _create_direct_connection
File "aiohttp\connector.py", line 1027, in _wrap_create_connection
aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to host discord.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1000)')]

which means that it cant connect to discord.com
#

even when i run it on my normal hardware it works

mossy violet
echo wraith
mossy violet
# echo wraith set logging to debug and run the command once

Ah, looks like they're being rate limited.

DEBUG:discord.http:PATCH https://discord.com/api/v10/channels/1257959406549864471 with {"name":"\ud83d\udfe9"} has returned 429
WARNING:discord.http:We are being rate limited. Retrying in 433.92 seconds. Handled under the bucket "1257959406549864471:None:/channels/{channel_id}"```
mossy violet
#

Odd, considering i have only ran the command a handful of times over the period of 10ish minutes. Thanks!

echo wraith
mossy violet
#
from discord import option
import logging

# Initialize the bot
bot = discord.Bot()
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger('discord')
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w')
handler.setFormatter(logging.Formatter('%(asctime)s:%(levelname)s:%(name)s: %(message)s'))
logger.addHandler(handler)

GUILD_ID = XXX
TOKEN = 'XXX'
CHANNEL_ID = 1252966014224826418
ALERT_ROLE_ID = 1252630357493420102
ALERT_STATUS_CHANNEL_ID = 1257959406549864471

# Autocomplete dictionaries
DIVISION = {
    "Command": 1252630419141300408,
    "Operations": 1252630944863617159,
    "Science": 1252631086010470544
}

DEPARTMENT = {
    "Command": 1252631629831213078,
    "Tactical": 1252631775822217287,
    "Intelligence": 1252631874543554582,
    "Diplomatic Corps": 1252632097634517204,
    "Science": 1252633011996856320,
    "Medical": 1252633127319240724,
    "Research & Development": 1252633752979505286,
    "Operations": 1252633283557330997,
    "Engineering": 1252633399886348389,
    "Security": 1252633479091322950
}

RANK = {
    "Captain": 1252812416073597090,
    "Commander": 1252812458729406595,
    "Lieutenant Commander": 1252812510508351549,
    "Lieutenant": 1252812578631979049,
    "Lieutenant Junior Grade": 1252812624337567934,
    "Ensign": 1252812811331964938
}

alert_data = {
    'red': ('🟥', 'Surnia in RED ALERT', discord.Color.red()),
    'yellow': ('🟨', 'Surnia in YELLOW ALERT', discord.Color.yellow()),
    'black': ('⬛', 'Surnia in BLACK ALERT', discord.Color.dark_grey()),
    'green': ('🟩', 'Surnia in GREEN ALERT', discord.Color.green())
}



@bot.slash_command(description="Set alert level")
@option("level", description="The alert level", choices=["red", "yellow", "black", "green"])
async def alert(ctx: discord.ApplicationContext, level: str):
    await ctx.defer(ephemeral=True)
    if level in alert_data:
        channel = bot.get_channel(ALERT_STATUS_CHANNEL_ID)
        if channel:
            new_name, alert_message, alert_color = alert_data[level]
            await channel.edit(name=new_name)
            embed = discord.Embed(description=alert_message, color=alert_color)
            embed.set_author(name="Computer")
            await channel.send(embed=embed)
            await ctx.respond(f'Channel name changed to {new_name} and alert message sent.', ephemeral=True)
        else:
            await ctx.respond(f'Channel with ID {ALERT_STATUS_CHANNEL_ID} not found', ephemeral=True)
    else:
        await ctx.respond('Invalid alert level', ephemeral=True)


@bot.event
async def on_ready():
    print(f'Bot is ready as {bot.user}')

bot.run(TOKEN)  # Replace with your bot token```
#

any clue what it could be?

echo wraith
mossy violet
#
  1. No
  2. This one's hosted on the same PC i'm typing on rn
deft kestrel
echo wraith
#

Yeah

mossy violet
#

👍 🙏 I appreciate yall

echo wraith
#

@deft kestrel can you run ls /usr/lib/ssl/certs? Do you get an output or not? No need to send it

deft kestrel
deft kestrel
deft kestrel
echo wraith
#

Ok

deft kestrel
echo wraith
deft kestrel
#

mhm

#

A WINDOWS VM

echo wraith
# deft kestrel mhm

I have no idea honestly, that looks wierd, but probably the issue is broader than pycord only.

deft kestrel
mossy violet
#

What is the ratelimit? I've sent the command 3 times in the span of a minute and it's rate limited me again

echo wraith
mossy violet
#

Ah I gotcha, danke

echo wraith
mossy violet
#
aiosignal==1.3.1
attrs==23.2.0
blinker==1.8.2
click==8.1.7
colorama==0.4.6
Flask==3.0.3
frozenlist==1.4.1
idna==3.7
itsdangerous==2.2.0
Jinja2==3.1.4
MarkupSafe==2.1.5
multidict==6.0.5
py-cord==2.5.0
Werkzeug==3.0.3
yarl==1.9.4```
echo wraith
#

just wanted to see pycord version

mossy violet
#

mhm

echo wraith
#

But this is wierd

mossy violet
#

Yea

mossy violet
sage tendon
#

show what you mean

mossy violet
# sage tendon show what you mean
WARNING:discord.http:We are being rate limited. Retrying in 68.41 seconds. Handled under the bucket "1257959406549864471:None:/channels/{channel_id}"```
sage tendon
#

are you renaming channels?

mossy violet
#

I am

sage tendon
#

Yea, channel renames have extremely low ratelimits

#

I think twice per 10 minutes

#

just avoid it if possible lol

mossy violet
#

Ohhh, that makes more sense then. I thought I was doing something wrong! I think for my use-case I won't need to do it more than once every hour or so. And only then for like 6 hours every week

mossy violet
#

I know a very basic question, but I'm rather new to python in general. is it possible to separate the different commands into different files from the main.py file?

frail basin
#

You should look into cogs

mossy violet
#

COGS, that's what I was looking for. I appreciate that so much

errant trout
# echo wraith I just found out there is `await client.login()`

if you want to use the api without connecting, use client.login and then refer to http.py to use the relevant methods. We cannot assist you with anything else as this is undocumented behavior, but here's an example py client = discord.Client() await client.login(token) await client.http.send_message(channel_id, "...")

echo wraith
#

And most of what I need to do is fetch things so it should not be too hard

lethal loom
#

hi, why i dont get the print in my console by the setup hook? can wehere helop me pls
Bot.py

class Bot(commands.Bot):
    def __init__(self):
        intents = discord.Intents.all()
        command_prefix = commands.when_mentioned_or("-")
        super().__init__(command_prefix=command_prefix, intents=intents)

    # Cog Loader
    async def setup_hook(self):
        print("Hook: Setup")

    async def on_ready(self):
        # This is without the Hook but i need a start first before the botsa starts
        await youtube_db.setup()```
**start.py**

from bot import Bot
import os
from utils.funcs import get_config

if name == 'main':
bot = Bot()
for filename in os.listdir("./cogs/dev/"):
if filename.endswith(".py"):
bot.load_extension(f"cogs.dev.{filename[:-3]}")

if get_config("bot")["dev_mode"]:
    bot.run(get_config("bot")["token_test"])
else:
    bot.run(get_config("bot")["token_privat"])
fresh sierra
lethal loom
fresh sierra
lethal loom
# fresh sierra Just load ur cog before the bot.run

this example is right?

from bot import Bot
import os
from utils.funcs import get_config

if __name__ == '__main__':
    bot = Bot()
    for filename in os.listdir("./cogs/dev/"):
        if filename.endswith(".py"):
            bot.load_extension(f"cogs.dev.{filename[:-3]}")

    if get_config("bot")["dev_mode"]:
        bot.run(get_config("bot")["token_test"])
    else:
        bot.run(get_config("bot")["token_privat"])
fresh sierra
lethal loom
fresh sierra
lethal loom
#

a ok thx

mossy violet
#
            await message.remove_reaction(payload.emoji, user)
            await user.send("Message A", ephemeral=True)
        else:
            await user.send("Message B", ephemeral=True)```

So it's giving me an error when I try to use the ephemerals. What's the correct way of going about this?

Error:
```Ignoring exception in on_raw_reaction_add
Traceback (most recent call last):
  File "C:\Users\tapie\Documents\TestBot\.venv\Lib\site-packages\discord\client.py", line 400, in _run_event
    await coro(*args, **kwargs)
  File "c:\Users\tapie\Documents\TestBot\Cogs\test.py", line 84, in on_raw_reaction_add
    await user.send("Message B", ephemeral=True)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Messageable.send() got an unexpected keyword argument 'ephemeral'```
sage tendon
#

You cant make normal messages ephemeral

mossy violet
#

Right,

#

Would ctx.send be more appropriate?

sage tendon
#

you cannot make normal messages ephemeral :)

#

.send is a normal message

#

only interaction responses can be ephemeral

mossy violet
#

Ohhh, I see now. Appreciate it.

sage tendon
#

also, you dont have a context in events lol

tranquil jolt
#

This should be a simple one to solve, yet currently being a lil bit smooth brained lmao

I followed the installation guide found on the docs website, got my venv setup and such, yet the simple bot example won't run as it's unable to find the 'discord' module 🤔 My previous bot version was in discord.py, which worked with minimal issue, so i'm not sure whats exactly wrong.

my venv's python version is 3.12.3, and my pip list is as follows:

lofty parcel
#

You shouldn't have discord and py-cord

#

discord is discord.py and conflicts with the library

sage tendon
#

Uninstall both and only install py-cord

tranquil jolt
#

Still has the same issue unfortunately :(

sage tendon
#

did you uninstall both?

tranquil jolt
#

Even threw in a quick restart to make sure 🫡

#

yea

#

uninstalled py-cord, and discord, then reinstalled py-cord

sage tendon
#

make sure its actually using the venv then

#

it might be using the globally installed packages where you still have both installed

#

or none

tranquil jolt
#

🫡

#

it wasn't using the venv oddly

sage tendon
#

Thats why i have no idea how to use venvs

#

Pycharm says it handles it, and it does, and thats all i need to know

#

(all the venv shit)

tranquil jolt
#

I ended up using anaconda at one point for a university AI class, and in the end it bit me in return because it caused a confliction issue and refused to install correct package versions and such :P

sage tendon
#

I've actually now looked up how to create a venv
amazing

#

actually not as hard as i thought

tranquil jolt
#

Does anyone happen to know if it's possible to get the legacy username of a user? I'd have imagined it'd be under ctx.flags, but it doesn't appear to be :')

little cobalt
#

Its pretty simple

edgy nest
#

python -m venv <dir>

echo wraith
nova epoch
# tranquil jolt Does anyone happen to know if it's possible to get the legacy username of a user...

From discord.User, you can retrieve:

  • discriminator - the #1234 from the old usernames system. Will be 0 if the user has migrated to an @username.
  • is_migrated - a boolean value showing if the user has an @username or not.

From discord.User.public_flags.all(), you can retrieve a user's flags (essentially badges) in which you could maybe fish out their legacy username#1234, if they have that badge enabled in their settings.

I haven't done any testing on this, it's purely theory, so it might not work. I think it could be worth a try, though, if it's really important.

sage tendon
sage tendon
fresh sierra
#

almost every

#

bot still got them

sage tendon
#

This isn't about bots

nova epoch
# sage tendon discriminators are gone. every user is migrated.

I know, I figured it was worth putting there still though because the discriminators are still kinda relevant (for app users)
The main point of that was the discord.User.public_flags, which I have now done testing with - there's nothing to do with legacy usernames

tranquil jolt
#

Damn thats kinda disappointing, as some website profiles that allowed discord social links may have an old reference to a users legacy profile, rather than having been retroactively changed post-legacy username removal. Especially as how legacy username may not always be the same username as current, kinda disappointing its not even grabbable through the public flags :’)

sage tendon
#

it's because you should never, ever use anything but the user ID to reference a user

#

if you only ever used user IDs there is absolutely no issue

tranquil jolt
#

Unfortunately in this case (speedrun.com) i don’t believe it’s possible to go from website social link -> discord userID

sage tendon
#

ah

#

yea but I get you
a lot of sites for discord stuff didn't even update to pomelo after all this time
it's not an issue it's just, "wtf are you even doing"

tranquil jolt
#

In the case of speedrun.com, they’re typically quite slow on the push to new features/updates. I believe the whole website staff consist of like… 6 or 7 people 💀

#

But yeah, curious how legacy username isn’t a public flag you can grab, given that it is technically a public flag

sage tendon
#

I think because they just don't want discriminators used for users anymore, at all

tranquil jolt
#

Does anyone happen to know of a faster way to respond from a command than ctx.respond? Felt my bot was pretty slow, so i've timed each chunk and the slowest by far is right at the end when the bot does await ctx.respond("Message")

0.17900514602661133   - getting user profile information from speedrun.com
0.0                   - checking SRC discord social-link
0.38216614723205566   - performing an account age check (0.0 from isolated chunk timing), and ctx.respond("Message")
#

ping is super low too

sage tendon
#

no

#

where is your server located

#

or you if you run it locally

tranquil jolt
#

it's being ran locally

sage tendon
#

where are you located then

tranquil jolt
#

Scotland 🫡

sage tendon
#

hm

tranquil jolt
sage tendon
#

think thats reasonable

#

never measured it myself

#

and responding to an interaction does a fair bit

rugged lodgeBOT
#

earth round?
Most probably.

red mist
#

Yes

#

Takes a bit for me too

#

never measured it but if it takes infact too long you might want to use defer at some point

sage tendon
#

its normal

#

it goes from the PC its hosted on > discord > ??? > your PC again

shell radish
#

pc > man (n times) > underwater cable > man (n times) > cloudflare > man (n times) > discord > back or something

sage tendon
#

man?

shell radish
#

metropolitan area network

#

you may have heard of LAN

echo wraith
#

Is there an accurate-ish and efficient way of getting a count of online members vs all members in a guild?

#

I feel like iterating over members is wierd, and don't see how all members would be cached by pycord

sage tendon
#

well, they are lol

#

guild.members

loud kayak
#

Helpers feel free to correct me if I’m wrong I haven’t touched any code in a year

errant trout
#

that is true, all guild members are cached by default, but what they want also exists separately

errant trout
#

if you don't want to do fetches then filtering cached members by status would be better

#

(also fun fact, this works for guilds the bot isn't in by using Client.fetch_invite instead)

loud kayak
echo wraith
#

Thanks both of you for the help

weary meteor
#

hi all, so lets say I have a button which will change its logic based off an arg i pass into the constructor, i want this button to be persisten so id need to subclass it into a view, now how can i make it so it stays persistent and it keeps the arg and does the logic i need

#

basically one button that acts dynamically based off the arg i give it

fresh sierra
#

yes its possible

#

just pass the arg inside the class

#

for example if you need to pass a guild config :
for guild in bot.guilds:
bot.add_item(View(guild.id))

atomic fern
#

is this a bug?

    
  class ConverterFlags(commands.FlagConverter, prefix="--", delimiter=" "):
    member: discord.Member
    num: int
    channel: discord.TextChannel
    
  @commands.command()
  async def test(ctx, *, flags: ConverterFlags):
    await ctx.reply(f"Channel: {flags.channel}, Num: {flags.num}, Member: {flags.member}.")
Failed to load extension cogs.Testing. Extension 'cogs.Testing' raised an error: TypeError: F
lag.__init__() got an unexpected keyword argument 'name'
upper flint
#

Is it guaranteed that "on_ready" event will fire ONLY after all cogs and extensions have been loaded?

#

In other words, is it guaranteed that all listeners in cogs will be called?

sage tendon
#

yea

#

cogs have to be loaded before on_ready

upper flint
#

In docs it says that discord.Cog.listener() is equivalent to bot.listen(), but there is no once parameter in it. Is it just a typo or once parameter is not intended here?

sage tendon
#

I don't think it does actually, but try it

#

if not, it takes seconds to write that yourself

wild prairie
#

How can I get attachments sent with slash commands (through urls)? I'm trying ctx.message.attachments, but ctx.message is None.
They aren't ONLY posting images though, so I can't just assume the text is an image

sage tendon
#

The attachment is in the option you let the user attach the image with

#

or wdym through urls

wild prairie
#

I have a slash command with a contents field that users can post image urls to (as far as I know, you can't paste images to slash commands). I want to get that image

fresh sierra
#

how with autocomplete to get the first option chosen by the member ?

sage tendon
#

ohh, wait, i misunderstood i think

fresh sierra
#

ctx.options something ?

wild prairie
#

They aren't ONLY posting images though, so I can't just assume it's an image

fresh sierra
#

.rtfm original_message

sage tendon
wild prairie
sage tendon
#

yea well what do you want me to do about it lol
guess you'll have to find out from the url's ending

wild prairie
fresh sierra
#
message = await ctx.interaction.original_message()
print(message.attachments)
fresh sierra
sage tendon
#

you are literally giving me an unsolvable problem
if you dont know if its an image then how the fuck am i supposed to fix that

#

and your question was anything but clear, tbh

#

because i still have zero clue what even happens in your command

wild prairie
wild prairie
sage tendon
#

isnt that what contains the attachment according to you tho

fresh sierra
wild prairie
fresh sierra
sage tendon
#

can you show us what your command looks like in discord

wild prairie
#

/add_quote quote_name:Metal Monsters quote_content:Cool monsters: https://cdn.discordapp.com/attachments/902573110409175130/1258666123075915817/unknown.png?ex=6688dfac&is=66878e2c&hm=42f7b607274260d74c28bd1a5edc53883bb71922d88bbd08417f7cd90821f501&

Given this, I want to get the attachment's url. Except, I don't want to start searching for urls because it may not pan out that way. I only want to get what discord recognizes as attachments

fresh sierra
#

also what should i use here to get emoji from the guild + unicode

fresh sierra
wild prairie
#

Maybe I'm misunderstanding how discord slash commands work

sage tendon
#

You can let user upload images of course

#

well, files
you cant restrict it to images

wild prairie
#

oh, nice!

#

that's exactly what I need

sage tendon
#

discord.Attachment is the option type for that

sage tendon
#

for the unicode, just, use the character in the string lol

fresh sierra
#

like for the user dont just put a random string

#

but i guess there is just no possibility to go that by itself

#

i will make a function

sage tendon
fresh sierra
sage tendon
#

and limit the input length to 1

sage tendon
fresh sierra
#

its just not possible, but a simple funct will sovle that

wild prairie
#

Is there a way to make one OR another slash command option required?

sage tendon
#

no

#

just handle it yourself in the code

fresh sierra
#

like if you mean put some options requiered and other not

#

yes you can

sage tendon
#

they mean either this or that option

wild prairie
fresh sierra
#

o

#

so yes no

wild prairie
#

it's fine

sage tendon
#

would be cool but discord completely forgor about slash command stuff

#

or modals

#

or anything

fresh sierra
#

can autocomplete display custom emoji ?

sage tendon
#

no

#

at least i'm 99% sure

fresh sierra
#

sad

#

slash with just a little bit more of caring can be so much better

sage tendon
#

but doesnt make money

errant trout
#

(note that it will trigger again on cog reload because there's no system for it to behave otherwise)

trim bison
#

what should i change in order to make dynamic cooldowns work??

@commands.dynamic_cooldown(cooldowns.report_cooldown, commands.BucketType.user)
@client.slash_command(name="report", description="Reports user for an inappropriate behavior.")
from discord.ext import commands
from discord import ApplicationContext

staff = [857993843566968862]

def report_cooldown(ctx:ApplicationContext):
    if ctx.author.id in staff:
        return None
    else:
        return commands.Cooldown(3, 86400)

Please ping on reply, thanks.

trim bison
errant trout
trim bison
#

@client.slash_command(name="report", description="Reports user for an inappropriate behavior.") first?

trim bison
#

Welp, It worked with normal commands.cooldown before, ill try gimme sec.

#

Nope, still the same...

sage tendon
#

show your code

trim bison
#
@mass.command(name="lookup", description="Mass-lookups for threats in your server.")
@commands.dynamic_cooldown(cooldowns.mass_lookup, commands.BucketType.guild)
async def mass_lookup(ctx:discord.ApplicationContext, minimum_violations:discord.Option(choices=["1", "2", "3", "4", "5", "6"])): #type: ignore
def mass_lookup(ctx:ApplicationContext):
    if ctx.guild.id in guilds:
        return None
    else:
        return commands.Cooldown(1, 259200)
#

(different command, same issue)

#

Okay, I just noticed that different cooldowns work for discord.BucketType.user not guild

#

Oh

#

My

#

God

#

Sorry guys xD

trim bison
sage tendon
#

i never knew there was dynamic cooldowns btw

#

definitely useful for my bot

shell radish
#

there's no shot

sage tendon
#

?

trim bison
little cobalt
sage tendon
#

all good

trim bison
#

dammn this is so fire 🔥

#

messed up footer dgaf

shell radish
#

1 culprit(s)
c'mon, just do it properly

trim bison
#

ggah ok

#

as you wish

fresh sierra
trim bison
#

Different cooldowns for different users/guilds basically what ever you want.

lapis dock
#

Dynamic cooldown does not work per guild?

#

seems like a missing feature

sage tendon
trim bison
#

buckettype guild

lapis dock
#

ah ok

trim bison
#

commands.CommandOnCooldown?

sage tendon
#

how do you automatically send that cooldown embed

trim bison
#

exception

sage tendon
fresh sierra
trim bison
#

yes

fresh sierra
#

Seems nice to prevent spammer as member for example

trim bison
#

yeah, or premium features

fresh sierra
#

Yeah true

trim bison
#

Okay, now, the cool part, how do I add one usage to the user?

report.cooldown.update_rate_limit(int(report.cooldown.get_tokens())+1)

is this the correct usage?

#

ping on reply pls

echo wraith
#

Do approximate_member_count or approximate_presence_count require the GUILD_MEMBERS intent?

echo wraith
#

But wanted to be sure

fresh sierra
#

and so i guess the opposite

#

if u want i can try it quickly

echo wraith
fresh sierra
#

ok let my 5s

echo wraith
#

cuz i have not bot to test quickly, and discord's docs don't tell anything clear. Tho I assume it means intents aren't required, which would not surprise me since member count does not give you the member object itself

fresh sierra
#

let me try with intents

#

even with intents it return me None

#

mb i didnt read the doc

#

wait

echo wraith
fresh sierra
echo wraith
fresh sierra
#

yep

#

so intents are not needed

echo wraith
fresh sierra
#

i used intents.default()

echo wraith
#

At least that

#

cuz discord would NEVER have given me the intents for my dumb feature

fresh sierra
echo wraith
fresh sierra
sly karmaBOT
fresh sierra
#

and tell us

trim bison
#

yeah, thats the point, it didnt

fresh sierra
#

sad

#

i cant really try it because i dont have ur logic

trim bison
#

?

fresh sierra
#

like i never used dyanmic cooldown

trim bison
#

i am talking about any cooldown 💀
Application Command raised an exception: AttributeError: 'NoneType' object has no attribute 'update_rate_limit'

fresh sierra
#

let me try

#

@trim bison can you send me how u have setup ur cooldown pls ?

trim bison
#

sure

fresh sierra
#

found it dw

#

it was in the chat

trim bison
#

oh

#

yeah

fresh sierra
# trim bison

strange that for prefix commands it works, but not for slash command

trim bison
#

how did you find out

fresh sierra
#

cooldown just does not work for subcommand

#

without group

#

with group :

#

i think its like for the default permission, you cant handle it for subcommand but you have to handle it for the whole command

#

or you do a custom function

trim bison
#

how the fuck

trim bison
#

pls

fresh sierra
#

well no got the same error

#

i will try to debug that

trim bison
#

k

fresh sierra
#
Resetting the discord slash command cooldown is currently not possible.
#

from a stack overflw

#

idk if its up to date

#

here the update token rate

#
    @subcommand("debug")
    @commands.slash_command()
    @commands.cooldown(1, 3600, commands.BucketType.guild)
    async def test(self, ctx: LumabotContext, test: str = None):
        self.test.cooldown.update_rate_limit(int(self.test.cooldown.get_tokens()) + 1)
        await ctx.respond(self.test.cooldown.get_tokens())
#

does not work

#

i guess we just cant update it like so so you will have to handle it differently in ur function @trim bison

trim bison
#

wait so if it is a regular cooldown it is going to work?

sage tendon
fresh sierra
#

Maybe you can use reset_cooldown

fresh sierra
trim bison
fresh sierra
#

Yep if it was the question with or without sub command it does not updated the cooldown

errant trout
#

if you have the subcommand decorator, you don't need slash_command

sage tendon
errant trout
#

and run update_rate_limit with no params

fresh sierra
fresh sierra
trim bison
trim bison
fresh sierra
#

im doing like so normally

errant trout
#

what is subcommand

#

it's not even a decorator in the base library

fresh sierra
#

A custom decorator

#

To create sub command

#

It will here put the test command inside the debug group

#

For both prefix and slash

#

And lumabot.command will add the prefix and slash command

#

you might use either that : self.command.reset_cooldown(ctx)
or just handle it inside ur function

trim bison
errant trout
#

command.reset_cooldown

trim bison
#

yeah, but i set it to 3 per day, so when someone is on 1 a day, it will reset back to 3, which can be abused

fresh sierra
#

if you set it 3 per day

#

why do you want to update the token ?

trim bison
#

so when user runs /report <anyone from staff> or /report <himself> it will give him the token back

fresh sierra
#

and in which case you want to not cooldown him then ?

trim bison
#

bro wtf

#

when user reports staff member or himself give him back the token

fresh sierra
#

like if when it does
/report it remove his cooldown each time

trim bison
#

no just when reports self or staff

fresh sierra
#

why put the cooldown since it will be remove for this member if you prefer

errant trout
#

handle it in your dynamic cooldown instead

trim bison
#

how?

fresh sierra
#

but is that a lib issue ?

trim bison
#

i check docs like 5 times nothing

sage tendon
#

or am i missing something

trim bison
#

no, when the cooldown is already active you cannot do that

#

example: 2 tokens out of 3

#

cant check for tokens as cmd.cooldowns is null

fresh sierra
#

cant you save that in a dict ?

#

self.reports = {}
and then check for each one

trim bison
#

no bro just

#

i want discord to handle that as they already handle cooldowns

fresh sierra
#

yeah but here it doesnt work right

errant trout
#

it's a little out of the way, but in a slash command you can parse ctx.interaction.data["options"] to get every argument passed

sage tendon
#

i think your requirements are just way too specific for the library to handle it

errant trout
#

and if so return no cooldown

trim bison
#

oh

errant trout
#

yes, discord parses that as an id

trim bison
#

wait

sage tendon
trim bison
#

you mean

fresh sierra
errant trout
#

oh that's what it's named

trim bison
errant trout
#

in your dynamic cooldown

trim bison
#

in the dynamic cooldown

#

yeah but

fresh sierra
trim bison
#

how

#

do i get

#

user

errant trout
#

as toothy linked above, you access ctx.selected_options

#

just print it and you'll understand the rest

trim bison
#

oh okay

#

is it dict?

errant trout
#

yes

sage tendon
#

check the docs :)

#

its all right there

trim bison
#

too lazy damn

#

thanks

#

brb on my way to check

sage tendon
#

docs should be open whenever you work on a pycord bot :>

fresh sierra
#
def mass_lookup(ctx:ApplicationContext):
    if ctx.guild.id in guilds:
        return None
    elif ctx.author == ctx.selected_options["member"]:
        return None
    else:
        return commands.Cooldown(1, 259200)
#

something like so ig

trim bison
#

yeah, i know lmfao

#

but the problem is

errant trout
#

(i don't think it's actually a dict so double check)

trim bison
#

i understand what your poin is

trim bison
#

but

#

when the cooldown is already active

errant trout
#

i guess a list counts as a dict in json

fresh sierra
#

and reset it then ig

sage tendon
#

actually mb the text is wrong

#

its a list of dicts

errant trout
sage tendon
#

the "returns" text is just worded wrongly

#

but each list item is a dict

errant trout
#

nah it says List[Dict[:class:str, Any]]

trim bison
#

oh okay let me try

sage tendon
#

yea, a list of dicts lol

errant trout
#

which is correct

sage tendon
#

but check the "returns" text above

errant trout
#

oh i see

trim bison
#

[{'value': '857993843566968862', 'type': 6, 'name': 'user'}, {'value': 'Racism', 'type': 3, 'name': 'reason'}]

#

i mean

errant trout
#

it's literally

#

the first one

trim bison
#

what is type?

errant trout
#

ignore it

#

it's just how discord parses types

trim bison
#

i cant use [0] tho

#

cause

#

if

#

i shuffle args

#

wait

errant trout
#

then check the name

trim bison
#

oh shit missed that

sage tendon
#

i imagine your options are required which assures the order is fixed

trim bison
#

are they?

sage tendon
#

you tell us

errant trout
#

you can typically assume they're ordered correctly, but it's good to check name regardless

sage tendon
#

but if the member option is required (which i hope it is) then its always [0]

trim bison
#

you can shuffle args in the cmd

fresh sierra
trim bison
#

but the output remains

trim bison
#

[{'value': '857993843566968862', 'type': 6, 'name': 'user'}, {'value': 'Racism', 'type': 3, 'name': 'reason'}]

fresh sierra
sage tendon
trim bison
#

just did

errant trout
#

you can, but even when you shuffle them discord reorders them

sage tendon
#

yea id imagine its always in the "suggested" order you set in the code

trim bison
#

so ill keep it as [0]

#

hope no issues will come

sage tendon
#

good luck

sly pebble
#

heya, pinpin here, new question for you all: when you're using a slash command how do you make the bot listen for a user's input via reply?

sage tendon
errant trout
#

you'd use bot.wait_for, but generally you're better off using a modal

sage tendon
#

damn nelo cmon

trim bison
#

i knew it would happen

sage tendon
#

i wanted to say that

errant trout
#

then do it smh

sly pebble
#

lol

sage tendon
#

i was too busy being proud of how fast i found it in the docs

sly pebble
#

you're like a pair of hawks

errant trout
sly pebble
#

ok i shouldnt be surprised one of you is a dragon

trim bison
sage tendon
#

w h a t

sly pebble
#

blue jumpscare

sage tendon
#

but i could just use the search

errant trout
#

index is faster

sage tendon
#

still cool where is the link for that on the site

errant trout
#

nowhere

#

it's autogenerated

sly pebble
#

does a modal have some upper limit for the amount of questions you can ask?

#

ah 5 fields

errant trout
#

5

#

yeah

#

discord likes fives

sly pebble
#

should be 4

sage tendon
#

no

sly pebble
#

oh i wouldnt want it to be that way to be helpful

sage tendon
#

don't make modals even worse please

sly pebble
#

i'd want it solely so i can make this joke

#

anywho

#

thanks for the quick answer lol

errant trout
#

just edit the thumb to be out

sly pebble
#

oh true

trim bison
#

my id is the last one

#
print(int(ctx.selected_options[0]["value"]))
print(ctx.author.id == int(ctx.selected_options[0]["value"]))
print(int(ctx.selected_options[0]["value"]) in staff)

778657519476277309
False
False

fresh sierra
#

And also staff

#

To check why it return false

errant trout
#

oh wait

#

different author hmmm

trim bison
#

so

#

alt mentioning this account:

857993843566968862 997570531643629571
False
True

fresh sierra
#

Si its normal ?

trim bison
#

alt mentioning itself:
997570531643629571 997570531643629571
True
False

fresh sierra
#

Like the author and the member are not the same but the member is onside staff

#

Yeah so it works as expected no ?

trim bison
#

i didnt mention anyone

#

else

fresh sierra
#

Idk

trim bison
#

wait lemme test again for 429

#

again?

#

okay i see the issue

#

i know where is the problem now

#

i said that earlier

#

and you forced me to test it xd

fresh sierra
#

Show us the function that handle that

#

What thing ?

trim bison
#

look

#

this report_cooldown is checked only when there is no cooldown

#

when there is any active cooldown for the guild, its just removes one from the rate limit

#

like so

#

2 out of 3 -> api sees that there is an active cooldown so report_cooldown remains unchecked

fresh sierra
#

Can you show us how look the mass lookup ?

trim bison
#
def report_cooldown(ctx:ApplicationContext):
    print(int(ctx.selected_options[0]["value"]), ctx.author.id)
    print(ctx.author.id == int(ctx.selected_options[0]["value"]))
    print(int(ctx.selected_options[0]["value"]) in staff)
    if ctx.author.id in staff:
        return None
    elif ctx.author.id == int(ctx.selected_options[0]["value"]):
        return None
    elif int(ctx.selected_options[0]["value"]) in staff:
        return None
    else:
        return commands.Cooldown(3, 86400)
#

after executing one command with False, False states - next commands remain unchecked

fresh sierra
#

Ok and this is only trigger when there is no cooldown

#

Well I can’t really debug it for the moment so

trim bison
#

Nelo, any clues?

#

prob if there was a way

#

to shorten discord.Members by staff and author

#

OH

#

MY

#

GOD

#

just found vulnerability as fuck

#

you can cross-report users???

sage tendon
#

vulnerability lol

#

thats intended behavior

trim bison
#

oh

#

damn

#

i can just check of the user is in the server 💀

errant trout
#

yeah

errant trout
trim bison
#

now prob nvm

trim bison
#

that would remove one token

sage tendon
#

just handle it Cry

trim bison
#

BRO YOU CANT

#

LITERALLY

sage tendon
#

shrug man just write your own handler

#

you're trying to wrangle pycord so hard here and it aint working

trim bison
#

wdym

#

how do i handle it

#

you cant

trim bison
sage tendon
#

handle cooldowns yourself lol, just write some stuff

#

you have the entirety of python at your disposal, use it

trim bison
errant trout
#

python was never optimal

trim bison
#

as long as discord handles cooldowns its easier and faster

sage tendon
errant trout
#

...this isn't handled by discord, it's handled by the library

sage tendon
#

Save your cooldowns to an sqlite file or whatever, it really isn't magic

#

this needs a custom system. period.

trim bison
#

ahh

#

so it isnt possible?

#

without command.cooldown working?3

sage tendon
#

pycord cooldowns arent made for something like this
I was already surprised dynamic cooldowns were a thing

#

if you really wanna get down to it maybe you can subclass the cooldowns and add the functionality to them but i'd just save the cooldowns somewhere and handle it myself

errant trout
#

it's probably possible but it's painfully hard to debug someone else's code

trim bison
#

can i dm you nelo?

sage tendon
#

and like, after checking the cooldown, you can just throw the cooldown exception yourself lol

#

this takes all of 15m to do

#

and if you look back at the chat we spent a lot of time, only ever coming back to "this doesnt work"

errant trout
#

i don't mind but i'd rather not help in dms, you'd generally be better off reading through the library code itself to see exactly how it works to fit your needs

trim bison
errant trout
#

isee

trim bison
#

thanks, you got all requirements there

sly pebble
#
def date_check(message):
    if message.author.id != initiator:
        return False

    parsed_creation_date = parse(message.content, locales=['en-US'],
                                 date_formats=["%B %d, %Y", "%m %d, %Y", "%B %d %Y", "%m %d %Y"])
    if parsed_creation_date is None:
        return False
    return True
#

i've got this code

#

is there a way to just get the creation date back into the parent function

#

since i know that's gonna shadow

#

i know global exists but idk if there's anything better than that

sage tendon
#

return it? lol

sly pebble
#

its a check in wait for tho

#

does that actually get returned?

sage tendon
#

ah

sly pebble
#

i've got no idea how if so

sage tendon
#

yea, idk then

sly pebble
#

prolly just global then

#

oh wait fuck there's something called nonlocal

#

thats sick

sage tendon
#

what is that

fervent surge
#

whats the best way of specifying interaction contexts in a bridge command?

sage tendon
#

bridge context

fervent surge
#

I mean when using a bridge command like:

@bridge.bridge_command()
async def command(ctx):
    ...

The best way to specify the new interaction contexts and if there's a way for backwards compatibility to ext (prefix) command guild and DM checks

sage tendon
#

bridge context

errant trout
fervent surge
#

I mean how guild_only is now deprecated and contexts are now preferred instead

sage tendon
#

ah

errant trout
fervent surge
#

Cuz currently it's deprecated. And specifying the contexts argument in the bridge.bridge_command() decorator doesn't do the legacy prefix command guild_only and dm_only checks

sage tendon
#

2.6 isn't even out yet

#

and deprecated doesn't mean it doesn't work, it means it might stop working in any version past 2.6

#

i'd say wait for release regardless

fervent surge
#

I seem to of gone off topic. I meant the best way to specify the interaction contexts for bridge conmands

#

Is it just specifying it in bridge.bridge_command? Then I'm gonna make a feature request to make sure there's a way it will work properly with prefix commands

errant trout
#

why yield

wide jasper
fervent surge
#

if it does somehow? send me some example code

errant trout
fervent surge
#

no, thats being deprecated

errant trout
#

Yes, I'm aware

#

We don't have an alternative in bridge yet

fervent surge
#

im talking about a possible feature that will work with the prefix commands that will replace bridge.guild_only

errant trout
#

So just keep using it until we do

fervent surge
#

ok, so there isn't any existing method

errant trout
#

Deprecated features won't be removed without prior warning

fervent surge
#

thats all I wanted to know

errant trout
#

It's also possible we keep the existing bridge.guild_only because bridge is outside of the api scope anyway

#

we'll see ig

wide jasper
#

why i am not able to delete it

errant trout
#

What happens when you print channel.guild

tired lake
#

i have been away from pycord and python for a while. i just reinstalled visual studio code and have Pylcance and the Microsoft Python extennsion. If i do discord.whatever i get drilled down options, but if i do print(message. i get nothing. how can i fix this?

errant trout
sage tendon
#

not just probably

tired lake
#

that worked. i dont remember having to do that before

#

ty

sage tendon
#

you have to

#

because python isn't statically typed

vestal folio
#

how do i write commands in py-cord that work on servers as well as via pn
so slash

#

please ping me

vestal folio
#

private mesage

#

with the bot

fresh sierra
#

do you talk about that ?

#

or about userapp ?

lapis dock
fresh sierra
#

doesnt normal /command appear in private message ?

vestal folio
#

thanks

lapis dock
fresh sierra
mild trout
#

Hi, this may be a stupid question but since my bot is starting to get more and more complex i was wondering what is the best way to move commands/functionalities to different files. If anyone has an example it would be great

sage tendon
#

cogs

silent shore
#

is there a error in pycord?

#

Error: AttributeError: type object 'Interaction' has no attribute 'respond'. Did you mean: 'response'?

#

bot = commands.Bot(
  command_prefix="!",
  help_command=None,
  activity=discord.Activity(type=discord.ActivityType.streaming, name='Made By @Diveer.'),
  status=discord.Status.idle,
  case_insensitive=True,
  intents=discord.Intents.all()
)

@bot.event
async def on_ready() -> None:
  print('Try To Connecting To Discord..')
  print(f'Connected To Discord as {bot.user.display_name}')
  print(f'-' * 50, '\n:arrows_clockwise: | Loading Extensions.')
  
  for filename in os.listdir("./src/commands"):
    if filename.endswith(".py"):
      print(filename)
      print(filename[:-3])
      await bot.load_extension(f"src.commands.{filename[:-3]}")
      print(f'\n:white_check_mark: | Loaded src.commands.{filename[:-3]} Successfully.')
  print(f'-' * 50, '\n:white_check_mark: | Loaded Extensions Successfully.\n\n')
  print(f"! {bot.user} has connected to Discord and Ready To Run")

bot.run(config.TOKEN)```
sly pebble
#

message.channel is not discord.DMChannel

is this the correct way to check if a message sent is outside of dms?

sly pebble
silent shore
sage tendon
silent shore
silent shore
# sage tendon show the full traceback please
Traceback (most recent call last):
  File "c:\Users\ahmed\OneDrive\Desktop\Coding\DiscordBots\Movies\main.py", line 95, in <module>
    import discord.commands
  File "C:\Python312\Lib\site-packages\discord\commands\__init__.py", line 26, in <module>
    from .context import *
  File "C:\Python312\Lib\site-packages\discord\commands\context.py", line 69, in <module>
    class ApplicationContext(discord.abc.Messageable):
  File "C:\Python312\Lib\site-packages\discord\commands\context.py", line 271, in ApplicationContext
    @discord.utils.copy_doc(Interaction.respond)
                            ^^^^^^^^^^^^^^^^^^^
AttributeError: type object 'Interaction' has no attribute 'respond'. Did you mean: 'response'?```
sage tendon
#

what did you last change in your code

silent shore
#

its a new project i didn't change anything

sage tendon
#

oh

#

you cant load your cogs in on_ready

silent shore
#

i have been trying to fix it for like 2 hours or something

sage tendon
#

it must happen before that

silent shore
#

its a stupid error ik, i can't figure it out cuz im tried

silent shore
sage tendon
#

great, but you cant do that if you have application commands in your cogs

#

load them before on_ready

sly pebble
#

just move it out, i have it like this in my code

silent shore
sage tendon
#

ill never understand why people dont just bot.load_extensions("cogs")

sage tendon
silent shore
sage tendon
sly pebble
silent shore
#

File "c:\Users\ahmed\OneDrive\Desktop\Coding\DiscordBots\Movies\main.py", line 95, in <module>
import discord.commands

#

its in a main file

sage tendon
sly pebble
#

oh neat

sage tendon
#

ah
yea

silent shore
sly pebble
#

there's a recursive flag so

#

it can

sage tendon
#

adding the imports would've probably helped lol

silent shore
#

do you have any example bot u sure its running fine, so i can test if the problem is in my discord bot itself

sage tendon
sage tendon
#

show your pip list

silent shore
#

so the problem is my project in dev app?

silent shore
silent shore
# sage tendon show your pip list

aiohttp 3.9.5
aiosignal 1.3.1
attrs 23.2.0
certifi 2024.6.2
charset-normalizer 3.3.2
discord.py 2.4.0
frozenlist 1.4.1
idna 3.7
multidict 6.0.5
pip 23.2.1
py-cord 2.5.0
requests 2.32.3
urllib3 2.2.2
yarl 1.9.4

sage tendon
#

uninstall both that and py-cord and only reinstall py-cord

silent shore
#

ye working now, told you a stupid error