#Basic Pycord Help
1 messages ¡ Page 65 of 1
ah - this one? https://guide.pycord.dev/popular-topics/cogs
Cogs, often known as modules or extensions, are used to organize commands into groups. This is useful
ye
yes
k reading now
If I want to send an attachment and have a file url, is there a way I can directly "pipe" the url to discord without having to re-download it to use less network ressources ?
I guess you can put it as filepath of a discord.File
very maybe
actually no that'll do the same thing I think
I don't think that's possible
alternatively just directly send the link lol
Giving the cogs another shot, quick question on it. where in the individual cog file in the setup() function does the bot object that is passed to setup come from?
Cogs, often known as modules or extensions, are used to organize commands into groups. This is useful
nowhere
it's just a standardised function that bot.load_extension calls
oh nvm I misread
well bot.load_extension calls setup(bot) very basically
in other words, when bot.load_extension('cogs.greetings') is called, ...
yep okay thanks
I don't want users to see the source url
after a brutal amount of hours spent on entitlements, discord documentation, discord.py and pycord documentation, and random stack overflow pages, I can confidently say that I did it. My first premium shop item is live. That took WAY too long, and I'm just glad it's over.
đ
(never used them so limited opinion)
thank you. I think I'm going to go get a cold beer and a lawn chair from walmart and just sit in my driveway
I fully agree. You can only get your SKU id from an api endpoint or from the url of your SKU in the dev portal. And then, you have to deal with EntitlementIterators only to realize that they DON'T WANT TO ITERATE. And THEN, you discover the golden chapel of interactions.entitlements, which returns a simple list of Entitlements that the invoking user owns, and all is right in the world.
lol
with cogs, we still need to call bot.run though correct?
if __name__ == "__main__":
cogs_list = ["referral"]
for cog in cogs_list:
bot.load_extension(f"cogs.{cog}")
bot.run(SWEEPY_TOKEN)
yes
hey guys I just have a question: persistent views, alright so they are kind of persistent, so they work everytime the bot is online, but are there cases where persistent views don't work?
fr?
really the only case I could think of
thought you were joking
When, you dont re-add them to your bot when you restarted
well yea but that's kinda required for a view to be considered persistent
the whole bot.add_view stuff
I just have to set the timeout to None and give every item a custom id right?
is there a different task decorator that needs to be used in cog?
@tasks.loop(hours=1)
no
and is it okay to have on_ready() defined in multiple cogs or is that a bad idea?
How it works is when you send a button (or other component) to discord it has a custom_id attached to it. Every time a user clicks the button discord send the custom ID to your bot and the bot finds what view it was "attached" to to and does the callback. So as long as your bot can receive the custom ID from discord (bot is online) and is able to find what view the button was attached to (there exists an "active" view that has a component with the same custom ID) it will work
does the on_ready retrigger on every cog through is forexample bot just disconnects / reconnects?
@commands.Cog.listener()
async def on_ready(self):
await self.update_contributors.start()
yea
Yes, you can add once=true to the listener tho
like this?
@commands.Cog.listener(once=True)
async def on_ready(self):
await self.update_contributors.start()
I believe so
yes
hey guys - ive almost fully migrated over to cogs but having an issue with a custom decorator that was previously working to validate the value provided from an autocomplete - I cant use Options as there are too many values i want the user to be able to select
def check_casino_name(casino_name):
if casino_name in CASINOS:
return casino_name
else:
return None
def validate_casino_name(func):
@wraps(func)
async def wrapper(ctx, casino_name: str, *args, **kwargs):
valid_casino_name = check_casino_name(casino_name)
if not valid_casino_name:
return await ctx.respond(ERROR_MESSAGE, ephemeral=True)
return await func(ctx, casino_name=valid_casino_name, *args, **kwargs)
return wrapper
class Casino(commands.Cog):
def __init__(self, bot):
self.bot = bot
@discord.slash_command(guild_ids=[GUILD_ID], description="Lookup information about a casino")
@validate_casino_name
async def info(self, ctx, casino_name: discord.Option(str, "Choose a casino", autocomplete=discord.utils.basic_autocomplete(casino_name_autocomplete))):
# Look up the casino info by name in the CASINOS dictionary
casino_data = CASINOS.get(casino_name.lower())
if casino_data is None:
await ctx.respond(f"'{casino_name}' is not a valid option. Please make a selection from the list", ephemeral=True)
return
getting this:
Ignoring exception in command info:
Traceback (most recent call last):
File "/Users/ethan/Python Projects/EliteSweeps/.venv/lib/python3.12/site-packages/discord/commands/core.py", line 138, in wrapped
ret = await coro(arg)
^^^^^^^^^^^^^^^
File "/Users/ethan/Python Projects/EliteSweeps/.venv/lib/python3.12/site-packages/discord/commands/core.py", line 1078, in _invoke
await self.callback(self.cog, ctx, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Casino.info() got multiple values for argument 'casino_name'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Users/ethan/Python Projects/EliteSweeps/.venv/lib/python3.12/site-packages/discord/bot.py", line 1137, in invoke_application_command
await ctx.command.invoke(ctx)
File "/Users/ethan/Python Projects/EliteSweeps/.venv/lib/python3.12/site-packages/discord/commands/core.py", line 435, in invoke
await injected(ctx)
File "/Users/ethan/Python Projects/EliteSweeps/.venv/lib/python3.12/site-packages/discord/commands/core.py", line 146, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: TypeError: Casino.info() got multiple values for argument 'casino_name'
not entirely sure where the multiple value is coming from, only thing really that changed is this info function is now part of a cog
you are passing casino_name twice, thats the entire problem
run kwargs.pop("casino_name")
you are passing it via **kwargs, and then explicitly
i think thats the issue at least
or no wait
i dont think so because this worked fine before putting in cog
since its in a cog it has self now, and your wrapper doesnt respect that
not just dummy lol
just do like wrapper(cog, ctx..)
its not a dummy because it serves a purpose :)
same for then calling the function below
sorry could you elaborate on this?
youre saying this
def validate_casino_name(func):
@wraps(func)
async def wrapper(cog, ctx, casino_name: str, *args, **kwargs):
valid_casino_name = check_casino_name(casino_name)
if not valid_casino_name:
return await ctx.respond(
f"It doesn't look like I know which casino `{casino_name}` is. Make sure you select a casino name from the dropdown and if it's not an option, open a request in #1318685820823142471 with the `new casino` tag.",
ephemeral=True,
)
# Pass the valid casino name to the command function as a keyword argument
return await func(ctx, casino_name=valid_casino_name, *args, **kwargs)
return wrapper
and then what else?
ah duh yeah sorry
okay let me try it
yep that did it - thanks!
Alright cogs up and running thanks all! definitely feels much more organized... now the main thing i wanted to work on today đ ... I currently have a subscriber only forum channel that the bot automatically posts to. I want to have some sort of way that once the post is over 24 hours, it then becomes visible to everyone regardless of if they are subscribed...
What would be the best approach to go about doing this? Is is possible to move an entire thread from one forum channel to another while keeping all its tags/comments etc.? For example like a public 'archive' forum channel that everyone can always see that threads get moved into after the time threshold
no, you cant move threads list that, you'd need to redo it
hmm, is there a way maybe then for when i post the thread to only have it visible within that channel to a certain role, and then after the time limit make it public?
no idea
why does the load_extension -with the recursive arg ignore every file which begin with _
because it should
yeah but why ?
because a _ prefix indicates private or unused things in python
even for a name file ?
guess so
how should i name my file for i can appear at the top of the other but still be use
maybe 1setup
but its very strange asf
file order really shouldnt be a consideration lol
its easier to find a setup file at the top of a folder rather than idk where
__init__
this is for a package, and it will not be load because of the _
i used to do init even if ik i shouldnt
just gonna do !setup
looks better
just for defining that group?
nah, its for everything that will be related to the group and not only a command, like event to add xp, loop for role etc
just rewriting my bot with a new db thats why its empty
Traceback (most recent call last):
File "C:\Users\SchĂźler\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\commands\core.py", line 138, in wrapped
ret = await coro(arg)
^^^^^^^^^^^^^^^
File "C:\Users\SchĂźler\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\commands\core.py", line 1078, in _invoke
await self.callback(self.cog, ctx, **kwargs)
File "C:\Users\SchĂźler\Documents\Botify\cogs\Admin\admin.py", line 290, in premium
"%Y-%m-%d %H:%M:%S") if entitlement.starts_at else "Unbekannt"
^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'int' object has no attribute 'starts_at'
premium_entitlements = await get_premium_users(self.bot)
desc = "Bot Entitlement Users:\n\n"
for entitlement in premium_entitlements:
starts_at = entitlement.starts_at.strftime(
"%Y-%m-%d %H:%M:%S") if entitlement.starts_at else "Unbekannt"
ends_at = entitlement.ends_at.strftime(
"%Y-%m-%d %H:%M:%S") if entitlement.ends_at else "Unbekannt"
desc += f"{int(entitlement.user_id)} - Start: {starts_at} - End: {ends_at}\n"
get_premium_users isnt something from pycord, so if thats your own function, fix what it returns
currently its evidently a list of ints
not sure why https://docs.pycord.dev/en/stable/api/clients.html#discord.Bot.entitlements cant do
Bots: Attributes activity, allowed_mentions, application_flags, application_id, auto_sync_commands, cached_messages, cogs, debug_guilds, default_command_contexts, default_command_integration_types,...
this is the function
async def _get_entitlements(bot: discord.Bot):
return await bot.entitlements(exclude_ended=True).flatten()
async def get_premium_users(bot: discord.Bot) -> list[int]:
"""Get all premium user IDs, This does not include custom premium users."""
return [
entitlements.user_id
for entitlements in await _get_entitlements(bot)
if not entitlements.deleted
]
that is not something built into Pycord by default unless it's just not documented
and I mean if you looked at it you'd see you get user IDs only, not entitlements
yes
yea so I don't know what you're doing if you know lol
just use this
and where is this from
this is my code

