#Basic Pycord Help
1 messages · Page 44 of 1
are user-installed apps available for pycord?
.master
pip install -U git+https://github.com/Pycord-Development/pycord
thanks is there an example of how to use it? the example here https://github.com/Pycord-Development/pycord/pull/2409 isn't available
that is a good question, I dont know if there is an example for it. I never used any user apps
ah alright thanks for the help though!
Pycord, a maintained fork of discord.py, is a python wrapper for the Discord API - Pycord-Development/pycord
@warm linden ^
oh thanks guys
imma try it now
idk why im getting this
```AttributeError: module 'discord' has no attribute 'IntegrationType'``
Can you show the pip list pls?
how can from the ctx i can get the command as a group since its a group? (prefix)
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:
aiohttp==3.9.5
async-timeout==4.0.3
frozenlist==1.4.1
idna==3.7
multidict==6.0.5
py-cord==2.5.0
pymongo==4.8.0
requests==2.32.3
its discordIntegration.IntefrationType
not directly discord
Models are classes that are received from Discord and are not meant to be created by the user of the library. Attributes key, url. Methods def is_animated, async read, def replace, async save, def ...
how to make my slash commands work on any chat with the "Use app anywhere"?
using user app
You need something that isn't in stable pycord yet
try making NotInHelpForum a subclass of CommandError
note i've never used this but this is what i gather from the docs
https://docs.pycord.dev/en/stable/api/cogs.html#discord.Cog.cog_check
https://docs.pycord.dev/en/stable/ext/commands/api.html#discord.ext.commands.check
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:
- How do I set description of the command
- Can i still pass ctx as an arg?
- @discord.slash_command(description=)
- yes and you will need to do it
tysm, same with @ SlashCommandGroup.command too, right?
yes
wait 1 more question lol
do i need to set guild_ids here aswell?
(it's a small bot)
If you only want your commands to be in specific servers yes you will need to add guild_ids
Wait, but I thought you had to put it in every server otherwise it takes a long time for the slash command to register and appear?
I heard if you don't put it, it takes upto 2 hours for the command to register
To be honest, it's not that long
not anymore it is only 1-2 min now most of the time
just refresh client side right after to make sure it works
ye
oh wait, really?
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
lol, last time i made discord bots frequently was when slash commands were just introduced
so, i'm not the most updated
right after discord.py fell?
yep
idk
i've never had commands take more than a second to register
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?
Do I have to check them manually using discord's bitwise docs?
You can create your own permissions object. The first arg is that number
https://docs.pycord.dev/en/stable/api/data_classes.html#discord.Permissions
perms = discord.Permissions(123456)
Ty!
Note the int vs string there
Good catch
it'd raise an error if I inputted the wrong thing though right
not sure
I dont think so
Yes, it worked flawlessly. Thanks a lot!
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
Imports are based off your main file
So you use from helpers import config_helper
How can I make a clickable link in embed like the one in this picture?
Thanks, that worked! I made a mistake by swapping these two, that's why it wasn't working (text)[url] 
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?
You can't, if someone sends a message it un-archives the thread
unless i'm misunderstanding
There is a public thread on a NextJS support server that has this functionality
When sending command it just errors with message "Not enough permissions"
You can lock the thread
Lock?
And this will prevent any messages from being sent?
And interrupt command execution?
Alright, seems like it. Thanks
is it intended that when creating a command through the @myCommandGroup.command() wrapper, default_member_permissions is ignored? 
or are subcommands not able to have default_member_permissions
can you show how u created the group and command ?
i see, and yeah i don’t think sub command have default permission
since they are considered as 1 command from discord
yeah that's what I did - it works fine just doesn't hide the command
I think people will survive though
Can bot rename threads created by other people and not himself?
what?
What is a branches ?
Threads, sorry
aight
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?
.tias
^^
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?
what did you change since it last worked is always the question
no never mind i found it - it wasn't between 2 commands, it was between a command and a slash command group, lol (why is it every time i post a problem here after looking for ages, the second i post it, i find the solution? Lol)
spend 2 minutes more finding the issue then :>
0-0
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.
see? I'm not brain-deprived after all
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?
.tias
I mean, docs says:
A list of Member that were mentioned.
Convert it to a set, remove duplicates. (Assuming the list will contain the member object twice)
And looks like it doesn't duplicate the objects. From a quick test.
a set can't have duplicates anyway
That's why I said convert it to a set lol
But the function already returns 1 member object even if multiple mentions of the same one
ah
.tag embed-images
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.
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
That was a quick reply xD. Alright, thanks.
just use None as default and if that option is none, set it to now()
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..)
thats a command group
what is the thing called where you can send a certain response depending the user
language
ctx.interaction.locale
thanks
that is only user
How to check if I can send a dm to user?
I dont think you can. You justhave to try/except it
I see, okay. Then I'm a bit confused on what exactly does this method do: https://docs.pycord.dev/en/stable/api/models.html#discord.Member.can_send. Can you explain it please?
Models are classes that are received from Discord and are not meant to be created by the user of the library. Attributes key, url. Methods def is_animated, async read, def replace, async save, def ...
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
🤠 👍
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.
What do you mean by invite that pass the guild ?
And for which use case (will be easier to help u)
I didn't say invite.
Startup checks.
event *
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
on_connect is called after a few hours because the bot can reconnect.
but why the bot disconect in the first place ?
and on_connect should also be trigger when the bot is online
for what purpose
.
Oh i read that
That tells me absolutely nothing and is about as imprecise as their initial message
What?
like i wanna do something when someone pay something in the bot
Target not found, try again and make sure to check your spelling.
discord.Entitlement
discord.Entitlement.application_id
discord.Entitlement.delete
discord.Entitlement.deleted
discord.Entitlement.ends_at
discord.Entitlement.guild_id
discord.Entitlement.id
discord.Entitlement.sku_id
discord.Entitlement.starts_at
discord.Entitlement.type
discord.Entitlement.user_id
discord.EntitlementOwnerType
discord.EntitlementOwnerType.guild
discord.EntitlementOwnerType.user
discord.EntitlementType
i mean monetization
i already answerd to ur question
(?)
there is no example but here you have all the info in the doc
discord.Entitlement
.
Is there a way to prevent a user from submitting a modal unless an input field exactly matches a given string?
nope
Good grief! Thank you
for what purpose?
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).
i dont see how that would slow anyone down
I think it would be better for the user experience to just but a cooldown on the invite command
you could always just do nothing if they didn't type it right
That makes more sense. Thank you for the suggestion!
i'm not 100% sure if this works, but try the on_entitlement_create event?
Isn't that for server subscriptions?
I thought bot subscriptions were not available to the public. Only select bots?
dyno
dyno got it for sure
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
but.. what
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
im so glad i dont have any monetization
...i just wanted when someone buy something the bot send a DM to the user
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
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?
Why should py-cord not support that?
Can I do that with pycord?
Like calling the api without bot.run?
Yes
Wait I completely missed that LMAO
no but the token is in bot.run
so where do I put it then?
And?
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
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.
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)```
?
yup
I just get "Bot is thinking..." forever
Do you have any errors in your terminal?
Nope, the only message in my terminal is "Bot##### is online"
ik this is kinda weird but why i cant my pycord code on a VM
.tag logging
Pycord logs errors and debug information via the logging python module. It is strongly recommended that the logging module is configured, as no errors or warnings will be output if it is not set up...
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
Oh yes, I have logging active. You want me to paste it here?
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}"```
mhm
you gotta wait a little
Odd, considering i have only ran the command a handful of times over the period of 10ish minutes. Thanks!
Looks like something in your code is spamming discord with requests
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?
- Are you running other bots?
- Are you running from a server?
- No
- This one's hosted on the same PC i'm typing on rn
then just let it restfor time
Yeah
👍 🙏 I appreciate yall
@deft kestrel can you run ls /usr/lib/ssl/certs? Do you get an output or not? No need to send it
ngl i doubt it will work
im running WINDOWS
that person is running linux
who said im hosting server?
You said it was in a vm
I have no idea honestly, that looks wierd, but probably the issue is broader than pycord only.
ima go to the most trusted thing in the world. stack overview
Good luck
What is the ratelimit? I've sent the command 3 times in the span of a minute and it's rate limited me again
It is dynamic and depends on your bot and other factors
Ah I gotcha, danke
can you give me the output of pip freeze
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```
ok thanks
just wanted to see pycord version
mhm
But this is wierd
Yea
rate limit in what way
I'm testing a new bot, sending ~3 commands a minute and I get rate limited on the outputs for ~500sec
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}"```
are you renaming channels?
I am
Yea, channel renames have extremely low ratelimits
I think twice per 10 minutes
just avoid it if possible lol
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
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?
Yes
You should look into cogs
Cogs, often known as modules or extensions, are used to organize commands into groups. This is useful
COGS, that's what I was looking for. I appreciate that so much
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, "...")
Yeah I did figure it out. Thanks much anyway
And most of what I need to do is fetch things so it should not be too hard
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"])
Setup hook does not exist in pycord
a other version of this i need a load he load before the cog loads
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"])
Yep, you can do if you want
bot.load_extension("./cog.dev", recursive=Trye)
recursive can you tell me what this do i read in the pycord doku but idk what this do
It does every file in ur folder
a ok thx
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'```
You cant make normal messages ephemeral
you cannot make normal messages ephemeral :)
.send is a normal message
only interaction responses can be ephemeral
Ohhh, I see now. Appreciate it.
also, you dont have a context in events lol
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:
You shouldn't have discord and py-cord
discord is discord.py and conflicts with the library
Uninstall both and only install py-cord
Still has the same issue unfortunately :(
did you uninstall both?
Even threw in a quick restart to make sure 🫡
yea
uninstalled py-cord, and discord, then reinstalled py-cord
make sure its actually using the venv then
it might be using the globally installed packages where you still have both installed
or none
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)
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
I've actually now looked up how to create a venv
amazing
actually not as hard as i thought
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 :')
python -m venv env
Its pretty simple
python -m venv <dir>
Until it stops doing it and then it sucks
From discord.User, you can retrieve:
discriminator- the#1234from the old usernames system. Will be0if 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.
what do you mean "legacy username"
discriminators are gone. every user is migrated.
This isn't about bots
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
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 :’)
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
Unfortunately in this case (speedrun.com) i don’t believe it’s possible to go from website social link -> discord userID
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"
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
I think because they just don't want discriminators used for users anymore, at all
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
it's being ran locally
where are you located then
Scotland 🫡
hm
and that's 382ms then?
Evidently so, its quite high for what i’d have expected
think thats reasonable
never measured it myself
and responding to an interaction does a fair bit
earth round?
Most probably.
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
pc > man (n times) > underwater cable > man (n times) > cloudflare > man (n times) > discord > back or something
man?
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
Server members are cached when all guilds are cached upon the bot starting up. Assuming you have chunk_guilds_on_startup still set to True by default, that’s how it behaves. Guilds are chunked, and so are members of said server.
Helpers feel free to correct me if I’m wrong I haven’t touched any code in a year
that is true, all guild members are cached by default, but what they want also exists separately
see approximate_presence_count (it has specific requirements)
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)
Nziie is alive wtf
Ye I’ve been grinding cod
Thanks both of you for the help
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
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))
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'
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?
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?
I don't think it does actually, but try it
if not, it takes seconds to write that yourself
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
The attachment is in the option you let the user attach the image with
or wdym through urls
meaning what?
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
how with autocomplete to get the first option chosen by the member ?
ohh, wait, i misunderstood i think
ctx.options something ?
They aren't ONLY posting images though, so I can't just assume it's an image
because its a response
.rtfm original_message
so.. read the url the user is giving you (?)
#1132206148309749830 message
yea well what do you want me to do about it lol
guess you'll have to find out from the url's ending
yea well what do you want me to do about it lol
tf? I thought my question was quite clear lol. You're not required to answer if you don't know
message = await ctx.interaction.original_message()
print(message.attachments)
????
here you will get the message of the response of the bot
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
if you dont know if its an image then how the fuck am i supposed to fix that
That's why I'm trying to get the attachments, not the text
Doesn't this reference what the bot sent?
isnt that what contains the attachment according to you tho
ctx.message is what the bot sent
oh, then I was using the wrong command entirely
what do you want to do ?
can you show us what your command looks like in discord
/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
also what should i use here to get emoji from the guild + unicode
so monster here is an str and not a discord.Attachment ?
Well, am I able to send an attachment to a slash command?
I figure discord still attaches it, no?
Maybe I'm misunderstanding how discord slash commands work
discord.Attachment is the option type for that
for the unicode, just, use the character in the string lol
my goal is to get both
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
Models are classes that are received from Discord and are not meant to be created by the user of the library. Attributes key, url. Methods def is_animated, async read, def replace, async save, def ...
this fail with unicode emoji
and limit the input length to 1
no clue then
its just not possible, but a simple funct will sovle that
Is there a way to make one OR another slash command option required?
wdym ?
like if you mean put some options requiered and other not
yes you can
they mean either this or that option
I need EITHER my content field required OR my image field required, but not both
it's fine
would be cool but discord completely forgor about slash command stuff
or modals
or anything
can autocomplete display custom emoji ?
but doesnt make money
it's present on master or 2.6 release later
(note that it will trigger again on cog reload because there's no system for it to behave otherwise)
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.
what exactly isn't working
Sorry forgot to specify... I mean it just doesn't give cooldown to anyone.
the command decorator should always be first
@client.slash_command(name="report", description="Reports user for an inappropriate behavior.") first?
always first
Welp, It worked with normal commands.cooldown before, ill try gimme sec.
Nope, still the same...
show your code
@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
this helped thanks :d
there's no shot
?
Yeah I found out today too.
I can give you a example how you can add cooldowns to buttons
all good
1 culprit(s)
c'mon, just do it properly
What is dynamic cooldown and what ur use with it ?
Different cooldowns for different users/guilds basically what ever you want.
how do you handle the cooldown response
You can set it up
buckettype guild
ah ok
how do you automatically send that cooldown embed
exception
ah
Ooo so for example a user with a certain role can use a command 1 time every hour while another can do it 20times
yes
Seems nice to prevent spammer as member for example
yeah, or premium features
Yeah true
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
Do approximate_member_count or approximate_presence_count require the GUILD_MEMBERS intent?

It's not written there so I assumed no
But wanted to be sure
you should need presence intents to get approxmiate presence
and so i guess the opposite
if u want i can try it quickly
That would be nice
ok let my 5s
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
without itents it return None, None
let me try with intents
even with intents it return me None
mb i didnt read the doc
wait
you have to set with_counts
add fetch guild worked
without intents?

i used intents.default()
for what do u need presence ?
I'll send you in dm
ok
anyone? D:
.tas
.tias
and tell us
yeah, thats the point, it didnt
?
like i never used dyanmic cooldown
i am talking about any cooldown 💀
Application Command raised an exception: AttributeError: 'NoneType' object has no attribute 'update_rate_limit'
pretty strange
let me try
@trim bison can you send me how u have setup ur cooldown pls ?
sure
strange that for prefix commands it works, but not for slash command
how did you find out
nah im sutpid
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
how the fuck
k
issue come from the dynamic cooldown
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
wait so if it is a regular cooldown it is going to work?
both subcommand and @slash_command?
No even a regular cooldown does not get updated
Maybe you can use reset_cooldown
?
does not work for both
Yep if it was the question with or without sub command it does not updated the cooldown
if you have the subcommand decorator, you don't need slash_command
why do you have both decorators
and run update_rate_limit with no params
Il usually not using command
Cooldown is None in his case
can't as cooldown is None
this
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
nelo how do i reset the rates then?
command.reset_cooldown
.
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
so when user runs /report <anyone from staff> or /report <himself> it will give him the token back
and in which case you want to not cooldown him then ?
like if when it does
/report it remove his cooldown each time
no just when reports self or staff
why put the cooldown since it will be remove for this member if you prefer
handle it in your dynamic cooldown instead
how?
but is that a lib issue ?
i check docs like 5 times nothing
by checking this.
or am i missing something
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
yeah but here it doesnt work right
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
just check if the user id they pass is ctx.author.id
i think your requirements are just way too specific for the library to handle it
and if so return no cooldown
nope they are passing discord.Member
oh
yes, discord parses that as an id
wait
https://docs.pycord.dev/en/stable/api/application_commands.html#discord.ApplicationContext.selected_options
bit better / more direct imo
Command Permission Decorators: Commands: Shortcut Decorators: Objects: Attributes full_parent_name, qualified_id, qualified_name. Methods@ after_invoke,@ before_invoke,@ error, def get_cooldown_ret...
you mean
then check if ctx.author.id == member.id
oh that's what it's named
yeah but where do i?
in your dynamic cooldown
inside the mass_function
as toothy linked above, you access ctx.selected_options
just print it and you'll understand the rest
yes
docs should be open whenever you work on a pycord bot :>
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
(i don't think it's actually a dict so double check)
i understand what your poin is
it is
i guess a list counts as a dict in json
you can parse the error
and reset it then ig
it doesn't matter, in your dynamic cooldown you can just tell it to go through
nah it says List[Dict[:class:str, Any]]
oh okay let me try
yea, a list of dicts lol
which is correct
but check the "returns" text above
oh i see
this wont work
again
[{'value': '857993843566968862', 'type': 6, 'name': 'user'}, {'value': 'Racism', 'type': 3, 'name': 'reason'}]
i mean
what is type?
then check the name
oh shit missed that
i imagine your options are required which assures the order is fixed
are they?
you tell us
you can typically assume they're ordered correctly, but it's good to check name regardless
but if the member option is required (which i hope it is) then its always [0]
you can shuffle args in the cmd
why ?
but the output remains
its list of dicts
[{'value': '857993843566968862', 'type': 6, 'name': 'user'}, {'value': 'Racism', 'type': 3, 'name': 'reason'}]
it was more to give u an idea of how to handle it than to do it
p sure you cant with required options
you can, but even when you shuffle them discord reorders them
yea id imagine its always in the "suggested" order you set in the code
yeah thats i am saying
so ill keep it as [0]
hope no issues will come
good luck
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?
Bots: Attributes activity, allowed_mentions, application_flags, application_id, auto_sync_commands, cached_messages, cogs, debug_guilds, description, emojis, extensions, get_command, guilds, intent...
you'd use bot.wait_for, but generally you're better off using a modal
damn nelo cmon
i knew it would happen
i wanted to say that
then do it smh
lol
i was too busy being proud of how fast i found it in the docs
you're like a pair of hawks
did you convert the ids
ok i shouldnt be surprised one of you is a dragon
w h a t
blue jumpscare
but i could just use the search
index is faster
still cool where is the link for that on the site
does a modal have some upper limit for the amount of questions you can ask?
ah 5 fields
should be 4
no
oh i wouldnt want it to be that way to be helpful
don't make modals even worse please
just edit the thumb to be out
oh true
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
You maybe should print also the ctx.aujtor.id
And also staff
To check why it return false
2nd one is correctly False, what's in the staff list?
oh wait
different author hmmm
ids
neither 7... 9... is there
so
alt mentioning this account:
857993843566968862 997570531643629571
False
True
Si its normal ?
alt mentioning itself:
997570531643629571 997570531643629571
True
False
Like the author and the member are not the same but the member is onside staff
Yeah so it works as expected no ?
so how the fuck i got 778657519476277309
i didnt mention anyone
else
Idk
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
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
Can you show us how look the mass lookup ?
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
Ok and this is only trigger when there is no cooldown
Well I can’t really debug it for the moment so
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???
yeah
wdym
now prob nvm
but again
that would remove one token
just handle it 
man just write your own handler
you're trying to wrangle pycord so hard here and it aint working
how do you expect me to handle it?
handle cooldowns yourself lol, just write some stuff
you have the entirety of python at your disposal, use it
but that is not really the most optimial
python was never optimal
as long as discord handles cooldowns its easier and faster
you evidently cant do it with pycord because it wasnt made for cooldowns this complex and specific
...this isn't handled by discord, it's handled by the library
Save your cooldowns to an sqlite file or whatever, it really isn't magic
this needs a custom system. period.
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
it's probably possible but it's painfully hard to debug someone else's code
can i dm you nelo?
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"
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
just want to show you my code, not exposing it here
isee
thanks, you got all requirements there
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
return it? lol
ah
i've got no idea how if so
yea, idk then
what is that
whats the best way of specifying interaction contexts in a bridge command?
You mean type hinting?
bridge context
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
bridge context
discord.ext.bridge.BridgeContext
discord.ext.bridge.BridgeContext.defer
discord.ext.bridge.BridgeContext.edit
discord.ext.bridge.BridgeContext.invoke
discord.ext.bridge.BridgeContext.is_app
discord.ext.bridge.BridgeContext.reply
discord.ext.bridge.BridgeContext.respond
discord.ext.bridge.BridgeExtContext
discord.ext.bridge.BridgeExtContext.delete
discord.ext.bridge.context.BridgeContext
discord.ext.bridge.BridgeApplicationContext
discord.ext.bridge.context.BridgeExtContext
discord.ext.bridge.context.BridgeApplicationContext
do you mean the changes made with user apps? or something else
I mean how guild_only is now deprecated and contexts are now preferred instead
ah
i don't think we adjusted it for bridge yet, guild_only will still continue to work for now but we'll update it later
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
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
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
it should? i've checked through the code and it's still compatible
why yield
did it with jsk
I've tested it and it doesn't seem to raise the guild_only exception
if it does somehow? send me some example code
i tested just now and it seems to work fine? it's just the @bridge.guild_only() decorator
no, thats being deprecated
im talking about a possible feature that will work with the prefix commands that will replace bridge.guild_only
So just keep using it until we do
ok, so there isn't any existing method
Deprecated features won't be removed without prior warning
thats all I wanted to know
It's also possible we keep the existing bridge.guild_only because bridge is outside of the api scope anyway
we'll see ig
What happens when you print channel.guild
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?
probably typehinting message: discord.Message?
not just probably
how do i write commands in py-cord that work on servers as well as via pn
so slash
please ping me
what is pn ?
Learn all about Slash Commands and how to implement them into your Discord Bot with Pycord!
do you talk about that ?
or about userapp ?
You can pass contexts into the command decorator. Note this is only as master right not but an release to pypi is coming soon.
this is for userapp right ?
doesnt normal /command appear in private message ?
thanks
yeah i guess so but I think they wanted user apps
Ok i was just wanting to be sure about slash
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
cogs
Cogs, often known as modules or extensions, are used to organize commands into groups. This is useful
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)```
message.channel is not discord.DMChannel
is this the correct way to check if a message sent is outside of dms?
is one of your extensions causing the error
its in the main file as u can see
show the full traceback please
sure
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'?```
what did you last change in your code
its a new project i didn't change anything
seems good
that, or you check message.guild
oh
you cant load your cogs in on_ready
i have been trying to fix it for like 2 hours or something
it must happen before that
its a stupid error ik, i can't figure it out cuz im tried
i mean i copied it from my old projects
great, but you cant do that if you have application commands in your cogs
load them before on_ready
just move it out, i have it like this in my code
i don't have any extensions
ill never understand why people dont just bot.load_extensions("cogs")
i mean im using it
so nothing in your /commands folder?
nope
nope
does it automatically iterate?
File "c:\Users\ahmed\OneDrive\Desktop\Coding\DiscordBots\Movies\main.py", line 95, in <module>
import discord.commands
its in a main file
i mean it loads all cogs in the cogs folder
not sure if it checks subfolders too
oh neat
ah
yea
huh
adding the imports would've probably helped lol
do you have any example bot u sure its running fine, so i can test if the problem is in my discord bot itself
Excited to create your first bot? Once you install Pycord, you can start right
not working too
show your pip list
so the problem is my project in dev app?
here one sec
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
you have discord.py installed
uninstall both that and py-cord and only reinstall py-cord
ye working now, told you a stupid error
thank you
