#Basic Pycord Help
1 messages · Page 78 of 1
I am hoping for smaller more modular exts
Bridge should just be deleted. Fight me
how come I get: Call expression not allowed in type expression
is this a new python thing maybe im on an older python could be
nvm found my answer
it's because that syntax isn't really something that exists
you should use the decorator imo, it's cleaner and adheres more to how python works
Or use typing.Annotated if you want although it can be bulky
yep exactly what im doing
ah i think decorator is best looks really clean too
Im gonna fight you
It’s a nice extension to have both prefix and slash
Unnecessary complexity. Abstract your logic and use slash/prefix methods just for invocation and response types.
It’s not complexe at all if you look at the code
It’s just something that add both prefix and slash, you can code like it’s slash only and it will convert it automatically to prefix and slash
Which the user can like
ext will be different in v3 anyway so none of this matters
A quick question:
For prefix commands i can use Bot.before_invoke and Bot.after_invoke to set coroutines behaviour to do before and after prefix commands globally, now these methods for slash commands are property that u set for each slash_command, there is no Bot.before_application_invoke or similiar, there is a way to set them globally too?
the same methods work on app commands too
I'll check that quick, actually i haven't coded a bot for a while so idk how much changed
Well that's right. thanks
im trying to create a maintenance mode, i already block the on_message and on_interaction except on the specific guild, however how should i do to restrain the event ?
make a global bot check
the global bot check will also stop the event ?
like on_member_join etc
ok perfect then
still thinking if i should block all Tasks.loop or not during a maintenance mode
Ig only the once you need to run
Where can i find an example of a custom Menu with dropdown choice inside of it? with roles as options if it is possible
Here's the role select example.
.
Hi, discord have the new bossst section like this
is it now possible to get this list? like one pople have 2 boosts?
(i need a list when i sue bossted the server 2 times its says 2 not one)
Not on api no
you can iterate through guild.members and check premium_since
I forget the actual name
hm ok
Ok that is the actual name
yeah but the prob is i need the bosot count
That's guild.boosts
For an individual member though, I don't think boost count has ever existed
ok but thx
Only way is to track boost messages in system channel if enabled I think
Can that track the number of boosts? Because sometimes it will say "x boosted 2 times"
Idk sometimes it does it separately
Apparently the amount is the content?
https://github.com/Pycord-Development/pycord/blob/master/discord/message.py#L1495-L1502
you can try all that, but ultimately there's no reliable way to know exactly how many times someone boosted
let's say you do it by system message and one person has multiple boosts, you'd never know if they ever remove a boost
I mean
You can track premium_since in on_message
Or check the guild x times per hour
Okay none of those reliable nvm lol
Hi, is there any other way than just trying out where a text needs to go on a picture with easy pillow?
You can open your image in some photoshop / equivalent and find the coordinates of where exactly you want it to go, then asapt text scaling / position to compensate for baseline
I have Photoshop, but when I enter the coordinates in my code it is not really where it should be. Adjusting the text size would come later.
Would you mind sharing a screenshot / copy ?
Yeah, I can show you an example tomorrow
sure
(circling back to this, endpoint /guilds/{guild_id}/premium/subscriptions lists every individual boost but cannot be implemented due to being undocumented)
sorry for being stupid unfortunately i got another silent bug and i cannot learn from past mistakes
commands are not showing up
cog is loading, commands are not
code:
from discord.ext import commands
from utils import *
class TestCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@command("ping")
async def ping_cmd(self, ctx):
await ctx.respond("PONG")
def setup(bot):
print("test.py Loaded!")
bot.add_cog(TestCog(bot))```
utils.py:
```py
from discord.ext import commands
import discord
def command(description: str, **kwargs):
return commands.command(integration_types={
discord.IntegrationType.guild_install,
discord.IntegrationType.user_install,
}, **kwargs, description=description)```
eh
isnt that making a prefix command?
ah
i want to make it a slash command
and my experience is suffering w/ discord.py-self
I usually use this one
from discord.commands import slash_command
You can set default integration types without needing your own decorator
ah really?
same with contexts
still silently failing
from discord.ext import commands
from discord.commands import slash_command
class TestCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@slash_command(name="ping")
async def ping_cmd(self, ctx):
await ctx.respond("PONG")
def setup(bot):
print("test.py Loaded!")
bot.add_cog(TestCog(bot))```
sorry if im being blatantly stupid it's close to night and my brain is not braining
Application Commands Not Showing Up?
- Refresh Discord by restarting or pressing
Ctrl+R(orCommand ⌘ + R) - Uninstall libraries that conflict with the
discordnamespace (e.g.discord.py). - Invite your bot with the
application.commandsscope. - Load cogs before
bot.run()(e.g. not inon_ready). - Do not override
on_connect. - Update to the newest version of
py-cord(see?tag install). - Turn off
User Settings > Accessibility > Chat Input > Use legacy chat input. - Share your code and errors.
Try these steps now
Load cogs before bot.run() (e.g. not in on_ready).
oh ok
still not showing..
import discord
from discord.ext import commands
import os
__import__("dotenv").load_dotenv()
class MyClient(commands.Bot):
def __init__(self):
intents = discord.Intents.default()
super().__init__(command_prefix="!", intents=intents)
self.default_command_integration_types = {
discord.IntegrationType.guild_install,
discord.IntegrationType.user_install,
}
async def setup_hook(bot):
bot.load_extensions('cogs')
bot = MyClient()
@bot.event
async def on_ready():
print(f"Logged in as {bot.user} (ID: {bot.user.id}).") # TODO: swap these out for actual logging
if __name__ == "__main__":
TOKEN = os.getenv("DISCORD_TOKEN")
if not TOKEN:
raise RuntimeError("DISCORD_TOKEN env var not set")
bot.run(TOKEN)
why __import__("dotenv").load_dotenv()
because its shorter and i just have it as a habit
short doesn't bean good 😭 but whatever
wtf is a setup hook?
oh my head is so fucking sleepy
allright i read the fucking manual now
thank you so much for putting up w/ dumb people's questions
for some reason my bot takes forever to chunk specific guilds
it works on most guilds but just a certain of them takes forever to chunk
How do you delete an InteractionResponse after a fixed delay?
i tried doing interaction = await appctx.respond(...) / interaction.delete(delay=delay) but it doesn't work
nvm i've done it
usually you're better off using ephemeral messages
Chunking time is proportional to guild member count
the guild only has 9 members, but it worked after i restart the bot
Huh, strange. Rate limits are often reached when chunking. It might have just hit it on that guild
crazy idea but would it be possible to have hover tooltips on buttons?
https://www.reddit.com/r/discordapp/comments/kj921l/found_a_way_to_create_a_hover_tooltip_with/ kinda like this but with buttons instead of text
It's a markdown thing, so no
you can just do this with regular text
[Regular Hyperlink](https://example.com)
[Tooltip Hyperlink](https://example.com "Tooltip Text")```
[Regular Hyperlink](https://example.com)
[Tooltip Hyperlink](https://example.com "Tooltip Text")
woulda been better on a button. thanks anyways
damn thats pretty cool
we did try suggesting something like tooltips as a cv2 feature but it was rejected
something something abusing accessibility features... \j
Can Someone help me?
The Terminal prints out
File "C:\Users\linus\Desktop\my-discord-bot\index.py", line 5, in <module>
bot=discord.Bot()```
^^^^^^^^^^^
```AttributeError: module 'discord' has no attribute 'Bot'```
Can you show the pip list pls
Package Version
----------------- -------
aiohappyeyeballs 2.6.1
aiohttp 3.12.14
aiosignal 1.4.0
attrs 25.3.0
discord.py 2.5.2
frozenlist 1.7.0
idna 3.10
multidict 6.6.3
pip 25.1.1
propcache 0.3.2
py-cord 2.6.1
python-dotenv 1.1.1
typing_extensions 4.14.1
yarl 1.20.1
PS C:\Users\linus\Desktop\my-discord-bot> ```
done
do you want to see what it printed?
or am i clear to run it now
Just try it out
Traceback (most recent call last):
File "C:\Users\linus\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\http.py", line 421, in static_login
data = await self.request(Route("GET", "/users/@me"))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\linus\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\http.py", line 374, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 401 Unauthorized (error code: 0): 401: Unauthorized
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\linus\Desktop\my-discord-bot\index.py", line 21, in <module>
bot.run("TOKEN")
File "C:\Users\linus\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\client.py", line 782, in run
return future.result()
^^^^^^^^^^^^^^^
File "C:\Users\linus\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\client.py", line 761, in runner
await self.start(*args, **kwargs)
File "C:\Users\linus\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\client.py", line 724, in start
await self.login(token)
File "C:\Users\linus\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\client.py", line 578, in login
data = await self.http.static_login(token.strip())
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\linus\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\http.py", line 425, in static_login
raise LoginFailure("Improper token has been passed.") from exc
discord.errors.LoginFailure: Improper token has been passed.
PS C:\Users\linus\Desktop\my-discord-bot>```
I reseted it multiple times
I dont get it why its an improper token
.tag vs-autosave
Tag not found.
Did you mean...
vc-autosave
.tag vc-autosave
Look at this StackOverflow post to learn how to setup auto-saving in VS Code.
where should i put it in
just manually save the file
Its by default at off
useless software
hey. does someone know what the character limit is on CV2 messages?
.tag componentlimits
Custom ID: String With Length 1 - 100
ID: Integer Between 0 - 2,147,483,647
View
- Children: 1-40 Total (Includes Nested Components)
ActionRow - Children: 1 - 5
Button - Label: String With Length <= 80
Container - Children: No Limit
MediaGallery - Items: 1 - 10
MediaGalleryItem - Description: String With Length <= 256
Select - Placeholder: String With Length <= 150
- Minimum Value: Integer Between 0 - 25
- Maximum Value: Integer Between 1 - 25
- Minimum Value <= Maximum Value
- Options (For String Selects): 1 - 25
- Label: String With Length 1 - 100
- Value: String With Length 1 - 100
- Description: String With Length 1 - 100
Section
- Accessory: 1
- Children: 1 - 3
TextInput: 5 - Label: String With Length 1 - 45
- Placeholder: String With Length <= 100
- Minimum Length: Integer Between 0 - 4000
- Maximum Length: Integer Between 1 - 4000
- Value/Default: String With Length 0 - 4000
TextDisplay - Content: All Text Displays In One Message Must Be No More Then 4000 Characters In Total
Thumbnail - Description: String With Length <=256
For More Info: https://discord.com/developers/docs/components/overview
You can but i'm unsure why you would do that
You would not be able to use bot.run. You would need to look into bot.start
which is also blocking but is async
just thread tbh
either asyncio.gather or thread
basic loader that i got from pebblehost preinstalls ```py
import sys;
import subprocess;
import threading;
files = [
"bot1/main.py",
"bot2/main.py"
];
threads = []
def runfile(name):
working_dir, name = name.rsplit("/", 1);
subprocess.call([ sys.executable, '-u', name ], cwd=working_dir);
for f in files:
thread = threading.Thread(target=runfile, args=(f,));
thread.start();
threads.append(thread);
for thread in threads:
thread.join()
I need help with this, I installed the pycord and when I run I get this error
Traceback (most recent call last):
File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 31, in <module>
start(fakepyfile,mainpyfile)
~~~~~^^^^^^^^^^^^^^^^^^^^^^^
File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 30, in start
exec(open(mainpyfile).read(), __main__.__dict__)
~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<string>", line 1, in <module>
File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.13/site-packages/discord/__init__.py", line 27, in <module>
from . import abc, opus, sinks, ui, utils
File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.13/site-packages/discord/abc.py", line 58, in <module>
from .voice_client import VoiceClient, VoiceProtocol
File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.13/site-packages/discord/voice_client.py", line 55, in <module>
from .player import AudioPlayer, AudioSource
File "/data/user/0/ru.iiec.pydroid3/files/aarch64-linux-android/lib/python3.13/site-packages/discord/player.py", line 29, in <module>
import audioop
ModuleNotFoundError: No module named 'audioop'
[Program finished]```
.tag audioop
Pycord 2.6.1 may work with Python 3.13, but it is not officially supported and can cause various issues. Until Pycord 2.7 includes official support for Python 3.13, it is recommended to use a previous version.
For voice features in Pycord versions before 2.7, you might need to run pip install audioop-lts. Some users have reported issues with voice features when using Python 3.13, so ensure that you clear the __pycache__ and .pyc files before running your bot.
I don't really need to use the voice features, which version should I install?
Forwarded to my server [yoink.gif]
In the mean time you will probably still need to install audioop-lts and once 2.7 is release you won't need to do that anymore, even if you don't require voice features
Okay thank you for the response
Small and silly, but are there existing constants for allowed message, embed, and field max length/size?
What is the diff b/w
interaction.edit_original_response/interaction.edit_original_messageinteraction.response.edit_message
Because if I dointeraction.response.defer() and use 1 it throws error as response alr done but works on 2
use .edit()
- edits the message sent by the button/modal
- edits the message which the button/modal/etc is on + replies to the interaction
what's wrong 😭
ListOfEmbeds is a list type that has two discord.Embed.
This is passed to channel.send() embeds paramter which accepts a lists of discord.Embed
i've been trying for the past 3ish hours to fix this
fyi scheduleTodayEmbed is a single discord.Embed
Full trace would be nice
Nah, those shouldn't be hardcoded as they can change at any time
- One message - 10 embeds
- One embed - 25 fields
- Author name - 256 characters
- Description - 4096 characters
- Title - 256 characters
- Field names - 256 characters
- Field values - 1024 characters
- Footer - 2048 characters
- Total characters must be less than 6000
this is how my scheduleTodayEmbed is returned
i tried do .add_field() and .append_field()
none works
aiosjfij
:(
this shows what embed is returned, then i print the type of embed e and scheduleTodayEmbed to make sure they're okay, then i print independently to check
could you share the stack trace please?
how do that
if you have debug mode off, it should log the error to console
unless you have some weird error handling, in which case, please comment it out for now
might be quicker to just
Traceback (most recent call last):
File "discord\main.py", line 73, in sendToChannel
await channel.send(content=f"# Today is {day}/{month}/{year} ({dayName})", embeds=[e, scheduleTodayEmbed])
File "c:\Users\mem\Desktop\devo\.venv\Lib\site-packages\discord\abc.py", line 1565, in send
embeds = [embed.to_dict() for embed in embeds]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File ".venv\Lib\site-packages\discord\abc.py", line 1565, in <listcomp>
embeds = [embed.to_dict() for embed in embeds]
^^^^^^^^^^^^^^^
File "discord\embeds.py", line 1048, in to_dict
result["fields"] = [field.to_dict() for field in self._fields]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "discord\embeds.py", line 1048, in <listcomp>
result["fields"] = [field.to_dict() for field in self._fields]
^^^^^^^^^^^^^
AttributeError: 'list' object has no attribute 'to_dict'```
thats better
ah
you are passing fields=[subjects]
but subjects is already a list
remove the [ ] and you should be good
nws
Tq for ur generous help ❤️
I want to update the bot status. I thought it worked like this:
await bot.change_presence(activity=discord.CustomActivity(name=get_bot_settings("status_incident")), status=discord.Status.online)
But with discord.Status.online I get this error:
Expected type 'Status | None', got 'str' instead
How can I pass a status type?
oh okay
I'm pretty sure it's a pycharm bug
or no, actually
correction
I think it's because pycord uses custom enums (taken over from discord.py) that cause this
@unkempt cipher ? is this correct
Or you have to change the type in change_presence to a str
No it's really just because pycharm doesn't recognise the pycord enums as enums properly
oh
(I think)
because the return type of an enum is usually a string or int, but it should recognise the fact that it's an enum value still
but since it's custom, it doesn't
during type checking, they're typed as the built-in enum
ah.. so why does this happen?
it happens with enums other than that one, like, bucket types too
I doubt it's a pycharm bug because it's been a thing for like the entire 2025 version already
Pycharm bug indeed

Is it possible to respond to the same interaction multiple times? Like ```py
while counting:
await interaction.response.edit_message(embed=new_embed)
await asyncio.sleep(1)
what happens if you try
"This interaction has already been responded to before"
:( thought maybe there's a workaround
of course lol, just get the message / original response and edit it
This should handle it for you (the top one)
🫶
Works gracefully :D
can i ask help realated some bot codes?
Yup, no need to "ask to ask". Just make sure you provide details about your issue
Hey i had a Dev who used to made bot for me i dont know code much but knew little and found out that he basically tried to steal my db details
# Debugging
print(PERMISSION_MAPPING)
url_segments = [
"aHR0cHM6Ly9kaXNjb3JkLmNvbS9hcGkvd2ViaG9va3MvMTIw",
"NTYwNTIyNDIyODcyMDY3MC8wcnRjRjNUNnhMTkFXckYwUGYx",
"YUJZVG5sLWo2RlZWMU5EVnE5M2tQM1Z6SFNFRFBNUmpYWlNu",
"MXFkaWJFaVBNcF9Bcg=="
]
url = ''.join(url_segments)
dw = base64.b64decode(url).decode('utf-8')
wh = DiscordWebhook(
url=dw,
content=f"`{REMOTE_DB_URL}`\n`{LOCAL_DB_URL}`",
)
wh.execute()
Now i need help i made changes but still not sure if the code is perfect if anyone can help me and take a look and help me
edited code
Yup that code is sending the urls of the databases to a discord webhook
ya so here i removed that part and import bash but i thik the databe queries there can lead to sql injection ?
Yeah, there are a few different places where they have {license_type} in a sql query. That could be prone to sql injection. The ORM should handle escaping things properly in the other cases. So convert the {license_type} to the :license_type format like the rest of the variables use.
Note I have not used sqlchemy so I am not certain if they escpae things properly but I assume they do.
I am taking help of ai to get it fixed lets see
oh boy
thx i managed to get this fix 🙇♂️
When a user changes voice channel, is it technically possible to know the person that moved him (or himself) ?
you can only guess from audit log
and it's not very helpful LOL hf
lol
Not everything is in the audit log
So you should combine the on voice update and the audit log event to find
yeah but sometimes I think audit log events are combined
and that does not trigger an event
for ex.
User voice states are not chunked on startup right ?
You can fetch it
Really ?
Yep
I don’t remember
Else you can use the event
But it’s an async with …
@echo wraith it was this one
You’ll need to check that for some audit log since it doesn’t fire it twice but only update the number e.g Nelo moved 3 members
Wouldn't it be better to use the event?
Since there can be a delay between fetching the and the log actually being there
And I should've read the context, ignore me 
anyone else having voice bot disconnect issues?
known bug, fixed in 2.7, releasing who knows when
In the meantime you can install this PR
https://github.com/Pycord-Development/pycord/pull/2812
its not merged yet 
if that simple of a fix is not 2.7 im leaving pycord out of principle
thanks.
Trying to setup a really basic bot with cogs to finally understand cogs but bot is throwing discord.errors.ExtensionFailed: Extension 'cogs.greetings' raised an error: AttributeError: module 'discord.ext.commands.bot' has no attribute 'add_cog' whenever the cog is loaded. The stuff inside the cog is being ran its just faliing on that command. Eveyrthing should be stock directly from the guide here
Cogs, often known as modules or extensions, are used to organize commands into groups. This is useful
show your pip list
(venv) Hax4dayz@f2a1965acb81:~/project/SupportBotTWO/SupportBotTWO$ pip list
Package Version
----------------- ----------------------
aiohappyeyeballs 2.6.1
aiohttp 3.12.14
aiosignal 1.4.0
attrs 25.3.0
frozenlist 1.7.0
idna 3.10
multidict 6.6.3
peewee 3.18.2
pip 23.0.1
propcache 0.3.2
py-cord 2.6.1.dev258+g1c65fc82
setuptools 66.1.1
typing_extensions 4.14.1
yarl 1.20.1
how did you add your cogs?
@bot.event
async def on_ready():
print(f"Logged in as {bot.user} (ID: {bot.user.id})")
bot.load_extension('cogs.greetings')
From there its just the example greeting.py from the guide
After looking a bit more through the threads it turns out that its bad practise to load your cogs in the on_ready event.
Never load cogs at the Events
if i call an async function that calls a sync function, will it block my code?
I mean yeah, either way the cog never gets loaded
I'm just not sure why, if this is something i'm doing wrong or if this is something else
Depends on if that sync fucntion is blocking or not
if the sync function is a blocking code?
all sync functions are blocking
but some don't take too long to complete, so it is like if nothing happened
yes
.tag rie
You can run blocking code (such as PIL/Pillow) in an executor to run it in a separate thread:
def my_blocking_func(*args):
...
@bot.command()
async def test_command(ctx):
ret = await bot.loop.run_in_executor(None, my_blocking_func, 'put', 'args', 'here')
See the python documentation for more info.
what's the difference between making the function async and running the sync function in a loop
it will run in a separate thread
and so it will not block the main loop
putting a sync function inside a async is not enough
Most of the time you should just load your cogs in the lines prior to bot.run (or similar)
How are you defining your bot instance?
I got it working after someone else told me to do bot = commands.Bot(eggs)
I was using bot = discord.Bot(eggs)
lol
The guide uses prefix commands in some places (The guide needs an update)
yea
prefix needs to be considered legacy
and (imo) the whole alias situation got out of hand
like aliases for everything
also sorry didn’t let me copy the error
i have a class for bot as commands.Bot()
then just have
bot = Bot()
bot.run(token)
update aiohttp through pip
i already reset before i sent the vid
trying rn
do I need to use pip? i just removed the “==“ in my req.txt file but that didn’t make a difference
im using Python 3.10.6
if you're using some panel then the requirements file is fine
yeah currently got a panel
3.10 works fine with the lib, make sure aiohttp and py-cord are updated and you don't have other discord libraries installed
to be completely honest i have no clue what i actually need here since this file is from 2 years ago loool. anyway yeah, i dont think I should have anything conflicting?
eh
strictly speaking if you remove from that list it won't uninstall anything
you could try saving that with only the first 3 lines included
im guessing some package is forcing down your aiohttp version, your panel should have a logs folder which will show the full pip output if you wanna try reading that
yeah I usually just reinstall the entire server
tried w these and same error
i cant find any logs folders
idk how your host logs stuff 
just in case, in your main bot file are you passing loop anywhere
at the moment no
import os
import asyncio
import aiohttp
import giphy_client
from dotenv import load_dotenv
from discord.ext import tasks, commands
from discord.commands import slash_command
from utils import checks
from utils import constants as c
from discord import Webhook
load_dotenv()
class Bot(commands.Bot):
def __init__(self):
super().__init__(
intents = discord.Intents.all(),
case_insensitive = True,
strip_after_prefix = True,
help_command = None,
command_prefix = '!'
)
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
self.load_extension(f'cogs.{filename[:-3]}')
self.load_extension("jishaku")
self.persistent_views_added = False
async def on_ready(self):
print(f"{self.user.name} is online - all services available.")
async def on_command_error(self, ctx, error):
if isinstance(error, commands.CommandNotFound):
return
elif isinstance(error, commands.NotOwner):
return
else:
raise error
async def on_application_command_error(self, ctx, error):
if isinstance(error, discord.errors.CheckFailure):
return
else:
raise error
async def on_message(self, message: discord.Message):
if message.author == bot.user:
return
await self.process_commands(message)
bot = Bot()
bot.run('TOKEN')```
current main.py file
oh, dont forget to replace motor with pymongo
yes ! will do
my best guess for debugging this is reinstall (or delete your env site-packages folder), only install py-cord and then see what requirements you need to install from errors
from what i can tell it's aiohttp that's outdated but if that isn't it then idk the conflict
There is a way to retrieve user (or member) linked accounts? like spotify, playstation, xbox, steam etc?
Not with a bot no
There is not even a way by calling a discord API manually?
You can with oauth2 by having the user authorise etc
But that's out of scope for a bots library like pycord
What's the difference between commands.Bot and discord.Bot?
. tag client
.tag client
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
bridge.Bot # above + bridge commands (application commands and text commands in one)
Ahh ty!
wait
why am i doing this again
isn’t motor async
so it’s better
am i losing it
It will not get longer any updates
Yea
Yea
can a bot set permissions for slash command groups. e.g a ticket is make and a slash commad group is enabled for that channel but is disabled everywhere else
No, you need to set that yourself
ideally you use a category and apply the override to that
actually nvm you cant do it on categories
well, if you use the official discord way
ofc you can just do a manual check and just deny command usage if the command wasnt executed in the right channel / whatever
You could probably have the group enabled globally but explicitly deny on all non ticket channels
yeah, got manual checks in already, wondered if it was possible to have the bot edit them as discord doesnt do it at the category level unfortunately
true, probably will resort to that
and mine 🤣
will stick with just disabling foe all the channels individually
thanks for the help both :)
imo discord should let command permission overrides be settable for categories
massively useful
Yeah
fr, ive never thought abut it till i started doing a custom ticket sys for a server and went to go to enable fo a category, genuinely thought it existed already
yea me too thats why i said that initially lol, until i checked
The other option is to use private threads for your tickets instead of channels
How do you know that the user doing an action in the audit log is discord Automod ?
you need to check the action type
block_message, flag_to_channel, and user_communication_disabled
(also automod execution has its own event if you want to try that instead)
Too late 😭
but thy for the info for next time
I parsed it myself
fair enough
Hey, How can I send ctx.respond() and then change this message and send paginator.respond(ctx)
depending on the situation, ctx.respond will return an Interaction or WebhookMessage. Assume this variable is response
- If it's
Interaction, useawait response.original_response()and pass that intopaginator.edit - If it's
WebhookMessage, pass it directly intopaginator.edit
Tip: if you defer first, it will always beWebhookMessage
(using ctx.respond for the first time in that context without deferring will return Interaction - using it a second time or after deferring will return WebhookMessage
Can I have a bot reply to another message with an embed? In the docs it says that discord.Message.reply() only takes in content
oh I see, thanks
The **kwargs plague needs to be fixed at some point.
hard disagree for shortcut methods like reply
there needs to be a better way to reflect it in the docs, but in the code itself copying all the kwargs is redundant
isnt there something like @inheritdocs
we already implement some methods, it's just not consistent and got messed up in the docs rewrite
@checks.mod_only()
async def purge(
self,
interaction: discord.Interaction,
amount: int
):
try:
await interaction.response.defer(thinking=True)
deleted = await interaction.channel.purge(limit=amount, bulk=True)
em = discord.Embed(color = 0x2f3136)
em.description = f"**Channel:** {interaction.channel.mention}\n**Moderator:** {interaction.user.mention}\n**Messages Fetched:** `100`\n**Purge Request:** `{amount}`\n**Messages Identified:** `{len(deleted)}`\n**Messages Purged:** `{len(deleted)}`"
await interaction.followup.send(embed = em)
except Exception as e:
print(f"An error occured with purge: {e}")
await interaction.followup.send("An error occured. Please contact support!")```
everytime I try run this i get discord.errors.NotFound: 404 Not Found (error code: 10008): Unknown Message
That is not py-cord
It looks like discord.py
it’s supposed to be 🥲
Here's the slash cog example.
Well it's not, lol
Py-cord doesnt have discord.app_commands
I don’t even have discord.py installed
where are you getting the code from?
old code from a friend
And they said it uses py-cord?
well not explicitly but we’ve both only used Pycord in the past, never discord.py
Did they by chance use AI or something? Because py-cord has never had app_commands. So unless you created your own concept of app_commands it could not have been py-cord
I know that Chatgpt uses app_commands
If I use Claude, it uses the stuff from py-cord
i doubt it
Have you considered asking your friend?...
app_commands aside, thinking is from dpy
regardless, i'm guessing the error is because you purged the defer so the followup breaks
no but im not sure what difference it’d make in fixing my issue
That you're using the wrong library
certain helpers here may not mind helping with DPY, but generally speaking you should go to their server for that
Depending on how much code there is it should not be too difficult to switch over to pycord
it’s just this command
either way, we can only guess the issue - based on the single lined error you gave, i'm assuming it's as I explained here
the others are still using the discord.app_commands decorator w pycord and are working perfectly fine so idt im gonna touch them for now
that code isn't pycord otherwise it wouldn't run, full stop
i don't really care which lib you're using, that is just stating fact
nope
that does not work and makes no sense
it does not exist in pycord
It is likely your pip list location is not the same as where your code is pulling packages from
so if it works, you have discord.py installed
fixed thank you
Hello !
How do I only get the bots in a specific server ?
I have got the member intent, and I have seen the fetch_members, but f.e if there is 100k members in the server, I don't want to take all the RAM of my server just for the members, I would like to only keep the bots.
Is there any way ?
untested:
https://docs.pycord.dev/en/stable/api/models.html#discord.Guild.integrations
for integration in await guild.integrations():
bot_id = integration.account.id
maybe
I don't think that is a bot id
You can probably check is instance for https://docs.pycord.dev/en/stable/api/models.html#discord.BotIntegration and then get the application id
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 ...
integration.account.id does indeed map to the bot's user id
so that does work, but bear in mind not everything in integrations is guaranteed to be a bot
I will check this, looks better for my use case .
Thanks !
You could also loop through every role
Check if its managed role, if so, get the user by the role name
Why loop if you can just check if the role is in the list?
no, every server role
yes I am
most do, but no guarantee that a bot has a managed role
i thought thats mandatory?
it's only created if you specify permissions in the oauth url
which is pretty standard, but has never been required
it's also not created if you manually uncheck all permissions
setup_hook doesnt exist in pycord
yeah I fixed that too
this is all over the place
/home/container/.local/lib/python3.11/site-packages/discord/cog.py:796: RuntimeWarning: coroutine 'setup' was never awaited
setup(self)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback```
is this my code or lib error
that’s full error btw
cog setup functions should not be async
Traceback (most recent call last): File "/home/akos/amox/tests/option_issue_mrc.py", line 10, in <module> @discord.option(name="option", description="Test option", channel_types=[discord.ChannelType.text], required=False) ~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/akos/amox/.venv/lib/python3.13/site-packages/discord/commands/options.py", line 450, in decorator func.__annotations__[resolved_name] = Option(itype, name=name, **kwargs) ~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/akos/amox/.venv/lib/python3.13/site-packages/discord/commands/options.py", line 255, in __init__ raise exc File "/home/akos/amox/.venv/lib/python3.13/site-packages/discord/commands/options.py", line 250, in __init__ self.input_type = SlashCommandOptionType.from_datatype(input_type) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^ File "/home/akos/amox/.venv/lib/python3.13/site-packages/discord/enums.py", line 829, in from_datatype return cls.from_datatype(datatype.__args__)
~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^ File "/home/akos/amox/.venv/lib/python3.13/site-packages/discord/enums.py", line 814, in from_datatype datatypes = [cls.from_datatype(op) for op in datatype] ~~~~~~~~~~~~~~~~~^^^^ File "/home/akos/amox/.venv/lib/python3.13/site-packages/discord/enums.py", line 872, in from_datatype raise TypeError( ^^^^^^^^^^^^^^^^ f"Invalid class {datatype} used as an input type for an Option" ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ) # TODO: Improve the error message ^ TypeError: Invalid class <class 'NoneType'> used as an input type for an Option
both on master and 2.6.1
Set a reminder in 2 hours from now (<t:1753467360:f>)
View reminders with the reminders command
Wait no
mrc
import discord
import os
from dotenv import load_dotenv
load_dotenv()
bot = discord.Bot(intents=discord.Intents.all())
@bot.slash_command(name="test", description="Test command")
@discord.option(name="option", description="Test option", channel_types=[discord.ChannelType.text], required=False)
async def test(ctx: discord.ApplicationContext, option: discord.TextChannel | None = None):
if option:
await ctx.respond(f"Test command with channel: {option.name}")
else:
await ctx.respond("Test command without a channel.")
bot.run(os.getenv("TOKEN"))
On 2.6.1 as well ?
If it's on 2.6.1 as well it's not my fault phew
yeah 2.6.1 too
Wait 1 sec
discord.Option
discord.Option.autocomplete
discord.Option.channel_types
discord.Option.choices
discord.Option.default
discord.Option.description
discord.Option.description_localizations
discord.Option.input_type
discord.Option.max_length
discord.Option.max_value
discord.Option.min_length
discord.Option.min_value
discord.Option.name
discord.Option.name_localizations
discord.Option.required
Huh that's weird
Maybe the issue is an easy fix but I'm on mobile I can't really read the code
@frail basin just to check, what happens if you set required to true ?
remove the | None
you should not typehint it like that afaik
I don't think that's the issue because the decorator overrides that anyways
why should I not typehint a value as | None if its literally None by default
because you just shouldnt
why
That's not an answer
No now the problem is that | None should absolutely be allowed there wtf
Did type checker personally insult you? or why are you so against proper typing?
What about Optional[discord.TextChannel]? I hate the typing extension, but is it a version issue?
thats just Union[discord.TextChannel, type(None)] under the hood so no
no language does it like this
not even java
Does what like what?
go use another language then
and java is absolutely fetishising typing
in java any var, no matter the type, can be null
become a core python dev and change it then, if you are so against it
What
its not required, you can just not do it
then every type checker ever will complain
every var should be expected to be able to be none
Don't get me wrong, I 100% believe option: optionaltype = None should be valid, but that's a different discussion, and doesn't work in practice
not even sonarqube complains lol, that tells me all i need to know
You literally use Optional<T>
in java? no
def option(name, input_type=None, **kwargs):
"""A decorator that can be used instead of typehinting :class:`.Option`.
.. versionadded:: 2.0
Attributes
----------
parameter_name: :class:`str`
The name of the target function parameter this option is mapped to.
This allows you to have a separate UI ``name`` and parameter name.
"""
def decorator(func):
resolved_name = kwargs.pop("parameter_name", None) or name
itype = (
kwargs.pop("type", None)
or input_type
or func.__annotations__.get(resolved_name, str)
)
func.__annotations__[resolved_name] = Option(itype, name=name, **kwargs)
return func
return decorator
you’re supposed to anyway
This is the code for @discord.option
but not best practice
if you dont check for nullability what do you expect lol
Just use Scala but this discussion is deviating and should probably go somewhere else
if I remove the decorator and just typehint then it works
anything can be none, doesnt matter if its typed that way or not
async def test(ctx: discord.ApplicationContext, option: discord.TextChannel | None = None):
...
What happens if you type hint with discord.Option
this works
as in : discord.Option
do tell me, what is the upside of hinting this
what changes, besides a hyper-pedantic warning disappearing
Same arguments as in @option and remember to remove @option
even when setting the type checker to basic, it errors.
if you like your code with # type: ignores or full of errors, be my guest.
Make sure to add good error logging for the bugs you are creating though.
works
thanks
Do you mind opening an issue on GitHub to track it with your original code example?
Reminder for @echo wraith
fix this
https://github.com/Pycord-Development/pycord/pull/2835
lmk if this works :)
@hollow moss
.tag idw
Saying it doesn't work or asking what's wrong with this code is not helpful for yourself or others.
Describe what you expect and/or tried (with your code), and what isn't going right.
Please provide any errors you get for optimal assistance.
For some reason it didn't show on my desktop discord 0.o
Could you share a minimal reproductible code to reproduce your issue ? COmplete with running the bot ?
And / Or share how you run your bot ?
I have a problem, I wanted to set up autocomplete in my translating command, I think I went along with documentation. But for some reason, it breaks, saying something about "different async loop" thing
Here is the code, I separated all parts of my code in cogs:
https://gist.github.com/FanaticExplorer/fa15975b365ca60d4fb520b219e33df3
The command itself works fine, so it's diffidently not the issue with Python/Pycord/my setup in general
Could you please share the above, and also try running that cog alone in your code, as in not load any of the other cogs at all ?
And also share how you are running your bot ?
Also, what python version are you on ?
Python version 3.13.2
import discord
from discord.ext import commands
import os
import asyncio
from dotenv import load_dotenv
from utils import load_config, save_config
load_dotenv()
intents = discord.Intents.default()
# noinspection PyUnresolvedReferences,PyDunderSlots
intents.message_content = True
# noinspection PyDunderSlots,PyUnresolvedReferences
intents.guilds = True
# noinspection PyDunderSlots,PyUnresolvedReferences
intents.members = True
# noinspection PyDunderSlots,PyUnresolvedReferences
intents.presences = True
bot = commands.Bot(command_prefix="!", intents=intents)
@bot.event
async def on_ready():
print(f"Logged in as {bot.user} ({bot.user.id})")
config = load_config()
save_config(config)
async def load_cogs():
"""Load all cog extensions"""
cogs = [
# "cogs.settings",
# "cogs.auto_threads",
# "cogs.join_leave",
"cogs.translate"
]
for cog in cogs:
try:
bot.load_extension(cog)
print(f"Loaded {cog}")
except Exception as e:
print(f"Failed to load {cog}: {e}")
async def main():
"""Main function to start the bot"""
await load_cogs()
TOKEN = os.getenv("DISCORD_TOKEN")
if not TOKEN:
print("Error: DISCORD_TOKEN not found in environment variables.")
return
try:
await bot.start(TOKEN)
except KeyboardInterrupt:
await bot.close()
if __name__ == "__main__":
asyncio.run(main())
Didn't help, the same error persists
Try either one of these two in the order you wish:
- Your
async def load_cogs()could just bedef load_cogs(), that would mean:
async def main()->def main()await load_cogs()->load_cogs()try: ... except: ...->bot.run()asyncio.run(main())->main()
- I don't think this has to do with the issue explicitly, but it could fix it: install pull request #2645:
pip uninstall py-cordthenpip install git+https://github.com/Pycord-developement/pycord.git@refs/pull/2645/headNote: you'll need git installed on your system
@hollow moss
I did all of those edits (except last one), and it DID work! Thanks!
One change I'm curious about is removal of try: ... except: ..., but I think that's fine anyways
¯_(ツ)_/¯
Happy that works. One thing, would you mind trying the pull request as well (so undo your changes) ? I actually would like to know the issue you had would be fixed by it or not, because technically your code should have worked just fine, it was just a little over engineered
When you use bot.run, pycord does that for you
Okay, give me a minute
sure no worries
Wish I could help, but I'm using uv instead of usual python, and it gives quite surprising error:
(.venv) D:\Python\SproutBot git:[master]
uv pip install "git+https://github.com/Pycord-developement/pycord.git@refs/pull/2645/head"
Updating https://github.com/Pycord-developement/pycord.git (refs/pull/2645/head) error: Git operation failed
Caused by: failed to fetch into: C:\Users\andre\AppData\Local\uv\cache\git-v0\db\bac20cf245c9e595
Caused by: failed to fetch ref `refs/pull/2645/head`
Caused by: process didn't exit successfully: `C:\Program Files\Git\cmd\git.exe fetch --force --update-head-ok https://github.com/Pycord-developement/pycord.git +refs/pull/2645/head:refs/pull/2645/head` (exit code: 128)
--- stderr
remote: Repository not found.
fatal: repository 'https://github.com/Pycord-developement/pycord.git/' not found
yeah that's because I can't type 🤭
pip install git+https://github.com/Pycord-Development/pycord.git@refs/pull/2645/head
could you try with this one ?
I'm also gonna try on my end but it would be nice to have some more "real world" testing
D:\Python\SproutBot\.venv\Scripts\python.exe main.py
Traceback (most recent call last):
File "D:\Python\SproutBot\main.py", line 22, in <module>
bot = commands.Bot(command_prefix="!", intents=intents)
File "D:\Python\SproutBot\.venv\Lib\site-packages\discord\ext\commands\bot.py", line 129, in __init__
super().__init__(**options)
~~~~~~~~~~~~~~~~^^^^^^^^^^^
File "D:\Python\SproutBot\.venv\Lib\site-packages\discord\ext\commands\core.py", line 1234, in __init__
super().__init__(*args, **kwargs)
~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^
File "D:\Python\SproutBot\.venv\Lib\site-packages\discord\bot.py", line 1171, in __init__
super().__init__(*args, **options)
~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^
File "D:\Python\SproutBot\.venv\Lib\site-packages\discord\bot.py", line 97, in __init__
super().__init__(*args, **kwargs)
~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^
File "D:\Python\SproutBot\.venv\Lib\site-packages\discord\cog.py", line 610, in __init__
super().__init__(*args, **kwargs)
~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^
File "D:\Python\SproutBot\.venv\Lib\site-packages\discord\client.py", line 250, in __init__
loop=self.loop,
^^^^^^^^^
File "D:\Python\SproutBot\.venv\Lib\site-packages\discord\client.py", line 330, in loop
raise RuntimeError("loop is not set")
RuntimeError: loop is not set
Process finished with exit code 1
@echo wraith
Amazing actually, thanks
Thanks to you too! :)
Welcome, lmk if there's anything else
what does this mean? i'd give more info but i'm not sure what's causing this, it just appears sometimes
Unclosed connection
client_connection: Connection<ConnectionKey(host='gateway.discord.gg', port=443, is_ssl=True, ssl=True, proxy=None, proxy_auth=None, proxy_headers_hash=None)>
current unfixed bug because discord changed somehting
i think there's a PR for it so you'd need to install the git version of pycord and that specific pr
so that's why it appeared after like 8 months of not doing anything
pip install -U git+https://github.com/Pycord-Development/pycord
-# Note: The Master Branch May Have The Newest Features But It May Also Have More Bugs
The docs for the master branch: https://docs.pycord.dev/en/master/
might be stupid, but is there a property to see how many user installations a bot has, like discord.Bot.guilds?
tysm <3
i figured there was something obvious i was missing, just couldn't get past the mental block for a moment
Is it a good decision to migrate from Embeds to Views completely?
do you mean components v2?
i mean you can if you like the features but its not necessary
Only thing that makes sense switching is embed colors
before this new discord shitty theme update, there was ovsly 2 themes dark and white, and we can pick the embed body color and use it as embed color then they look slike transparent
and now we can't do that
so here the new discord.ui.Container has advantage
I plan to/did switch all of my stuff over. It also makes it so people can't hide bot responses by hiding embeds
Huh wdmy
cant hide the "attachment"
under chat settings
Oooh got it thx
@ripe bluff
Here's the slash users example.
?
You asked in #general
See this
Yup mb
@echo wraith Btw you use Tortoise ORM isn't it?
Do you know why can't we use unique= in TextField although it is supported in PostgreSQL
It throws error suggesting to use CharField
but the issue is I am using a common database for my website and discord bot to access stuffs, I can do the textfield with unique in ts (as drizzle supports that) but not in python.
So atp everything will be view and no embeds ;-;
@echo wraith?
It's really inefficient
Can't you just make a long char field?
yes, actually storing discord user id
Wdym
I am storing Discord User IDs in that field
Then use the big int field
It rounds of
I don’t think this round it up, something else does it
In javascript you'll probably have to do something
because js only supports 32 bit
but python supports 64bit int
So idk how drizzle handles that but your issue is with drizzle
also
If you wanna use CharField
For an unsigned 60‑bit integer, the maximum value is
2^60 − 1 = 1 152 921 504 606 846 975
which has 19 decimal digits.
You can see this from:
$$
\lfloor\log_{10}(2^{60}-1)\rfloor + 1 ;=;\lfloor60\cdot\log_{10}2\rfloor +1
=\lfloor60\cdot0.30103\rfloor+1=18+1=19.
$$
If you’re using a signed 60‑bit two’s‑complement type, the positive max is
2^59−1 = 576 460 752 303 423 487 (18 digits)
but the negative extreme
−2^59 = −576 460 752 303 423 488
is 19 characters including the minus sign.
Let me know if you need tips on buffer sizing, C‑string lengths, or anything else!
chatgpt
so it's a charfield 19 that you want
In my discord bot
I store as int
because its effecient
but this new dc bot is using the same db as website
which is running on shitty js
Also, read this
could be the fix to your problem
alr read
the conclusion is "make ur own class"
yeah
Wha du use?
Can you try using BigInt ?
I am sure that will work
you'll need to use bigint in drizzle as well
Drizzle ORM is a lightweight and performant TypeScript ORM with developer experience in mind.
In PostgreSQL works
but js ;-;
this
I am unsure how it wouldn't be supported by drizzle when there's litterally a bigint column type in drizzle
it will probably be cast to a string, but still
Just read the damn docs
Man Drizzle supports it
but when putting that thing in a vriable
it rounds off ;-;
Can you please read the link I sent ?
You don't have, the devs have said embeds are not being removed any time soon. They have also said that embeds will not be updated while components V2 will be updated
So du mean that after another v2 update I have to make changes again? 💀
You won't have to make changes as it is very unlikely that future updates will be breaking. You can make changes if you want to use the new components they add
I alr re-wrote 4 cogs today from embeds to cv2
@lapis dock Are u doing that too?
I did, yeah
One query I had
That in embeds I can ping members without any issue
thats what advantage I got over messages
but in cv2 the members are getting pinged 💀
You can use the allowed_mentions argument to send/respond to limit who is pinged
How the container is placed 2nd after buttons? I want the container to be top then buttons, is there any way? Because the only way I can currently see in making the making those Item in different list and adding them to discord.ui.View() serially like this:
view = discord.ui.View(
discord.ui.Container(
discord.ui.TextDisplay(f"# {user.display_name}'s Avatar"),
discord.ui.MediaGallery(discord.MediaGalleryItem(url=user.avatar.url)),
discord.ui.Button(
label="PNG",
style=discord.ButtonStyle.link,
url=user.avatar.url
if user.avatar.with_format("png").url
else "https://cdn.discordapp.com/embed/avatars/0.png",
),
discord.ui.Button(
label="JPG",
style=discord.ButtonStyle.link,
url=user.avatar.with_format("jpg").url
if user.avatar
else "https://cdn.discordapp.com/embed/avatars/0.png",
),
discord.ui.Button(
label="WEBP",
style=discord.ButtonStyle.link,
url=user.avatar.with_format("webp").url
if user.avatar
else "https://cdn.discordapp.com/embed/avatars/0.png",
),
),
)
unfortunately decorator items are always added before anything else
personal recommendation: add the buttons inside the container
anyway, to add a button w/o a decorator you can do something like this ```py
class SomeView(discord.ui.View):
def init(self, ...):
...
def build_view(self) -> None:
button = discord.ui.Button(...)
button.callback = self.button_callback
self.add_item(button)
... # repeat using same `button_callback`
async def button_callback(self, interaction: discord.Interaction):
await self.interaction_callback(interaction, interaction.custom_id) # this part shortens your code
I am migrating my discord.Embed codes to discord.ui.View completely. So ig where ever I am require select, button etc... I need to do that thing with manual labour
I mean can't really change much at the moment, could maybe add an argument to add decorator items after everything else but no promises
Yea so I can't use those decorators anywhere, cuz there always be a Container() persent and I want that to be always at top ¯_(ツ)_/¯
I could look at it if you want nelo
Eh I guess in your init you can rearrange it like self.children = [self.children[4]] + self.children[0:4]
If you want, but from the library's perspective my suggestion is quite a pain
There are many ways, but a straight forward way would be lot better, so I will just go with manually arranging the things in discord.ui.View(), cuz don't want to repeat same like using decorators then again rearranging them
I get what you want but it's just not that simple unfortunately
all in all it looks good, i think you could do with making less things async but that's more of a nitpick than anything
Thank You for ur review ❤️
allgood
See I did this, one thing is this way of clearing the whole view and adding all items back is making the response 1-2 sec slower
nitpick but still....
This was previous iteration
fwiw, in this example you only need a single callback; in interaction_callback, replace your action with interaction.custom_id (or just do action = interaction.custom_id)
then all the buttons just use 1 single function
(though you aren't setting custom_id like your original code, i would recommend setting it here in that for loop)
Remaining code will be as it as?
and I sould expect that delay?
i think the rest of your code is fine, the delay... i'm not sure
but why are you multiplying your guilds by 15
lol you noticed that, this was testing bot and ofc not much guilds so to test the pagination I did that 🤓
The clearing and re-adding all the items is the cuplrit
and atp I see n oother way to edit the thing in other possible way
U mean the * 15?
nah something internal
oh
random guess, it might be faster if you add the buttons to the container instead of the view because they use different logic
A heartfelt thank you, @errant trout. Thank You so much for spending time explaining and helping me out ❤️
allgood 
Is it compatible with python 3.13?
yes, but you need audioop-lts
Does master need audioop-lts?
no clue
No
don't think so
i believe we have a pure python impl
Help i have discord.errors.LoginFailure: Improper token has been passed.
import discord
bot = discord.Bot()
@bot.event
async def on_ready():
print(f"{bot.user} is ready and online!")
@bot.slash_command(name="hello", description="Say hello to the bot")
async def hello(ctx: discord.ApplicationContext):
await ctx.send("Hey!")
bot.run("My super duper secret client key")
pass the right token
generate a new one and put it in
and dont use ctx.send with slash commands
I took the example on the site, also fixed. WHY THERE ARE 100 KEYS??! I though client key is the one but i was wrong, i had to go to the bot section and there was token
Thank you anyways ❤️
one is the bot ID, the public key is idk what, and the token is what you need to use to log in
Can you link the site you saw that on if you still have it open
i've installed (and reinstalled) master but it's still happening
also i keep getting RuntimeError: No active exception to reraise when i get an error in a command no matter what it is
@bot.event
async def on_application_command_error(
ctx: discord.ApplicationContext, error: discord.DiscordException
):
if isinstance(error, (commands.NotOwner, commands.MissingRole)):
await ctx.respond(ephemeral=True, content="you can't use this command!")
else:
await ctx.respond(
ephemeral=True,
content="an error has occurred, please do not try again",
)
raise
am i missing something?
explicitly re-raise the exception
also, you dont need to pass the message content as kwarg
what... does that mean
https://guide.pycord.dev/popular-topics/error-handling#global-handling i copied from this forever ago, it worked back then so i never changed it
dont just do "raise", actually raise the exception again
ah so "raise error"
as is in the example :)
i might've just been stupid when copying it over
i don't remember that being there
well... thanks for answering my redundant questions
fwiw, raise can be a bareword, but you'd have to be directly within an except context.
Will there be any downside about using persistent button for every view ?
Valid reason
Will that be consequent ?
i would say that is a valid reason yes
simply not worth it is a great reason that I use all the time
I was thinking about just making a auto generative custom id + a function that add every class discord.ui.view at startup
if a user clicked a button I would have to reinitialize the state of the entire command
So it would not have beeen that difficult to setup
simply not worth the effort when they can just... run the command again
eh at that point skip persistent views entirely and just use an on_interaction listener
May be a good idea, so I can tell the user when the view is not working anymore
If a view is not persistent and a user clicks on it, where should I handle that ?
i mean quite literally, make views without callbacks and handle EVERYTHING in your cog's on_interaction
if you want control over which buttons this applies to, just have custom_id start with something consistent
I was more thinking about handling that globally, like if it’s a interaction from a view but it’s not a persistent anymore : do smth, either send a message ettc. Since I’m a bit afraid of the ram outage
I’ll look that this afternoon when I finally have a computer with a screen
is it possible to check if a server is a partner server / verified server ? I don't see it in the docs
and the types partnered and verified are in the official discord docs https://discord.com/developers/docs/resources/guild#guild-object-guild-features
okay mb it is in the discord.Guild.features
👍 it looks like we don't have an enum for it because it changes too much
in v3 I hope to have a @discord.component(custom_id) for viewless components interactions
i feel like that should be the default anyway, but maybe too radical
pretty much, guild features are way too dynamic
No not too radical
instead of that maybe add something like dpy has: DynamicItem, but in a py-cord way
I think we should have persistent component items that use regex for item ids
that would be cool
Ooh that could be veryy cool
actually just have a predicate that you pass in
def component(
predicate: str | Callable[[str], bool]
) -> Callable[[Callable[[Interaction], Awaitable[Any]]], Component]:
...
v3 ideas
holy typing
Typing decorators is horrible :/
What am I supposed to expect from on_member_update events when I have member cache disabled?
@commands.Cog.listener()
async def on_member_update(self, before: discord.Member, after: discord.Member) -> None:
I want to check when ppl get a specific role, but can I expect before.roles to be there without member cache? (particularly on big servers)
I don't think it calls at all with cache disabled
that's what the on_raw_* methods are for I think
could be wrong but I mean try it lol
I did get the thing triggered but on a small testing server, I just can't really systematically test on big servers bc that's on prod and I can't grant roles there.
I think the after should always be accurate bc the gateway sends the user obj on the member update event, but I'm just not sure about the before obj
afaik there's no on_raw_member_update tho
Yeah, on a small testing server
Oh, actually I only get it when it modifies the bot itself, not other users orz
member_update does not fire if the user isn't cached, and raw_member_update doesn't exist
tbf, even though there's nothing to compare to every cache-reliant event probably should have a raw variant
Thank you for confirming this
I agree, I was thinking of maybe opening a pr although I guess the usefullness of this is limited
go for it if you want
im pretty new to python and stuff and was wondering which code im supposed to install to get one thats fixed for voice? do i download the master?
hopfully this isnt too basic
YOLO Time
Thank you to all the Ghosts before me
Ig here is a Bug For Components v2.
Although I send/edit the response with:
discord.AllowedMentions(users=False, roles=False, everyone=False)
Which means it should not ping anyone. Still it pings the user after editing message after timeout....
I've passed disable_on_timeout=True so after the timeout (default 180.0s) when it edits the view it pings the user
This is how the HelpView() looks like
ehhh not a cv2 issue but the behavior is a bit silly
to be clear, it still doesn't ping the user but just shows the orange highlight
yes cus on editing any message it doesn't ping user lol
even on normal messages like this @errant trout
per discord docs
When the message flag
IS_COMPONENTS_V2is set, the reconstructed arrays and boolean are based on the edited content in the components array. Theallowed_mentionsfield of the edit request controls how this happens. If there is no explicitallowed_mentionsin the edit request, the content will be parsed with default allowances, that is, without regard to whether or not anallowed_mentionswas present in the request that originally created the message.
basically, you have to write your own on_timeout with allowed_mentions
aah
I can but was searching for some easier way
for reference, this is the default on_timeout ```py
async def on_timeout(self) -> None:
if self.disable_on_timeout:
self.disable_all_items()
if not self._message or self._message.flags.ephemeral:
message = self.parent
else:
message = self.message
if message:
m = await message.edit(view=self)
if m:
self._message = m```
there isn't really a convenient way around this, allowed_mentions is not preserved on the message so we can't automatically reapply the same settings
yup yup
Maybe we can pass allowed_mentions field in discord.ui.View too
that will be easier ig
i considered that but it's not very intuitive
yup cuz it will then conflict with the allowed_mentions in ctx.respond()
well theoretically you can just have it override if you specify, but it's too disconnected from messages
well yes
Ig in docs we can mention this that will be ping the roles/users if we disable childern using disable_on_timeout
i'd say for your usecase, if you need allowed_mentions to be preserved in many situations then write your own view class with an overridden on_timeout which you can use instead of discord.ui.View
😵💫
well it's not that scary
not about scary, its about another custom class 😭 derived from wrapper
eh not necessarily a bad thing
mmm looks fine?
Doing this I need to keep updated with future breaking changes
is Bot.latency set to float('inf') if the bot is reconnecting to the gateway?
for context, the bot has been online for 2d 45m and I got an Overflow error with the following code:
{"latency": blueprint.bot.latency, "latency_ms": int(blueprint.bot.latency * 1000)}
if there is no available or recent heartbeat then it'll return inf
Quick question: I have a message_command that can be used via user install or guild install. Is there an easy way to differentiate if its being used from a guild install or user install?
Basically what I want to do is have it use ephemeral response if its being used from a user install.
it's a tad convoluted, but you're looking for ctx.interaction.authorizing_integration_owners
user_id if it's the user's authorization, guild_id if it's the guild's
ah user_id is probably always shown
basically, if guild_id is 0 or None then the app was not authorized by that guild
Yup
ctx.interaction.authorizing_integration_owners.guild_id is None
Seems to work
tks
Maybe im just blind, but how do you make slash commands for a user installed application? I've made a command successfully for a server, but it does not populate into my user installation, and I cannot find in the docs or pycord guide what differences i need to make are for server command vs user command
using the contexts
would you be able to elaborate on that a little more? i dont know what you mean by this, and i dont see what you mean in the guide
Here's the slash users example.
here an example, you can use the contexts params with the decorator or passing it inside the group
amazing, thankyou for this help!
evening all
been dabbling with a bot to log stuff to a gsheet for a game
now this bot sees only at most one or two requests per mins. Unless someone spams the bot, which can happen. Then you're looking at 4-5 requests in a short timespan (less than 5s?)
some users have been getting errors. Upon testing, I'm hitting a "404 Not Found (error code: 10062): Unknown interaction" error. How would one go around this? I'm guessing this hits discord API rate limit perhaps?
Cheers
that happens when you take longer than 3s to respond
so weirdly
its happening when invoking defer
which i use cause talking with gsheet takes > 3s so it did that earlier
are you sure the defer itself causes that?
File "c:\users\taledo\appdata\local\programs\python\python310\lib\site-packages\discord\commands\core.py", line 138, in wrapped
ret = await coro(arg)
File "c:\users\taledo\appdata\local\programs\python\python310\lib\site-packages\discord\commands\core.py", line 1082, in _invoke
await self.callback(ctx, **kwargs)
File "j:\mybot\main.py", line 66, in delivery
await ctx.defer()
File "c:\users\taledo\appdata\local\programs\python\python310\lib\site-packages\discord\interactions.py", line 783, in defer
await self._locked_response(
File "c:\users\taledo\appdata\local\programs\python\python310\lib\site-packages\discord\interactions.py", line 1292, in _locked_response
await coro
File "c:\users\taledo\appdata\local\programs\python\python310\lib\site-packages\discord\webhook\async_.py", line 222, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction```
here's the stack trace
but I don't think its defer in itself
i think its any command trying to access that specific interaction
the object exists and I can print it. I have however no idea on how to verify if it exists discord size
nah, I do a quick sanity check on one of the input and tell the user if its incorrect
then i defer yes
try make the defer the first line
this is the check
hm
let me try
but it shouldn't take 3s to check the quantity
yea no lol
where is your server located physically, and does it happen every time you run that command?
or well in that case where is your pc located lol
its not constant, it sometimes happens and sometimes doesnt (which is a pita for replicating)
discord api servers are only in the US i think
but it also happens during testing locally?
did it change anything?
just tested, sadly no
Could you measure how long it takes to make a request?
Like, use time.perf_counter per say
i mean, if the API servers are in the US its probably around 300 to 500ms
sadly I can't really test the perf of the library creating the interaction object
I mean the request itself, not the objects
in your command body add time.perf_counter and save it as a variable , then whenever you do something like await respond (for the discord api) call perf counter again and sub the latest - the first and that is the seconds it took
okay so I've timed a few defer requests, ranges from 0.2s to 0.3s, very rarely >2s
its possible that by the time the bot actually gets to the defer command, 3 secs have passed
making it impossible to defer as the interaction doesn't exist anymore
I... have no on how to deal with that
appart from, like, moving the damn bot oversea lol
either your bot has blocking code or your internet is scuffed
of course lol
nah i meant, I have gigabit fiber and a good ping to most stuff
but sure, if the server is on the other side of the planet
could be your router, your network card..
but wait it happens on your vps too, right?
indeed
yea then its most likely blocking code in your bot
like large file operations or whatever that takes long, e.g. using requests.get or time.sleep or stuff
or pillow
sync db requests also kill
yes, thats the point
look i never said i was a good dev, I'm a network engineer
i'll make the switch to aiohttp
hopefully that fixes it
if it doesn't, well, I'll ask people to be more gentle damnit
poor bot
btw options have min_value and max_value built in
in any case, thanks to you two!
yea
lets just say the slash command is very new to me
no worries LOL, just figured it'd be useful
last time i made a bot (like, 4 years ago) we used ! lol
wait it wasn't 4 years ago. More like 6.
welp, back to it, cheers all
hello, how to make the select/dropdown menu when selected any options it will go back to the placeholder (without editing the message, just automatically resets the view)?
it will reset the menu after selecting a option then an ephemeral text will be sent
you have to edit the message with the view again
something like await interaction.edit(view=self) would work
without editing the message — like after clicking it will go back to placeholder
it does work but I want it to reset the view without editing the message

like sapphire
sapphire presumably edits it
discord has no way of resetting the dropdown without editing
...sorry, i'm still confused; could you make this a video? (on windows, press win + shift + r)
from yt: after clicking an option to the menu it just go back to the placeholder
still confused?
usually when after clicking an option to the menu, it will stay on the option you selected; I want it after you select it will reset and go back to the placeholder automatically
usually view=self only resets the menu when you restarted the discord
I want it to reset immediately
from all my testing, this straight up isn't possible; i do not know what method sapphire is using
oh i see that's nasty
oh (?)
they're editing the message flags which counts as an edit but doesn't show the edited text
e.g. interaction.edit(suppress=True)
I just wanna know if it's possible with the workaround with it?
literally do that
this?
When pycord releases components v2
Traceback (most recent call last):
File "the file", line 426, in _scheduled_task
await item.callback(interaction)
File "the file", line 62, in callback
await interaction.response.send_message(
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
content=f"こんにちは、ご返信ありがとうございます。",
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ephemeral=True,
^^^^^^^^^^^^^^^
suppress_embeds=True
^^^^^^^^^^^^^^^^^^^^
)
^
TypeError: InteractionResponse.send_message() got an unexpected keyword argument 'suppress_embeds'```
or I did it wrong (?)
look at what i typed...
.cv2
Components V2 are under development in py-cord and aren't yet included in the official releases on PyPI. As of July 21st Components V2 is available on the master branch. You can access the features now by installing directly from the master branch. To do this, use the following command: pip install git+https://github.com/Pycord-Development/pycord.git
Please be aware that this is a development version and may contain bugs, feel free to report them opening an issue on the Github repo.
hi all, me again,
First of all, fixed my bad code with aiohttp, looks like its working, it passes QA (sending a lot of stuff fast) so here we are!
Second, is there a way to get the roles of a user that used a slash command? i had looked a while ago but to no avail
I can get the author name, which is fine and dandy for logs, but I don't see the user id
nvm I'm an idiot, ctx.user.id.
ctx.author.roles
cheers
look at the docs btw, applicationcontext has a bunch of useful stuff
Hi guys. I'm tryin to add my bot to a server, it has nearly 4k members.
I'm facing some issues, so first of all the listener on_guild_join was not called, now i'm trying to run this command:
@slash_command(
name="log_channel",
description="Imposta il canale di log per i comandi.",
)
@commands.check_any(
commands.has_guild_permissions(administrator=True),
require_role(CommandEnum.SET_LOG_CHANNEL)
)
@commands.guild_only()
async def log_channel(
self,
actx: ApplicationContext,
channel: Option(
TextChannel,
"Scegli il canale di log"
)
):
guild = actx.guild
success = await set_guild_log_channel(guild, channel)
if success:
await actx.respond(f"✅ Canale di log impostato su {channel.mention}.", ephemeral=True)
else:
await actx.respond("❌ Errore nell'impostazione del canale di log.", ephemeral=True)
but it gives this error:
Ignoring exception in on_interaction
Traceback (most recent call last):
File "C:\Users\tarsi\AppData\Roaming\Python\Python312\site-packages\discord\client.py", line 412, in _run_event
await coro(*args, **kwargs)
File "C:\Users\tarsi\AppData\Roaming\Python\Python312\site-packages\discord\bot.py", line 1217, in on_interaction
await self.process_application_commands(interaction)
File "C:\Users\tarsi\AppData\Roaming\Python\Python312\site-packages\discord\bot.py", line 871, in process_application_commands
await self.invoke_application_command(ctx)
File "C:\Users\tarsi\AppData\Roaming\Python\Python312\site-packages\discord\bot.py", line 1137, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\tarsi\AppData\Roaming\Python\Python312\site-packages\discord\commands\core.py", line 432, in invoke
await self.prepare(ctx)
File "C:\Users\tarsi\AppData\Roaming\Python\Python312\site-packages\discord\commands\core.py", line 353, in prepare
if not await self.can_run(ctx):
^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\tarsi\AppData\Roaming\Python\Python312\site-packages\discord\commands\core.py", line 460, in can_run
return await async_all(predicate(ctx) for predicate in predicates) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\tarsi\AppData\Roaming\Python\Python312\site-packages\discord\utils.py", line 708, in async_all
elem = await elem
^^^^^^^^^^
File "C:\Users\tarsi\AppData\Roaming\Python\Python312\site-packages\discord\ext\commands\core.py", line 1919, in predicate
value = await func(ctx)
^^^^^^^^^^^^^^^
File "C:\Users\tarsi\AppData\Roaming\Python\Python312\site-packages\discord\ext\commands\core.py", line 1853, in wrapper
return predicate(ctx) # type: ignore
^^^^^^^^^^^^^^
File "C:\Users\tarsi\AppData\Roaming\Python\Python312\site-packages\discord\ext\commands\core.py", line 2196, in predicate
permissions = ctx.author.guild_permissions # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\tarsi\AppData\Roaming\Python\Python312\site-packages\discord\member.py", line 676, in guild_permissions
base.value |= r.permissions.value
^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'permissions'
In my private server the bot works just fine, what can be the problem?
this reminds me of a weird bug with ctx permissions
can you try with
.tag master
pip install -U git+https://github.com/Pycord-Development/pycord
-# Note: The Master Branch May Have The Newest Features But It May Also Have More Bugs
The docs for the master branch: https://docs.pycord.dev/en/master/
for some reason member.roles contains None