I got it
In this error, your entitlement variable is an int. Your get entitlements method returns a list of user ids, which are ints
did you do this with chatgpt
Why is it that when i try and run both of these tasks on ready, only the first seems to run?
class Casino(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener(once=True)
async def on_ready(self):
await self.update_freebie_stats.start()
await self.archive_old_threads.start()
It seems to work if i remove the awaits - but im not sure if thats the proper way to handle this?
.start() is not meant to be awaited
you can, but it will wait until the task gets cancelled
since it returns the internal task
also you should not start tasks in on ready, you should use wait_until_ready in the task's before method
you can see examples here: https://docs.pycord.dev/en/stable/ext/tasks/index.html#discord.ext.tasks.Loop
One of the most common operations when making a bot is having a loop run in the background at a specified interval. This pattern is very common but has a lot of things you need to look out for: How...
Ah wow okay Iâm definitely doing this wrong will try updating to the example flow today
Thanks!
cant you add the await wait_until_ready at the begining of the loop ?
trying to follow this - i dont understand why update_leaderboard is just calling itself?
class LeaderboardCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.update_leaderboard.start()
self.leaderboard_embed = generate_leaderboard_embed()
leaderboard = SlashCommandGroup(name='leaderboard', description='Leaderboard commands.')
@tasks.loop(minutes=10)
async def update_leaderboard(self):
print('Updating leaderboard...')
await update_leaderboard()
I think this is the correct approach though?
class Casino(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.archive_old_threads.start()
@tasks.loop(hours=1)
async def archive_old_threads(self):
logger.info("Archiving threads older than 24 hours...")
# ...Rest of code for this function
@archive_old_threads.before_loop
async def before_archive_old_threads(self):
await self.bot.wait_until_ready()
What are you trying to accomplish here? Calling the loop function manually?
I originally had this and was told its inaccurate way to do it #1132206148309749830 message
just trying to have some tasks start up and run in background
to not start them in the on_ready
Okay, it seems okay, but what do you exactly donât understand
You said âI donât understand why update_leaderboard is just calling itself?â
??
yeah i was confused too - thats from the docs
Concept
in the example
yea, its calling a different function
yeah i gathered that after but confusing since its named the same as the one its in
yea its kind of a bad example name, wildcard import doesnt help
then when do you want to start them
I do want them to start right when the bot starts, but @edgy nest mentioned to not actually do it in the on_ready, and pointed to the guide, which states to start it in the init (which im doing now i think accurately)
It really doesnt matter where you start them
moving from #1132206148309749830 message to #1132206148309749830 message
but you should put await self.bot.wait_until_ready() as the first line of your task
that ensures it doesnt start too early, before cache is present
well yeah i just have it in the before loop now
class Casino(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.update_freebie_stats.start()
@update_freebie_stats.before_loop
async def before_update_freebie(self):
await self.bot.wait_until_ready()
never knew you could even split loops like that, weird
Am i doing something wrong here? the after_loop doesnt seem to ever run. I am seeing the 'TEST DONE' get printed but not the "thread archiving complete" message
@tasks.loop(hours=1)
async def archive_old_threads(self):
cutoff_time = datetime.now(timezone.utc) - timedelta(hours=24)
channels = [await find_channel_by_name(self.bot, "freebies"), await find_channel_by_name(self.bot, "promos")]
for channel in channels:
for thread in sorted(channel.threads, key=lambda t: t.id, reverse=True):
if thread.created_at <= cutoff_time and not thread.archived:
logger.info(f"Archiving thread {thread}")
await thread.archive()
print('TEST DONE')
@archive_old_threads.before_loop
async def before_archive_old_threads(self):
await self.bot.wait_until_ready()
logger.info("Archiving old threads...")
@archive_old_threads.after_loop
async def after_archive_old_threads(self):
logger.info("Thread archiving complete")
are you ever stopping the task?
the after loop is not when the loop is done, its when its stopped (not sure)
ah so if we have a loop that is going every 1 hour, it would never "stop" then right?
i guess i can just put that log message at the end of the function itself and not overengineer it lol
im not sure about that
well if i have this for if it errors out, and there shouldnt be any other scenario where i want it to stop so i think i dont need after_loop then
@archive_old_threads.error
async def error_archive_old_threads(self, error):
msg = f"An error occurred while archiving old threads: {error}"
logger.error(msg)
await send_moderator_message(self.bot, msg)
so this all makes sense for a task thats on a loop, but what if there is a task i just want run once when the bot starts up... still not best practice to put in on_ready?
async def refresh_invite_cache(self):
logger.info(f"Refreshing server invites cache...")
async with self.server_invites_lock:
guild = self.bot.get_guild(GUILD_ID)
invites = await guild.invites()
self.server_invites = invites
logger.info(f"Server invite cache refresh complete!")
@commands.Cog.listener(once=True)
async def on_ready(self):
await self.refresh_invite_cache()
The other way i was thinking to do it could be like this, but not sure the implications of having a function declared as a loop and then also having other events call that same function?
class Referral(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.refresh_invite_cache.start()
@tasks.loop(count=1)
async def refresh_invite_cache(self):
async with self.server_invites_lock:
guild = self.bot.get_guild(GUILD_ID)
invites = await guild.invites()
self.server_invites = invites
logger.info(f"Server invite cache refresh complete!")
@refresh_invite_cache.before_loop
async def before_refresh_invite_cache(self):
await self.bot.wait_until_ready()
logger.info(f"Refreshing server invites cache...")
@refresh_invite_cache.error
async def error_refresh_invite_cache(self, error):
msg = f"An error occurred while refreshing invite cache: {error}"
logger.error(msg)
await send_moderator_message(self.bot, msg)
@commands.Cog.listener()
async def on_invite_create(self, invite: discord.Invite):
await self.refresh_invite_cache()
@commands.Cog.listener()
async def on_invite_delete(self, invite: discord.Invite):
await self.refresh_invite_cache()
at that point just make a seperate helper function that the task also calls
also what is count=1?
oh is that not valid? i was using it previously here and it seemed to be working
@tasks.loop(count=1)
async def run_fastapi(self):
logger.info("Starting FastAPI server")
config = uvicorn.Config(self.app, host="0.0.0.0", port=8080)
server = uvicorn.Server(config)
await server.serve()
im asking what it is
well what i am trying to do is essentially when the bot starts, run the refresh_invite_cache 1 time
why make a task for that?
and then the listeneres when invites get created / deleted, it runs it on demand
just call the function?
literally just call the function
there is no point to make a task that only runs once
I was previously doing it like this
@commands.Cog.listener(once=True)
async def on_ready(self):
await self.refresh_invite_cache()
but was now going into all the code and refactoring away from using the on_ready
i dont see the issue with that
Doing things in on_ready is generally bad unless you are using once=true
oh yea that was what I forgot thx
Sealy time! Todayâs question isâŚ(drumroll for dramatic effect)âŚwhich @after_invoke() decorator should I use for my slash commands if I want to save a log of that command being executed to my DB? I presume it would be ApplicationContext, but I notice that when building the decorator it asks for a âselfâ parameter. Am I good to simply skip it and say âcoro=testâ?
applicationcontext is not a decorator
And what if I have parameters I want to pass to that method as well?
The docs made me interpret that there was a discord.ApplicationContext.after_invoke decorator
ApplicationCommand*
Brain went brrr for a second, sorry
Found it, thanks
Back to the other question then, is there a way to pass params to it?
doubt, why?
My solution was going to be adding a decorator to handle all methods instead of adding it to each individual one. If not, then Iâll find another way lol
Just seemed it would be more convenient to do it that way so I only had to look at the top level of the method instead of searching through the methodâs code for the call
how can i inquire if the server has owner premium then the others should also have premium automatically
wdym "owner premium"
I think they mean how do they check if the server owner has premium so they can allow other members of the same server to use premium commands
https://docs.pycord.dev/en/stable/api/models.html#discord.Guild.owner here, thats all you should need
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 ...
yes
thanks
Hmmm. Does my bot need the (privileged) message content intent, to be able to retrieve its own messages with Channel.fetch_message() ? (I'm getting '403 Forbidden (error code: 50001): Missing Access', so it would seem possibly so, but it seems pretty weird that a bot wouldn't be able to retrieve its own messages)
No, you would not get that error even with other messages. You just would get blank content fields
Can you check if your bot has the read messages permission in that channel?
Ah, do you mean "read message history"?
Yes
ah, does not. Still seems weird it wouldn't be able to retrieve its own messages (by id, anyhow), but I guess I can see the logic. That works, at any rate, thanks!
Yeah, it would make sense to allow that but it might be difficult to implement on discords side đ¤ˇââď¸
Are there built-ins for creating group dm's? If not, any suggestions for getting a group of users from different guilds a medium to message each other?
bots cannot create a group dm because bots cannot be friends with another user.
You can use the bot to relay the message though
What about adding users to a guild?
you can create invites, yes
Is there an example of the slash command option for mentionable input?
Didn't see it in the Guide or the github Examples folder, but could've sworn I've seen it before
i really see very little use for something like that tbfh so not sure if its worth an example
Well it's a good thing you're not the fucking king of pycord
What I'm saying is that it's pointless to make an example for something that barely has any real use
This is what I mean when I tell you that you're an asshole. It's not for you to say what has real use or not. Newsflash, I actually need it for something, so it has use.
you dont understand what im saying. try and stop being dick.
I do understand what you're saying - King Fucking Toothy doesn't think something matters, despite it being available, so nobody else should use it or be able to find information on how to implement it
sorry for offering my opinion
i cant change how you view what i say, maybe fix your mindset
if you think it matters, PR an example
Maybe stfu when someone asks a question and you don't have a constructive answer. It's been like this with you for as long as you've been here.
again, i cant change how you react to me giving my opinion
remember i said I see little use for that. i very explicitly gave my opinion
you are free to ignore it
But note that I (nor anyone else that posts here) didn't ask for opinions. People here ask for information. Your "opinion" does not belong unless specifically requested.
i mean you already said it doesnt exist
No, I said I was having trouble finding one; it wasn't a definitive conclusion that it didn't exist. Reading comprehension. Even if I did, the underlying question was how to use it; it still wasn't asking you what you personally thought about it.
For future helpers: I found it. (inferred from a GH Issue)
Dang you two like to yap
But I do agree with Debau
@sage tendon this is a help channel. You're no judge about how people use the library. The man was looking how to do mentionable inputs, you shouldn't give a fuck about what he uses it for, just provide the help.
no
I thought it was merely about the lack of a specific example, not how to actually use it
Is there something that lets you update the bot without having to restart discord entirely?
maybe reloading cogs
/extensions
but I think there are issues w/ slash commands and that currently
can u set up cogs so u can reload them while the bot is up?
yes
ill take a look thanks for letting me know
Paillat is right that it is kinda broken rn. It might work for your case but there are lots of glitches
đ
I might try to fix it in the next ~1 month but don't know if I will have time
appreciate it eitherway
i have a pretty decent way that i do it atm
it uses importlib and also just basic cog reloading
Mentionable as in mentioning a user? If so, then I type cast my input variable to a discord.Option(discord.Member, description=âMember you want to selectâ)
mentionable is typically roles, channels, users
Yeah, thatâs what I did. And I needed to have roles and users, so found that you have to Union (for some reason canât use 3.10 syntax of Member | Role - or at least it whines)
Ahhhh I understand now. Clever. Iâll keep that in mind if I ever need it lol
Python whines anytime I use discord.Option but I hit it with the silliest move (#type: ignore)
using the decorator version (@discord.option) gets rid of that warning, and is also a bit cleaner imo
Trying to use the VoiceClient to record audio from a stage, but I'm getting very choppy audio. Anyone have any experience with this? Or is this process pretty resource hungry?
Voice is a sea of mysteries.
Nobody really uses it so nobody really knows how it works
Nobody really uses it so nobody really knows how it works
Nobody really uses it so nobody really knows how it works
Thanks for the reminder of what i said squid
why does the info not show in the blue command thing, its apart of the actual command
Because it probably just shows the parent command
Idk ask discord
doesnt do that for other bots that use command groups 
Discord being discord i guess
bug probably
test for a bug
I don't think so.
hm, i see the subcommand there on mobile
same for desktop
test for question
Yes.
Yeah, guess not
probably some odd build discord broke something in again
This might seem dumb but is there an event for when someone adds a user-app to their account (kinda like on_guild_join but for user-apps)?
Been looking at this page but can't seem to find a list of events anywhere (also including google) đ
https://docs.pycord.dev/en/stable/api/clients.html#discord.Bot.event
i think discord's last message on that was that its "coming next"
nothing since on that topic afaik
Quick question, can i use py cord with python 3.13?
For the most part, but if you want voice, you'll need to install audioop-lts
I don't plan to use the vc stff soon
Thank you
It's not officially supported.
Just use 3.12.x
ok
#general message
Thanks, I'll take a look in a bit :)
yea, but it doesnt work at all if you dont install that
you need audioop regardless of if you use voice features or not, it'll crash during startup
unless there is some lean install version of pycord without any of the voice features
They specifically choose not to make it available over the gateway for some reason.
maybe they'll add it soon given this message, but who knows
since custom emojis are a thing now
no, however you can use webhooks
when somebody moves a channel to a new position, is there a way for a bot to see who did it? the action triggers discord.on_guild_channel_update but doesn't seem to show up in the audit log
If it's not in the audit log I don't think so
Also the audit log seems like it has been a bit let behind lately
New features aren't necessarily logged properly anymore
ah, i see
Not saying that on_guild_channel_update is a new feature
Very late, but pretty sure they don't bother with the event on channel move because it would have to trigger for every single channel below it
oh, that makes sense
I mean, I guess. But they could have short-circuited it to just note the intentionally-changed position
hey guys I am a bit confused
This is currently the channel status, only a few people can view the channel and actually join it
@bot.slash_command(name="some")
async def some(ctx: discord.ApplicationContext):
await ctx.respond("OK")
for member in ctx.channel.members:
await ctx.channel.send(str(member))
currently, this is what the bot is printing
seems perfectly like expected then
I mean, how? Am i using the wrong property to get the users in the channel or
hm
Each user (there is a selected group of users) that can only send and view the channel
Those are the only permissions: view and send
And yeah intents are Intents.all()
does it print all members of the server?
What was that
i was off by 1 to the right on my keyboard
just as confused too
can you make sure that ctx.channel is the right one idk this seems weird
This is weird
since
If I do this:
@bot.slash_command(name="some")
async def some(ctx: discord.ApplicationContext):
channel = ctx.guild.get_channel(1325911264941314059)
await ctx.respond(f"len: {len(channel.members)}")
then it gives me the correct result:
len: 12
can you do print(ctx.channel == ctx.guild.get_channel(id))
@bot.slash_command(name="some")
async def some(ctx: discord.ApplicationContext):
channel = ctx.guild.get_channel(1325911264941314059)
await ctx.respond(str(ctx.channel == channel))
you dont need to cast everything to str lol
caching?
can you do the same with the member amount of the channels
Member count of ctx.channel.members is 712
and if I use get_channel then it gives me 12 which is the correct result
can you do it with fetch_channel
with the assert?
mystr = str(len(ctx.channel.members))
channel = ctx.guild.get_channel(1325911264941314059)
await ctx.respond(f"{mystr} {len(channel.members)}")
can you try that
using fetch_channel
@bot.slash_command(name="some")
async def some(ctx: discord.ApplicationContext):
channel: discord.TextChannel = await bot.fetch_channel(1325911264941314059)
await ctx.respond(f"fetched result: {len(channel.members)}")
#await ctx.respond(str(ctx.channel == channel))
This is what members returns so I dont know why channel cache would have anything to do with it
return [m for m in self.guild.members if self.permissions_for(m).read_messages]
@bot.slash_command(name="some")
async def some(ctx: discord.ApplicationContext):
channel: discord.TextChannel = await bot.fetch_channel(1325911264941314059)
mystr = str(len(ctx.channel.members))
channel = ctx.guild.get_channel(1325911264941314059)
await ctx.respond(f"{mystr} {len(channel.members)}")
its weird
Should I make it an issue then in gh or
@bot.slash_command(name="some")
async def some(ctx: discord.ApplicationContext):
#channel: discord.TextChannel = await bot.fetch_channel(1325911264941314059)
mystr = str(len(ctx.channel.members))
channel = ctx.guild.get_channel(1325911264941314059)
await ctx.respond(f"{mystr} {len(channel.members)}")
if you want you can open an issue. I will keep looking into it though
Right, thanks yall for giving it an attempt
One last thing you can try is printing ctx.channel.overwrites and channel.overwrites I think the interaction channel is not getting its overwrites set properly.
issue created
will try that
@bot.slash_command(name="some")
async def some(ctx: discord.ApplicationContext):
from_ctx = ctx.channel.overwrites
from_get = ctx.guild.get_channel(ctx.channel_id).overwrites
await ctx.respond(f"From ctx:\n\`\`\`{from_ctx}\`\`\`\nFrom get:\n\`\`\`{from_get}\`\`\`")
You get the idea
Yeah, thats what I suspected. That narrows down the issue but I would have to do a lot more testing to find where it is actually wrong
I think this is only an issue in private channels or channels with permission overwrites. It should work properly for "normal" channels
Trying to debug some of my code that's broken after a Pycord update.
I'm currently decorating a Cog method for a slash command with the following:
@commands.slash_command(
name = "scan",
description = "Scan the monitored servers for a problematic user, without raising a proper Alert.",
guild_ids = list(fcy_constants.ENABLED_ALERT_GUILDS.keys()),
guild_only = True,
cooldown = None,
)
That's raising an exception, for which the relevant portion of the traceback is:
File "/home/lux/.local/lib/python3.13/site-packages/discord/commands/core.py", line 257, in __init__
raise InvalidArgument(
"the 'contexts' and 'integration_types' parameters are not available for guild commands"
)
(There's also a @discord.commands.option decorator, but that's not what the traceback is telling me is causing the exception.)
Based on the source code, it seems like the guild_only kwarg is considered to be deprecated. Is the fix for this simply removing the guild_only = True kwarg and decorating the method with @discord.commands.guild_only instead?
(I know I can just try that and see if it works, but I want to make sure that's the right solution rather than a hack that works for reasons I don't understand.)
You should set contexts instead
which in your case will only be discord.InteractionContextType.guild
Cheers; I'll go ahead and try that, although I'm somewhat confused, since the documentation says:
contexts
The location where this command can be used. Cannot be set if this is a guild command. [emphasis added]
Yeah, I'm actually still getting the same error with either using the guild_only decorator instead, and with setting contexts = discord.InteractionContextType.guild instead
And that makes sense, given what I'm seeing in the source code (discord/commands/core.py line 1269) - it looks like I can't pass guild_ids along with any way to declare that the command is only available in a guild setting.
But that... seems like something one would want to be able to do... right? I would think there needs to be a way to do that?
The source code doesn't seem to imply this anywhere, but does setting guild_ids implicitly mean that the command is now guild-only, or something like that?
i think so
A command registered to a specific guild is only available in the guild itself
Not in other places like global commands
I think I found it, imma make a pr tomorrow as soon as I can
đ
idk it gives this
what is 'it'?
sounds like you entered into the python repl by accident
In the console run quit()
alr thanks
I made a PR that is on master rn for that I think
1. Uninstall discord.py or any other forks of discord.py you might have with the namespace discord.
python -m pip uninstall discord.py discord -y
2a. Install py-cord
python -m pip install py-cord
2b. Update py-cord
python pip install -U py-cord
Installing other builds:
Note: You need to have git installed. Use ?tag git to find out how to install git.
Updating the module to master branch (unstable):
pip install -U git+https://github.com/Pycord-Development/pycord
No actually it's still open #2658
@torn barn âŹď¸
so... I tried to use run_in_executor but I get every time Command raised an exception: TypeError: BaseEventLoop.run_in_executor() missing 1 required positional argument: 'func'
just try passing None as first arg
that worked, thx
Add None as the first positional argument
oh he said it
Does the tag need to be updated them?
Add the "None" to it, that should be enough
is this a bug?
yes
I know server admins can restrict command visibility/usability to certain roles or permissions, but can you do that in the code?
like i want the command to not be visible to people without the Manage Channels permission, or just a specific role
is that possible?
@discord.default_permissions()
look it up in the docs
not possible to do it with roles though, only permissions
does it hide the command or just make it unusable, just curious
alright tysm
This is only the default permission when you bot is added to the server. Server admins can override this to whomever they want
Yea i read
This is more discord help but...if I had lootboxes to my bot is that ok? Like is that against ToS or Privacy Policy? I read both and it mentioned "illegal gambling", but the boxes aren't buyable. It's a daily reward.
I'm sure I've seen lootboxes that ARE buyable on other bots before, but want to double check because I'm a good seal
if it was on mee6, its not bound by any rules
mee6 is lawless because it's discords best selling bot
I wouldn't doubt that
Thanks y'all!
I read that one of the criteria was "Prizes have real-world value" and jokingly went "good thing my bot has no real world value" LOL

finna sell seal coins and be a gazillionaire frfr

How can I check if a guild has purchased a certain SKU? I tried it in a testing server and purchased a SKU, but it doesn't show up under guild.entitlements()
you actually bought the SKU? lol i think you can use test entitlements for it
but no clue about entitlements apart from that so
Devs can purchase any SKY for free @sage tendon
oh, ok
@maiden bloom is it the server owner youâre checking for?
If thatâs the case, you would check the user.entitlements of the server owner
Iâm not aware of how guild SKUs work as Iâve only used user subscription ones
No, Iâm checking for the SKU that was purchased for the whole guild. It was purchased by my testing account which is a dev but not the owner of the server. It was free
how
The testing account is part of the bot's dev team in the dev portal
It shows as premium under the guild integration settings and the shop shows that the current guild is subscribed
@maiden bloom Iâm sadly not sure. Where are you getting your guild reference from?
I know that when I was handling my entitlements I had to get them from a specific context
I tried getting it from a command context and also tried fetching the guild. Both have no entitlements
Are you using a test bot as well? Or is this on the main bot
Ik that I personally have a dev and prod bot for coding purposes
And that I pulled a silly once with entitlements where I tried grabbing entitlements from the dev bot that were for the prod bot
If not, then Iâm not quite sure. Discord doesnât have good docs related to entitlements, so I canât really suggest any of them to read sadly. I would say to look up your context in pycordâs docs and read what the entitlements fields are giving you
I spent a few hours browsing them and fully understanding what it needed, returned, and referenced before it clicked
Sorry I canât help more
Hi there, I have a few general questions that I've not been able to find clear answers to:
- Is it possible to place buttons in an ephemeral message?
- If not, is it otherwise possible to limit the use of buttons to a specific user?
- Is it possible to place buttons in an embed object?
Yes, yes and yes

Okay, excellent. Are there any handy examples which show how to do these things?
Pycord Guide is a complete guide for Pycord. Learn how to create Discord Bots today!
I have read the docs. I've not found anything that clarifies my original questions, thus why I asked them here. Otherwise I wouldn't be here.
What do you want to do?
Add buttons to an ephemeral message?
Specifically what I'm doing is sending a series of multiple choice questions to users, which would be great to set up as a series of interactive embeds with buttons for answer selection. The questions are directed at specific users and thus input must be filtered out to only the user who invoked the command to start the sequence.
If buttons can manage that then I no longer necessarily require ephemerality.
Well, it's easier to make it ephemeral.
Clarification for 3:
You cannot have buttons in an embed object. You can have buttons in a view that is attached to a message that also has embeds.
Also what nightmare is saying is that you can have a backend check to "direct" button at one user but making it ephemeral would make it so there users can't see the message and buttons at all
Here's the tic tac toe example.
If you are still struggling after looking at the examples you should post your current code with any errors you are getting
For what I understand, even if itâs not with real money etc you cannot play at some casino game
Even if itâs not related to real money
(This is the policy for premium app only)
@drowsy grove you might want to check that
I have it with fake money, but I see people that make gambling bots that succeed as well. They only go so far as to increase daily rewards, which is all Iâve done as well
I want to see if I can contact discord for an exact answer, because I donât want to break any of their policies
good luck
Because this seems very cut and dry, whereas the other things Iâve read say that itâs fine as long as it has no real world value
Itâs allowed for normal bit but not premium one
Thank you for pointing out the monetization policy, as I didnât know it existed @fresh sierra
Hi, guys. new to pycord. How do you limit all commands to one server for testing purposes
You can pass a list of guilds ids to debug_guilds= on your bot's init
thank you
hi, question about modals: if user input fails validation, how can I tell them that as the "Something went wrong" error appears? I've been trying to set the self.children[0].value to an error message, but it doesn't change.
this isn't possible
you basically have to accept whatever they input and respond to the modal so it closes
Ah. Alright, thanks
I think the best option is to send a message containing what the invalid input was with a button that allows them to re submit the model, possibly with the other values pre-filled in.
yup, seems like the next best option, thanks.
I combed through the Pycord docs and couldn't figure this one out. I submitted a bug report for it:
https://github.com/Pycord-Development/pycord/issues/2691
In a Paginator, are Page instances bound to a view / paginator, or can they be stored and reused across paginator instances ?
How do I create a custom command check?
def my_custom_check():
async def predicate(ctx):
# check goes here
Thank you
they are completely independent
Okkk thx
How can I create discord slash and context commands?
do you mean Prefix commands?
As in the ones that discord will autocomplete, (e.g. </cat:824701594695368767>)
that is a slash command
Yes, I would also like to know how you make the context menu commands, as in right click > apps > command
Official Pycord Guide: https://guide.pycord.dev/
These will help you get started along with the other examples in the "app_commands" directory on the github page. If you have more questions feel free to ask!
Thank you!
Is it possible to do with client, or just bot? nevermind
Client is only for events so you should use discord.Bot
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)
Yeah I figured that out, thanks.
How would you type a function return type (say it returns a list of whatever) as Immutable ?
I get it wouldn't actually be
just in typing
is there a way even ?
Would you not need to use a list subclass for that?
just use tuples
otherwise stuff like collections.abc.Sequence are considered immutable types (though, as always, not enforced)
I want to type it as an immutable list because after that it goes into another method that takes lists as params
make it take lists or tuples
shouldn't be breaking unless you mess with the list in certain ways in that method
they're both collections and iterable
if you specifically want it immutable and enforced, tuple is exactly what you want
if you only care to type it as immutable, then type it as Sequence
The method is not my own though
hm
convert it back to a list when you pass it to the method?
Hi guys
@bot.command()
@discord.option('amount', input_type=discord.SlashCommandOptionType.integer, min_value=1)
async def give(ctx, amount, target: discord.User):
...
Why does this error still appear
AttributeError: Option does not take min_value or max_value if not of type SlashCommandOptionType.integer or SlashCommandOptionType.number
it's type for the decorator i think
you can just pass it as the second positional argument, just remove the input_type=
and you can just use int, you dont have to use the slashcommandoptiontype thing
and you should typehint target as discord.Member
Yeah but I prefer letting discord check for the integer >= 1 instead of writing conditions
thats what you should do
@discord.option(âamountâ, min_value=1)
async def give(ctx, amount: int)
Should be the same but you will also get the type hint
i never said anything about that part lol
@bot.command()
@discord.option('amount', int, min_value=1)
async def give(ctx, amount: int, target: discord.Member):
...
this is what i meant
ahh I see thanks
Why put 2 times the int ?
in the option to make it immediately obvious just from reading the decorator, and in the function header to get proper autocomplete in the function code
Ok so just for more clarity
you dont need the int at the @option if you already did it at the amount
i know
This is why decorators for options are stupid
shhhh you are going to anger toothy
Let him go on his rampage about being wrong. If you define it in the method args, it's easier to follow and don't have to do it twice.
Hi, I'm here for some help. I used bot.get_user(), but is there a way to get their display name in a specific server?
You are looking for guild.get_member().
That returns a discord.Member object, which has a .display_name property
.rtfm discord.Guild.me
.rtfm discord.Guild.get_member
ctx.guild.me.display_name if its in a command
.rtfm discord.Guild.get_member
guild.get_member with a proper ID that I'm in returns a NoneType.
Using bot.get_user with the same ID returns a User object.
Any idea why that could be happening?
.rtfm discord.Guild.get_user
Target not found, try again and make sure to check your spelling.
=========
get_member also doesn't work. It returns a nonetype even if im in the guild, right ID, and right Guild ID.
Neither doing
members = guild.members
user = discord.utils.get(members, id=1008913569871564811)```
works.
I'm in the guild.
Guild name works correctly using guild.name.
why not this?
can you show the exact line you used
user = guild.get_member(1008913569871564811)```
`GUILDID` is valid and returns the correct `.name`.
Oh... ok
help imagine if it did
god no
...lag?
buffers
ooooh.
not a good idea
yeah definitely
thats kinda how it works in gateway
on startup you can receive every member of the guild, though it takes some time when scaling
I'm testing on a 1200 member server and its ok
yeah at that size it's instant
but if you scale it it gets messed up?
well in the most literal sense, the more members you have naturally the longer it takes
if your bot is connected to, let's say, guilds totalling 1 million members, the startup may take a few mins if you intend to receive all of them
How to call Pycord coroutine outside of an asynchronous context?
For example, outside a command or event handler
what do you wanna actually achieve
I have a thread running with a socket server receiving messages from another process
And I need to call some Pycord functions in it, such as role managing
asyncio ig?
Probably, but everything I've tried doesn't work
I'm wondering if there's some perfect way that's best used
When I use the asyncio methods I get
RuntimeError: Timeout context manager should be used inside a task
So, what do you want to do?
or for what do you need that?
Can't you run the socket server as a bot task?
#1132206148309749830 message
Why do I need to get data from another process?
Is this exactly the topic of the current question?
Hmmm...
I don't want to rewrite half of my code
Is there a way to purposely stall how long a button takes to respond after being pressed? I've tried using asyncio.sleep() in the button's callback method, but this breaks the button's functionality
why do you want to delay the response artificially
because I want to limit the user from spamming said button
Use cooldowns
just waiting wouldn't change anything
that wouldnt help at all tho?
okay well it would but.. no, dont do that
hence why im asking how to stop the user from doing this. I cannot find a solution
You should use cooldowns
you can use a ttl cache for example
I use aiocache
and you add a key for each user that expires after a set time
dont cooldowns only apply to commands?
Here i'm talking about a manual cooldown implementation in your bot
and in the button callback you ccheck if the key is present, if it is you return, if it isn't you set it and go on with the callback
Gotcha, thank you
what are the benefits of using cogs in my bot? i understand that i can group different commands, but are there any other benefits?
It's mainly for the QOL of your code
You can very well not use cogs at all and struggle a lot to maintain your code structure and quality
A wise man once said you read code much more than you write, so write good code that you'd want to read
why do user apps not work
from utils.extensions.user_apps import *
@discord.command(
integration_types=ALL_INTEGRATIONS,
contexts=DM_CONTEXTS,
)
class Bot(ezcord.Bot):
def __init__(self) -> None:
super().__init__(
intents=discord.Intents.all(),
language="auto",
debug=True,
error_webhook_url=ERROR_WEBHOOK_URL,
default_command_contexts={discord.InteractionContextType.guild},
default_command_integration_types={discord.IntegrationType.guild_install},
import discord
from discord import InteractionContextType, IntegrationType
ALL_INTEGRATIONS = {
IntegrationType.guild_install,
IntegrationType.user_install,
}
DM_CONTEXTS = {
InteractionContextType.bot_dm
}
User apps work, but you use ezcord, so no clue if they broke it
also never seen @discord.command
I will take a look with slash_command
might be a prefix command in ezcord, no clue what ezcord.Bot subclases
also, what exactly doesnt even work
does the command show or not, what happens if you call it..
thanks anyway
don't use ezcord
..so does it work now or
no i'll ask on the ezcord server
this
I just have 1000-line long cogs đŚ
Why ask here if you use ezcord
only 1k?
I have four out of 24 cogs with >1K lines (one is 2200)
Is there a way to rate limit slash commands?
The following section outlines the API of Pycordâs prefixed command extension module. Bots: Bot: Attributes activity, allowed_mentions, application_flags, application_id, cached_messages, case_inse...
The following section outlines the API of Pycordâs prefixed command extension module. Bots: Bot: Attributes activity, allowed_mentions, application_flags, application_id, cached_messages, case_inse...
is there a way to send a modal and then followup and edit a message
await interaction.response.send_modal(InputModal())
await interaction.response.edit_message(view=view)
like this but w/o the interactionresponded error
Hi, how do you apply CommandOnCooldown error handling (defined in main script) to commands in other cogs
you can add this
to a listener
thank you đ
how do I uh avoid pasting the same error handling to every cog
oh wait it's await
you don't have to
you can use on_command_error
like this
class MyErrorHandlingCog(commands.Cog):
@commands.Cog.listener()
async def on_command_error(self, ctx, error) -> None:
Yeah but let's say I have this script, I want to apply this to all commands in all cogs i.e. the whole bot
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandOnCooldown):
print("Print debug statement")
await ctx.respond(embed=discord.Embed(
color=discord.Colour.brand_red(),
description="You can use this command again in **{0:,} seconds**".format(round(error.retry_after))
))
I would suggest to use a decorator then, but it is maybe not the best
it seems non-cog commands also face the same issue. not sure if im doing something wrong
I also tried print debugging but it did not appear as well.
Update: tried removing the if isinstance statement but the print debug statement did not appear as well
Subclass all of your Cogs with Paillat's example class
ok. let me try that
something like this?
import discord
from discord.ext import commands
from main import MyErrorHandlingCog
class MoneyGame(MyErrorHandlingCog): ...
# Commands go here
def setup(bot):
bot.add_cog(MoneyGame(bot))
I recommend putting it in a separate file, as importing from main is generally a bad idea, but yes.
are you using slash commands ?
did you manage to have it working ?
yup
is there a better way to do this
@bot.command()
async def test(ctx):
"""please do not run this"""
result = await send_confirmation(ctx, ctx.user, "Press Confirm")
if result:
result = await send_confirmation(ctx, ctx.user, "I was joking, are you really really sure", followup=True)
if result:
result = await send_confirmation(ctx, ctx.user, "last warning, you will be ban", followup=True)
if result:
await ctx.followup.send("jk")
else:
await ctx.followup.send("ok")
else:
await ctx.followup.send("ok")
else:
await ctx.followup.send("ok")
if/else nests are bad
You can return after the jk and then only keep the ok at the end
interaction.edit_original_response
i'm having some trouble subclassing my bot and adding cogs, do i use commands.Bot for my bot class or do i use discord.Bot for my bot class?
I'm not sure, as I don't use discord.Bot
I would think there isn't, but that's a better question for one of the helpers
alright, thanks đ
you only need commands.Bot if you want prefix commands
if your bot is all on slash commands, context menu etc., then discord.Bot is fine
i see, thanks a lot
guys need help
How do I edit the original message and send an additional ephemeral message upon interaction (in a view)?
.rtfm Interaction.edit_original
thanks. May I know why does the following not work?
await interaction.response.edit_message(embed=self.embed, view=self)
await interaction.followup.send_message(embed=discord.Embed(description=text), ephemeral=True)
Do you get any errors ?
.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.
Sorry, here is the error.
AttributeError: 'Webhook' object has no attribute 'send_message'
it is
.rtfm Webhook.send
Ohh thanks đ
np lmk if anything
Using slash commands: How can I respond with "Bot is thinking" and then send the actual response. Discord allows more time to respond when sending a confirmation.
.rtfm defer
discord.ext.bridge.BridgeContext.defer
discord.ext.bridge.BridgeExtContext.defer
discord.InteractionResponse.defer
discord.InteractionResponseType.deferred_channel_message
discord.InteractionResponseType.deferred_message_update
discord.ext.bridge.BridgeApplicationContext.defer
discord.ApplicationContext.defer
.rtfm on_application_command
discord.on_application_command
discord.on_application_command_error
discord.on_application_command_completion
discord.ext.commands.Bot.on_application_command_auto_complete
discord.ext.commands.Bot.on_application_command_error
discord.ext.commands.AutoShardedBot.on_application_command_auto_complete
discord.ext.commands.AutoShardedBot.on_application_command_error
discord.Bot.on_application_command_auto_complete
discord.Bot.on_application_command_error
discord.AutoShardedBot.on_application_command_auto_complete
discord.AutoShardedBot.on_application_command_error
discord.ext.bridge.Bot.on_application_command_auto_complete
discord.ext.bridge.Bot.on_application_command_error
discord.ext.bridge.AutoShardedBot.on_application_command_auto_complete
discord.ext.bridge.AutoShardedBot.on_application_command_error
How can I create a voice channel that is only joinable if you received an invite link? If there is no direct way to do this, can the bot set a voice channel to only be joinable for certain usernames? (I want to avoid creating roles)
sure, you can create overrides for users just like in the UI
and no, you can't do the former for all I know
Thank you. Didn't realize overwrites directly allowed you to input users, not just roles
I know there is a way to allow users to join a voice channel (maybe only stage?) with an invite but not actually join the server. I have no idea how that works tho
Them joining the server is fine. Curious if there is actually a way around that tho đ
I think you mean visitor links that kick you if you leave the channel
^
not sure if you can use it here, maybe with some smart permission or role shenanigans depending on your server
I'm adding a premium feature that allows servers to change the embed color for the bot. I'm assuming fetching the guild's entitlements to check it's premium status for every single embed that is sent isn't a great idea.
Would having a scheduled task that runs every hour or so and checks the premium status of a guild and updates it in a database be more efficient or is there an easier method I'm not thinking of?
I see there's an event for when a SKU gets purchased, but not for when one has expired/ended
Caching is definitely better.
interaction.entitlements will include guild entitlements
if you manage these embeds through interactions, anyway
otherwise periodically checking isn't a bad idea
is it possible to have image on modal?
No
str input only
Quick question:
Can you make subgroups for a BridgeCommandGroup?
I want to have the commands:
game card blackjack (args)
game card war (args)
and have them as slash too
discord.ext.bridge.BridgeCommandGroup
discord.ext.bridge.BridgeCommandGroup.command
discord.ext.bridge.BridgeCommandGroup.ext_variant
discord.ext.bridge.BridgeCommandGroup.mapped
discord.ext.bridge.BridgeCommandGroup.slash_variant
discord.ext.bridge.BridgeCommandGroup.subcommands
discord.ext.bridge.BridgeCommandGroup.walk_commands
discord.ext.bridge.core.BridgeCommandGroup
that's not possible unfortunately
you would have to define slash and prefix versions separately
uhhh you could probably try with creating another bridge group and specifying parent
see #2035
otherwise apparently bridge never updated the create_subgroup function
yeah, i did rtfm, found nothing
it's not that big of a deal, but it would make life a bit easier if it was there
My ctx.guild.members returns 4300 while the server has 100k members
Iâm trying to get a specific role.members but that also just feels members 5 out of 50 get returned
I have all intents enabled and itâs a custom bot
just checking, does this happen to match your guild's online member count?
and show your main bot file
With with_counts=True
i think they want the actual members, the count was just to demonstrate their issue lol
oh maks sense
does this request check if "bot.is_ready()" returns True, before it is executed?
Itâs in a task.loop which starts when bot is ready event triggers
I havenât used is ready method to check though
First time it caches less members
Then second and onwards it works perfectly
Then the next 1.5 days it returns no members
hmmm, depending on the loop it might trigger several times during runtime. bots can have several "on ready" events when its online long enough.
soo depending on which loop its in, maybe not the best place.
however: b2t
would you make it a topic and share code + outcome, so we can have a closer look?
Why should you not able to run it?
Is there a good example that comes to mind of a bot that's also serving requests sent in via a webhook?
In particular, we have logic that serves /commands that we want to also serve an incoming webhook.
E.g. /statistics can be asked for by a user or from e.g. Zapier
And thse webhooks could be channel specific or across the whole server
I'm also wondering if Pycord has generic support to make all /commands capable of also serving webhooks
Or if this is something we need to build
Ohh
Sure Iâll do that (once Iâm allowed to be on pc Monday) đ
you will need to do it
because /command works with a context
why the http request doesnt create any
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...
If the webhook supplies user and channel, could it assume values for the rest of context?
I assume this is the right documentation- it says pycord 0.1 at the top
That is just a bug with the docs. Although you linked the 2.5.x version when latest is 2.6.x
You can change that in the little box in the lower right corner
I dont know exactly what you are trying to do but it sounds like you should have a structure like this
async def get_the_data(user, channel):
return ...
@bot.slash_command()
async def stats(ctx):
await ctx.send(get_the_data(ctx.author, ctx.channel))
// However you return a webhook thing to your service
I cant help more now but feel free to ask more questions
Are there any optimisations I can do to reduce the latency of my bot? Right now it's at 400ms and I'm unsure if that's normal.
The location of your hosting
make sure everything is async and else as dark said look for an hosting in the us next to the discord datacenter
You could try py-cord[speed] but idk how much faster that makes it. US East is location of discord servers
what is py-cord[speed] lol
Extra dependencies that are supposed to make the library work faster
what extra dependencies? is there a list
Probably somewhere. It aiohttp speedup stuff. Apparently it only works on some computer systems tho
only works as in the speed-up effect or it will crash completely?
I am not sure, I have never used it
oh alright
Thanks!
Thanks defi
Any ideas?
The bot has full administrator access (top role in the hierarchy), the category has 0 channels so thats also not an issue.
Nevermind, didnt specify any of thebeginning, end, before or after params.
Though, the error could be a little more descriptive.
having strange behavior suddenly in my but without having made changes. Events all work normally. but no slash command works anymore. and logger set to debug returns zero information when a command is executed. Only get "The application did not respond"
did you try a restart?
several times
your discord client as well?
try check this event
This section outlines the different types of events listened by Client. There are 3 ways to register an event, the first way is through the use of Client.event(). The second way is through subclass...
if that doesnt fire i guess discord somehow fails to send your bot the event?
nothin lol

You made sure to use @bot.listner() or similar right?
cog listerner yea
it was working fine when i went to bed
100% of all of my commands are dead
Did you override on_interaction?
negative
Can you override on_interaction and see if you get any events
how do you mean? i don't have any interactions
slash commands are interactions
i thought you meant in the sense of discord.Interaction
You should be able to put that event in place of the one you just had
Are you using cogs? If so are you ensuring they are loaded correctly?
make a new command and see if that shows up maybe
Or try running the basic slash example with your token
Here's the slash basic example.
made a new command, it registered in discord immediatly. but no execution, and nothing in log
Can you show how you are starting your bot and one of the command definitions?
do try this imo
would take a lot out of the equation
and you get the same issue when you run it locally or on your (i assume) server (as in VPS)?
@modcmd.command(name='godmode', description='Add or Remove Self From Admin-Mode')
@commands.is_owner()
async def godmode(self, ctx: discord.ApplicationContext):
member = ctx.author
role = discord.utils.get(ctx.guild.roles, id=ADMIN_ROLE)
if role in member.roles:
await member.remove_roles(role)
await ctx.respond('Removed from Admin-Mode', ephemeral=True)
else:
await member.add_roles(role)
await ctx.respond('Added to Admin-Mode', ephemeral=True)
i start it with systemd or just python main.py
i have a poweredge in home. only place i host from
exotic guess would be that something in the network route is somehow blocking those very packets
but idk how discord sends data so no clue if thats even possible
It sounds a little bit like you are cloud flare banned but that should be giving you an error
is discord using cloudflare ?
yeah
i have an event for creating voice channels if you join a "join to create" channel. that works.
or cloudflare somehow comes into the equation
everything about the bot works except for slashcommands
it posts logs for every event. like prescense, typing, voice status
Try the basic slash example from above please
nope
have you enabled logging yet?
yep in debug mode as well
DEBUG:discord.client:Dispatching event socket_event_type
DEBUG:discord.client:Dispatching event presence_update
DEBUG:discord.gateway:Keeping shard ID None websocket alive with sequence 5.
DEBUG:discord.gateway:For Shard ID None: WebSocket Event: {'t': None, 's': None, 'op': 11, 'd': None}
DEBUG:discord.gateway:For Shard ID None: WebSocket Event: {'t': 'PRESENCE_UPDATE', 's': 6, 'op': 0, 'd': {'user': {'username': 'cauan1000', 'primary_guild': None, 'id': '1288180297329803351', 'global_name': 'Cauan', 'discriminator': '0', 'clan': None, 'avatar_decoration_data': None, 'avatar': 'f44cb3daf7dbe4511b744a6b9dde42ab'}, 'status': 'online', 'guild_id': 'xxxx', 'client_status': {'mobile': 'online'}, 'activities': [{'type': 4, 'state': 'Vivendo sem Ăłdio đŤ ', 'name': 'Custom Status', 'id': 'custom', 'created_at': 1737155361910}]}}
DEBUG:discord.client:Dispatching event socket_event_type
DEBUG:discord.client:Dispatching event presence_update
i get these messages only
Are you doing anything "weird" with commands or do you think you have a pretty normal setup?
pretty standard. been running untouched for months
think the most complex thing i do is reachout to minecraft through RCON
or my temporary private voice channel system
Can you print
bot._listeners and self._handlers in on_ready
print(f'{bot._listeners} listeners registered.\n{bot._handlers} handlers registered.\n'
{} listeners registered.
{'ready': <bound method Client._handle_ready of <discord.bot.Bot object at 0x7f28eb2ab6e0>>} handlers registered.
You are on 2.6.x version of pycord right?
2.6.1
python version?
3.12.8
This is really weird, if basic bot does not work and you are up to date on other things I feel like it has to be something other than your code
You dont have multiple discord bot libraries installed do you (like discord.py, nextcord, etc)
nope. just py-cord
ill throw it onto another server quick
yep. same problem on cloud vps
but my other bots on other servers work
Is it specifically that guild? If you try testing your bot on a different guild do the results change?
try different bot token if you havent already
Yes
same issue
there really arent that many possible cases left then
pretty much HAS to be something with the code
OOH SHIT
bruh moment
oh 
maybe it takes a while to propogate after removing that
i put the damn endpoint url in the wrong bot
Make sure you hit save in the dev portal. Then you probably have to restart the bot again
ill let the bot sit offline a while. still borked. WTB ctrl+f5 for bots
i mean, stopping the bot does clear the cache lol
thats the one
there we go. i reset my token again and magic
sorry for the missing curly brace moment
đ
I was like you would know if you changed something in the dev portal. But it makes 100% sense how you would accidently do that.
yea my bots are named Axon, and Axon Verifiy
I am probably going to change my bots name one of these days because my password manager autofills my discord username into the bot username field everytime I open the dev portal 
lol
ProtonPass does that shit to me too
sometimes it enteres my password as the username
ProtonPass is legit ass
Tried to use it but nothing beats bitwarden
i like it, specially the passkey functionality
bitwarden has it too
just where i jumped to after lastpass failures. i got the unlimited subscription to the proton stack. i can't be bothered to hop again for a while
man i need to write a mod for discord where shell commands work in the text box. like ctrl-a and ctrl-e
is this normal when I'm trying to import pycord's discord package
happens on python 3.13+
either downgrade or manually install (i forgot the command tho)
wia pip install you mean?
Yes
pip install audioop-lts
^
thx
afaik 3.13.1 doesnt work at all tho, i think there was some bug
ive been using 3.13.1 perfectly fine
i did have to install audioop-lts but thats because it was removed in 3.13 after being deprecated in 3.11
other than that, no issues so far
why does making database querys cause discord to rate limit, but when i comment out database querys. everything is fine
you mean it times out?
database queries can take some time and unless you defer, you can't respond to an interaction after 3 seconds
no it force restarts the bot
2025-01-18 09:00:13,755:INFO:discord.client: Cleaning up tasks.
2025-01-18 09:00:13,755:INFO:discord.client: Cleaning up after 2 tasks.
2025-01-18 09:00:13,756:INFO:discord.client: All tasks finished cancelling.
2025-01-18 09:00:13,756:INFO:discord.client: Closing the event loop.
lol what
i have an on_message event that makes a db query
async?
yes
show your on message
@commands.Cog.listener()
async def on_message(self, message: discord.Message):
if message.author.bot:
return
db = AsyncSurrealDB(self.db_host)
await db.connect()
await db.sign_in(self.db_user, self.db_pass)
await db.use(self.db_namespace, self.db_db)
select_query = f"SELECT * FROM activity WHERE member_id = '{str(message.author.id)}'"
result = await db.query(select_query)
if result and result[0].get('result'):
update_query = f"UPDATE activity SET last_active = time::now() WHERE member_id = '{str(message.author.id)}'"
result = await db.query(update_query)
logger.info(f"{result}")
else:
insert = await db.create('activity', {
"member_id": str(message.author.id),
"last_active": "time::now()"
})
logger.info(f"{result}")
await db.close()
do you get a high amount of messages per second?
lol
but it does finish this function?
where does it get to
i dunno it just restarst the bot on message
it doesn't execute any of the logger methods
what is your self.db_host exactly
localhost
you should also consider not creating a new connection every time you receive a message but instead use some db pool
can you just put a print after each of the first 3 db lines
I think that the DB somehow interferes with the discord event loop
2025-01-18 09:07:48,221:INFO:discord: connect: <surrealdb.async_surrealdb.AsyncSurrealDB object at 0x7eff16186ed0>
2025-01-18 09:07:48,271:INFO:discord: signin: eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpYXQiOjE3MzcyMTI4NjgsIm5iZiI6MTczNzIxMjg2OCwiZXhwIjoxNzM3MjE2NDY4LCJpc3MiOiJTdXJyZWFsREIiLCJqdGkiOiJiOTg2MDk5Yy02MDQ3LTQ3NjktYWE3NC0zYjcxNzZkZjMyMGIiLCJJRCI6InJvb3QifQ.BzoqBrG0tF5rnNXTKtckRN6Er4nfciJ1LY8G4aJNccIA8jSBf4GOR_UM_uIY2jLp53PfCv0a4725cPLNpMLucg
2025-01-18 09:07:48,272:INFO:discord: use: None
2025-01-18 09:07:54,987:WARNING:discord.http: We are being rate limited. Retrying in 21.05 seconds. Handled under the bucket "None:1313644334465421312:/applications/{application_id}/guilds/{guild_id}/commands"
never
You can't be rate limited if you are not sending requests...
maybe auto syncing
modcmd = discord.SlashCommandGroup(name='mod', description='Moderation commands', guild_ids=[GUILD_ID])
thats how i do my commands
try disabling auto syncing
yea but they are being rate limited lol
well if i comment out the db queries in on_message. all the problems disappear
goes back to normal operation
huh
this is still my best guess but it's a bit far fetched because I'm not that good with how python async works at that level
yeah, that could not happen
Is it possible the DB is emiting the same error we catch for rate limits?
it wont even output to logger
can you find out exactly which line it gets to before it shuts down? might help

connecting to db
signing in
using db
('no decoder for tag', 12)
can you wrap all of your db stuff in a try except and print the type
kinda poking into nothing here but this is a very weird problem lol
try except yields nothing
await self.db.connect()
print("connecting to db")
await self.db.sign_in(self.db_user, self.db_pass)
print("signing in")
await self.db.use(self.db_namespace, self.db_db)
print( "using db")
select_query = f"SELECT * FROM activity WHERE member_id = '{str(message.author.id)}'"
result = await self.db.query(select_query)
print( f"result: {result}")
if result and result[0].get('result'):
print( "exist")
update_query = f"UPDATE activity SET last_active = time::now() WHERE member_id = '{str(message.author.id)}'"
result = await self.db.query(update_query)
print( f"update: {result}")
logger.info(f"update: {result}")
else:
print( "not exist")
insert = await self.db.create('activity', {
"member_id": str(message.author.id),
"last_active": "time::now()"
})
print( f"insert: {insert}")
logger.info(f"insert: {insert}")
yeah, wrap all of that on a try / except block
