#Basic Pycord Help
1 messages · Page 51 of 1
Technically we can actually assign a type to partialmessageable which fixes it, but this is a rather old issue
But it's strange, because if you recieve a message like in the error you should have the full channel no?
Looks like since it was a poll event the channel wasn't available
poll_event wasn't the actual event (that's just a gateway function?), was message_update
But either way I should probably adjust the behaviour
Oh messages don't even have full channel data ok
What's the method name for creating a post in a forum channel?
create_thread
What does it need channel data for anyways?
Polls?
They're always attached to a message, and have related methods, so yeah
i suppose that makes sense
as for this an isinstance would work as well
or just not checking the type if it turns out to be None (since that should only be possible for partialmessageable)
can someone help me here? #1271568482206617672 I've been debugging it since yesterday but still coudln't figure out why it's not working
Hey there, I'm looking for a way to know how many messages a user has sent in a channel in the past. Could someone nudge me in the right direction pretty please 😅 ?
(just to be clear I don't want to start counting from when my bot was added to a server, I want my bot to be able to check the history of specific channels to see who wrote messages in them and in the end obtain a list of users and how many messages they wrote)
TextChannel.history is a start. Not sure what the ratelimits are. Might take a while depending on the channels size.
Command raised an exception: Forbidden: 403 Forbidden (error code: 50013): Missing Permissions
What would the error handler be for that?
e.g, if isinstance(error, ???):
Exception Hierarchy:- Exception,-- DiscordException,-- ClientException,- InvalidData, InvalidArgument, LoginFailure, ConnectionClosed, PrivilegedIntentsRequired, InteractionResponded.,., NoMoreItem...
im using on command error if that makes any difference
If its a slash command, you should be using on_application_command_error
using on_command_error
elif isinstance(error, discord.Forbidden):
print("forbidden")
elif isinstance(error, discord.HTTPException):
print("http")
no responses
is it a slash command?
no
@commands.Cog.listener()
async def on_command_error(self, ctx, error):
if thats any help
what is type(error)
<class 'discord.ext.commands.errors.CommandInvokeError'>
ah i had that too
i'm pretty sure that means it's not a pycord exception
and you can get the actual error via error.original
i'm doing the same in my bot
if its not a discord exception, error.original will "unwrap" it
alright thanks
await channel.create_thread(name={nome_e_cognome}, embed=embed, auto_archive_duration=60, type=discord.ChannelType.private_thread, reason=None)
I got:
create_thread() got an unexpected keyword argument 'type'
i mean this to create threats
ForumChannels threads don't have a type argument
I assume they're always public. You can't create a private post
ok i'll try
400 Bad Request (error code: 40067): A tag is required to create a forum post in this channel
how to assign a tag?
You have to get the tags first
.rtfm ForumChannel.tags
Target not found, try again and make sure to check your spelling.
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 ...
And then just applied_tags=[the tags you wanna apply] to the method
There's any limit of ctx.followup.send?
Like I can send max 2/3 responses
yea i think you can do 2 followups after the original response
but you should use .respond, there's (afaik) no need to ever use followup.send
you can also do a 100 times a ctx.respond ;3
really? i thought discord limits it at 3 "responses"
There's no max
Except for user installed apps - they have a max of 5
Otherwise, your limit is 15 minutes
any particular reason for this choice?
Uhhh theoretical spam
hey! how could i use the utils module to get the name of a person from their id?
Utils module?
im looking at the docs but i have massive skill issue
Just use bot.fetch_user (api call, id should be int)
discord.utils would be unrelated
and prefer get_user if anyhow possible
If it's a member in one of the bots guilds, guild.get_member or bot.get_user
oh, right.. thanks ill check em
wait, why shouldnt i use get_or_fetch?
never said that
so i can use it?
eh, prolly, this isnt some super optimized bot to begin with
thanks all
sure
Damn
Kinda forgot to reply but I tested that out earlier today and it worked great ! Thanks for the tip 😉
Okay uhh turns out after further testing that even when you do not add a limit to the number of messages that you want to request, it still actually adds its own arbitrary limit.
Or wait it seems that actually when you do not add a limit it actually sets it to 100 by default
Yeah
What's the actual risk of setting it to 10.000/100.000/1.000.000
I'll just get rate limited and the command will take more time to execute, right?
Not like my IP is gonna get banned from accessing discord API (?)
That's gonna take a really long time
I did once do something similar and didn't get anything other than rate limit
Do you know if there's a cheap way to just get the total number of messages in a channel?
Nope
sigh
default limit is 100 because that's how much the api supports
So setting limit=None will do (total/100) requests
That being said, the library handles it with no issue
Yeah okay, makes sense.
It'll just take some time for large channels
Thanks for the help 🙂
class AutomationCog(commands.Cog):
def __init__(self, bot: discord.bot.Bot):
self.bot = bot
bot = discord.Bot()
bot.add_cog(AutomationCog(bot))
if __name__ == "__main__":
bot.run(DISCORD_KEY)
Traceback (most recent call last):
File "/var/home/lucas/Projects/werk/ti_automation/main.py", line 11, in <module>
bot.add_cog(AutomationCog(bot))
File "/var/home/lucas/.pyenv/versions/ti_automation/lib/python3.12/site-packages/discord/cog.py", line 666, in add_cog
cog = cog._inject(self)
^^^^^^^^^^^^^^^^^
File "/var/home/lucas/.pyenv/versions/ti_automation/lib/python3.12/site-packages/discord/cog.py", line 574, in _inject
raise e
File "/var/home/lucas/.pyenv/versions/ti_automation/lib/python3.12/site-packages/discord/cog.py", line 568, in _inject
bot.add_command(command)
^^^^^^^^^^^^^^^
AttributeError: 'Bot' object has no attribute 'add_command'. Did you mean: 'all_commands'?
does someone know if im doing something wrong? im trying to make cogs to split up my discord bobt
why bot.Bot?
also can you show the pip list pls
i kind of figured it out, i was using discord.bot to create the bot instead of commands.bot
but now none of my slash commands show up haha
from discord.ext import commands # noqa: I002
from config import DISCORD_KEY
from dc.cogs.automation import AutomationCog
bot = commands.Bot()
bot.add_cog(AutomationCog(bot))
if __name__ == "__main__":
bot.run(DISCORD_KEY)
any clue if i need to do more in order for them to show up again
ahh im trying to follow the tutorial: https://docs.pycord.dev/en/stable/ext/commands/cogs.html
There comes a point in your bot’s development when you want to organize a collection of commands, listeners, and some state into one class. Cogs allow you to do just that. The gist: Each cog is a P...
Cogs, often known as modules or extensions, are used to organize commands into groups. This is useful
thanks!
any clue which typehint i should use for ctx? when using a slash_command this typehint doesnt work: ctx: commands.Context
ahh thanks!
its either right or wrong lol
yeah hahah tho i meant the extension crashes when using the wrong one
that shouldnt happen for all i know lol
discord.errors.ExtensionFailed: Extension 'dc.cogs.automation' raised an error: TypeError: Invalid class <class 'discord.ext.commands.context.Context'> used as an input type for an Option
ah
Hey. How can i make a list with activitys for the bot like playing Minecraft or watching Youtube or something else, and choice one of it every 30 seconds?
.rtfm tasks.loop
discord.ext.tasks.loop
discord.ext.tasks.Loop
discord.ext.tasks.Loop.add_exception_type
discord.ext.tasks.Loop.after_loop
discord.ext.tasks.Loop.before_loop
discord.ext.tasks.Loop.cancel
discord.ext.tasks.Loop.change_interval
discord.ext.tasks.Loop.clear_exception_types
discord.ext.tasks.Loop.current_loop
discord.ext.tasks.Loop.error
discord.ext.tasks.Loop.failed
discord.ext.tasks.Loop.get_task
discord.ext.tasks.Loop.hours
discord.ext.tasks.Loop.is_being_cancelled
discord.ext.tasks.Loop.is_running
discord.ext.tasks.Loop.minutes
discord.ext.tasks.Loop.next_iteration
discord.ext.tasks.Loop.remove_exception_type
discord.ext.tasks.Loop.restart
discord.ext.tasks.Loop.seconds
Use this (first result)
ok thanks 🙂
That's because you're somehow setting ctx as an option.
You're either adding extra arguments or you're missing arguments.
ctx is an option...
no
ctx counts as an option at the slash_commands
Any idea how to develop custom slash commands per-server or per-user?
If you mean that a server can run /create_command text: Hello here is the starting point:
Bot.add_application_command than Bot.sync_commands but make sure to set guild_ids and the command just in case the library does not handle it well you do not want to hit ratelimits
Like toothy said I dont think per-user is possible
wouldnt that still count towards the 200 limit
you get 200 global and 200 per guild a day
might be 100 per guild. Not 100% sure but I know you get some per guild
How do I sync channel permissions with category?
then it's synced by default
oh ok
alr so is await discord.Emoji.read() fix ?
?
bcs it not rlly work
you are giving me 0 context my guy
or it not work with discord.Guild.create_custom_emoji parameter "image"
ye but english is not my main langage so idk how to explain it
or lemme me send u my code in dm
don't DM me
so u can see wth I mean
why
i dont want it
we can be ban ?
send it here
alr so
commands.command()
async def create(self, ctx : commands.Context, emojis : commands.Greedy[discord.Emoji]):
for emoji in emojis :
await ctx.guild.create_custom_emoji(name=emoji.name, roles=[ctx.guild.default_role], image=await emoji.read())
and what about that doesn't work?
idk the code send me 0 error in response but it don't work idk how to fix it
in fact it will work
so I thought it was a api error in the code
ik
so you're using an emoji from another guild?
and a guy tell me I need self.bot need to be in the guild
well, yea
but with other bot it work without that
the guild of owner emojis
too 😂
no, for all i know
well just asking, is it possible or no
lol
well you clearly have a reason to ask
and its better to fix that earlier
but no, not easily for all i know
alright thanks
They are just numbers at the end...
i still wanna know why you ask
The closest thing is to assume they're checking authorizing_integration_owners
Can I set the min_value and max_value dynamically like this or will this only get set when I start the bot
I see. Thank you
Damn
Also variables I cannot auto fill? Like a command that is server based and have a option per-server
if you want diff options per server you can make a different command for every server
:p
but you can't change the options constantly
Hi there again, does someone know if there is a way to add colour to a single field's value in an embed?
is it possible to have a slash command with the same name as a command group?
Should be possible yes.
/test test should be possible
i don't quite mean that
but that was your question
rather, having
/test that does something
and /test something which does something more specific
or whatever
Also I don't understand your question
Embeds have a color you can set
Single embed field values are just values with text etc. you cannot fill it out with just a color
i'm mainly just curious
You can make multiple commands that do the same tho, yet its still registered as a different command
what
I want the text of the value to be a certain a colour obviously 😂
There is code blocks that you can sometimes set to different colors
Welcome to [2;33mRebane[0m's [2;45m[2;37mDiscord[0m[2;45m[0m [2;31mC[0m[2;32mo[0m[2;33ml[0m[2;34mo[0m[2;35mr[0m[2;36me[0m[2;37md[0m Text Generator!
Rebane's Discord Colored Text Generator
Only works on PC I think
Or if you only need 2 colors you can use diff
+ Green
- Red
just say you want colored text >.>
I thought there would be something specific for fields in embeds but if that works then I'll take it 😄
Thanks for the help
Make an image with a transparent background but with colored text that matches the size and font of discord 
Oh I hadn't understood that it only worked in code blocks. That looks ew.
shame there's nothing better 😦
Hello, i need add 2 buttons or more using classes, how to do it? discord.ui.View
use the decorator to create buttons inside the view class
pretty sure that's all in the guide
from discord.commands import Option
@bot.command()
async def help(ctx,options:Option(str,"this is a option", choices=["fun","admin"]))```
and stay in one place asking for help please
There no 2 buttons or more
just add another decorator for a button lol
@discord.ui.button(label="Узнать Кто Написал", style=discord.ButtonStyle.grey, emoji="❓")
async def button_callback(self, button, interaction):
await interaction.response.send_message(ctx.author)
@discord.ui.button(label="Узнать Кто Написал", style=discord.ButtonStyle.grey, emoji="❓")
async def button_callback(self, button, interaction):
await interaction.response.send_message(ctx.author)```
Like this?
yea
But shows 1 button
function names have to be unique
really? i thought the decorator just consumed them basically
no lol
The decorator changes the method to an attribute of type Slash command but it is still there
Still typing?
Some one help
r=random.randint(1, 70)
class MyModl(discord.ui.Modal):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.add_item(discord.ui.InputText(label="Угадай Число от 0 до 70", style=discord.InputTextStyle.long))
async def calback(self, interaction: discord.Interaction):
if self.children[0].value == r:
await interaction.response.send_message(f'Вы угадали число и это был: {ctx.author}')
else:
await interaction.response.send_message('Вы не угадалм число.')```
Bot didnt send something 'if else'
whatever you're doing, its wrong i think
Learn how you can implement Modals in your Discord Bot with Pycord!
Js help
Pls
Ik modals but whats wrong my code
oh nevermind i thought that was a view class
well, did you try print if it gets into the callback at all?
No
Didnt works
is the print the first line in your callback?
No, lemmi try
Not working
but the modal shows up?
Yes
also uh, you're using ctx inside of your callback
there is no ctx
oh bruh, your callback is called calback
typo
@alex.event
async def on_message(message: discord.Message):
if not (message.author.bot):
if (message.attachments):
channel = alex.get_channel(os.getenv('MEDIA_ID'))
for img in message.attachments:
channel.send(img.url)
If I send a message with an image the debugger shows attachments list and content as empty. I'm pretty stumped as to why
I have a past project that did something similar and it looks the same
are you sending the image via a link?
also, you dont need brackets around the if conditions lol, this isnt java
ik lol, old habits die hard
and no, its a drag and drop file
message.content is also empty
you dont have message content intents then most likely
I thought I did. I'll double check
thanks i fixed the code
yup, I had it as default instead of all
ty
❤️
np
what does a command group's description affect?
For the first order it's what is shown in the Interactions tab in server settings
Also application directory stuff
How can I make it so that when I press a button, other buttons appear for me?
edit the view of the message
Example pls
just pass another view to the message by editing it
or send a new message with the new view
await interaction.edit_original_response(view=view)?
try it and see
Didnt works
Unknown Webhook?
I dont have some webhooks in code
all interactions are webhooks in a way
A ok
but idk then, im too tired, someone else maybe
Okay
Easy question
User has no attribute timeout
user: discord.Option(discord.Member)
Whats wrong
if it's actually a user object, it has no guild specific stuff
a user is a discord user without any relation to a guild
User to didnt work
you probably put in the ID of someone not in the server you're using the command in
discord.User too didnt work
yea because user is what you DON'T want
How to fix it?
put in the ID / mention someone who is in the server, then you'll get a member object
Same error
show your code
forget it, it works. But keyword argument 'seconds'
?
Code
await user.timeout(seconds=1800, reason='Panel Muted')```
Error
Member.timeout() got an unexpected keyword argument 'seconds'```
@sage tendon
check the docs
and use timeout_for
Can u write some example
no
you need to pass a datetime.timedelta object
the pycord docs link to what that is
Hwo read this..
cant help you with reading it i'm afraid
Pls just make example
how do i make a discord.ext.tasks.loop() function not run upon a bot's startup
for example, if i have a task that runs every 15 mins, how do i make it run for the first time 15 mins after startup rather than upon startup?
I'm not sure if the library has a function that handles that case, but you could use a flag that indicates that the bot started for the first time:
# Flag indicating that the bot was started for the first time
flag = True
@tasks.loop(minutes=15)
async def example():
global flag
if flag:
await asyncio.sleep(900) # 15 Minutes
# Change the flag
flag = False
# Your code...
i see, thx
use the time argument instead https://docs.pycord.dev/en/stable/ext/tasks/index.html#discord.ext.tasks.Loop.time
also fun to automatically construct it, e.g. this does every 30 mins of the day py times = [datetime.time.min] for i in range(47): times.append(datetime.time(hour=math.ceil(i/2), minute=(not (i%2))*30))just gotta figure out the right logic for your use case
turns out, adding a sleep in the task.before_loop worked
petition to make tasks accept cron time formats
just implement it wyd
pr it then :)
How come when I execute a slash command. it doesnt allow me to run anymore commands? Like none show even in the integrations tab in discord settings
Yeah
restart discord and see if it happens again
Yeah its still happening
so you cant even use the same command again or what
show your code
Which part
import discord
import os
import config
bot = discord.Bot(intents=discord.Intents.all(), debug_guilds=config.DEBUG_GUILDS)
col = config.COL
for file in os.listdir("cogs"):
if file.endswith(".py"):
name = file[:-3]
bot.load_extension(f"cogs.{name}")
print(f"[-] ✅ Loaded {name}")
@bot.event
async def on_ready():
print("##################################################")
print(f"[-] ✅ Logged in {bot.user.name}#{bot.user.discriminator} | {bot.user.id}")
print("##################################################")
await bot.change_presence(status=discord.Status.idle)
bot.run(config.TOKEN)```
yes
do you have any on_application_command listener
can you show one cog
Thats my listener
One of
import discord
from discord.ext import commands
import config
import app
import msgs
class DevCmds(commands.Cog):
def __init__(self, bot):
self.bot = bot
@discord.slash_command()
async def reload(self, ctx, file: discord.Option(str, choices=config.choices)):
check = await app.dev_check(ctx=ctx)
if check:
self.bot.unload_extension(f'cogs.{file}')
self.bot.load_extension(f'cogs.{file}')
await ctx.respond(f"Successfully reloaded `{file}`", ephemeral=True)
@discord.slash_command()
async def load(self, ctx, file=''):
check = await app.dev_check(ctx=ctx)
if check:
if file == '':
await ctx.respond(msgs.ERR_LOAD_FILE, ephemeral=True)
else:
self.bot.load_extension(f'cogs.{file}')
self.bot.sync_commands
await ctx.respond(f"Successfully loaded `{file}`", ephemeral=True)
@discord.slash_command()
async def unload(self, ctx, file=''):
check = await app.dev_check(ctx=ctx)
if check:
if file == '':
await ctx.respond(msgs.ERR_UNLOAD_FILE, ephemeral=True)
else:
self.bot.unload_extension(f'cogs.{file}')
self.bot.sync_commands
await ctx.respond(f"Successfully unloaded `{file}`", ephemeral=True)
def setup(bot):
bot.add_cog(DevCmds(bot))```
Where do i go from here
call the function?
I see
your IDE should've given you a warning about that too
because that line does nothing like it is
its async
await it
Bots: Attributes activity, allowed_mentions, application_flags, application_id, auto_sync_commands, cached_messages, cogs, debug_guilds, default_command_contexts, default_command_integration_types,...
np
basically an active subscription for all i know
with an attribus "application_id" ?
yea
because its documented the exact same way in the discord api docs
oh
alr thx man
where?
in discord.Client
a user's profile theme color
and is accent_color and accent_colour are same ?
Yes, it says that in the description
nice tysm
property timed_out is it boolean ?
yes
why is it not write ?
i dont do the docs
cause the dev didn't have the time imo
no, its a bug
probably
it’s a bug
alr, good thing
is there a way to use one modal after anotehr
like what is mean is after i sumbit a modal
can i start filling up anotehr one
like the second modal will open right after clicking the sumbit button
no
sad what is the best way to approach this
cause i am trying to create a form which has over 5 questions
buttons
you can just reuse the same button but send a different modal
ooo another good idea thanks sir
how to use new thing call emoji (the one in dev portal)
I read the doc and I do it with f-string but don't work
You can use them just using the markdown that you can copy via the dev portal
pycord itself doesnt have anything for them yet, but they work if you just paste the markdown
alr let's searcj
that ? :
{
"id": "41771983429993937",
"name": "LUL",
"animated": true
}
there were already bots for that kind of stuff ages ago lol
for emojis ?
nqn?
yes
nqn ?
app
appli
fr
inspect element >
..no?
?
wth he mean
hes confused
@bridge.bridge_command(name="timeout", description="Timeout a Member", guild_ids=guild_id)
@discord.default_permissions(administrator=True)
async def timeout(self,
ctx,
member:discord.Member,
duration: BridgeOption(str, "Duration", required=True),
reason: BridgeOption(str, "Reason", required=False),
):
The Reason is working for the Slashcommand version, but when used through the old way, it only picks up the first word, can I fix it?
make it *reason
if that doesnt work, put the reason into quotation marks when you use the command
thats working, thanks alot
can very frequent garbage collection possibly cause this issue?
my threshold is (200, 3, 3)
made it that low cuz of my ec2 free tier limitations
idk if it should do that cuz ik the self.bot's user is always cached
Same thought. Garbage collector shouldn’t throw away objects which have a strong reference somewhere
if that actually happens, might that be a library bug?
this sometimes happens when my bot tries to resume its connection
is there any difference with discord.Member and discord.User
discord.Member is linked to a guild, and not discord.User
for example you have discord.Member.roles but not discord.User.roles
let's keep english, I don't really know that website, I don't think it has anything to do with that
we can use discord.utils.get(discord.User, id=myid) ?
that makes no sense
you need to have an iterable in the first parameter
so for example a list of users
and it would give you the one user with the id you specified
bruh so discord.User is bad
Why would it be?
bcs we can't manage role and the discord.User is limit, so for me discord.Member is better fr
I have a Discord.Message object from on_message which is the response of some bot to a slash command. How do I get the user who called the command from this object? I tried to use Discord.Message.reference but in this case it is None since there is no explicit message being replied to.
Target not found, try again and make sure to check your spelling.
Models are classes that are received from Discord and are not meant to be created by the user of the library. Attributes key, url. Methods def is_animated, async read, def replace, async save, def ...
I use it wrong?
user = ctx.guild.get_member(ctx.interaction_metadata.user.>
python3[31315]: AttributeError: 'NoneType' object has no attribute 'user'
ctx - discord.Message
.get_x
Any function that starts with get_ in Py-cord is retrieving the related object from your bots cache. If the object is not in the bots cache the get_ method will return None. Because of this behavior you should check if the get_x method is None and if it is use the fetch_x method.
Why Is Using fetch_ Without Using get_ First Bad?
The fetch_ method makes a call to the discord API. This API call is unneeded if you already have the information. It will also make your command take longer because it will have to send and than wait for a response from the discord API. It will also contribute to the discord APIs global rate limit of 50 requests per second.
What Is Cache?
The cache is a temporary storage inside your bot. It holds many objects from members to messages. When you restart your bot the cache will be empty. When the cache is full it will delete older objects to make space for the new objects.
But that's not what's wrong
?
I understand that the problem is that the interaction_metadata is missing from the message object in this case, no?
other question, what do you want to do?
I want to timeout anyone who calls bots not from the server (like esmBot), I already have code written that just deletes other people's bot messages.
just disable the use external apps permission
you don't need a bot to do that
That sounds more correct, passed it on to the admin, I'm a proger after all, I was told, I started doing it.
thx
as for your actual answer; interaction_metadata is none if the message wasn't created from an interaction
What's the way to use get_or_fetch for messages? I tried
await discord.utils.get_or_fetch(channel, 'message', message_id)
but since there's no get_message on the channel, it fails.
there is a better way to do it
1 sec.
.partial-objects
Partial Objects
These can be used to make API calls when you have channel id and/or message id, and you don't want to rely on the cache to have their objects.
Methods which can be used on them are
Example Usage:
async def star_message(channel_id: int, message_id: int):
# Get Partial Messageable object
partial_channel = bot.get_partial_messageable(channel_id)
# Get Partial Message
partial_message = partial_channel.get_partial_message(message_id)
# Add a reaction
await partial_message.add_reaction(":star:")
"Partial" is essentially constructing an empty class with a reference to the id? I just want to set a reply, so I guess that should work.
yea, think so
since the library very often uses <object>.id, it's often enough to create a barebones object with just an ID
Hm.
.get_partial_message() is throwing an Exception
TypeError("Expected TextChannel, VoiceChannel, StageChannel, DMChannel or Thread not <class 'discord.channel.PartialMessageable'>")
Which is true. PartialMessage's __init__ checks the incoming channel type.
Raised GH Issue.
is it possible that using api v9 instead of v10 causes the issue
very much unlikely
werent you the guy who disabled like, all cache?
and gets the weirdest-af errors because of it?
if so, thats probably why
i re-enabled it
cuz i realized i needed member cache for member-related events
and i didn't really touch any other cache
@Lumabot.group("role")
@Lumabot.command()
@Lumabot.has_perm("manage_roles")
async def add(
self,
ctx: LumabotContext,
member: discord.Member,
role: discord.Role | str,
reason: str = None,
):
if not ctx.is_app:
role_name = role
if isinstance(role, str):
role = ...
Is there a way to do something like so ?
including handle the error of discord.Role not found and then trigger the function with the role as str and not discord.Role
i dont see why .Role would ever fail
if he pass some str and not a role
(with prefix)
yea, there's no reason to ever do that
my goal is if the user use the slash it works fine
reason #5957198 why prefix commands should be banned
else with prefix it get the role using the name to get a list and fuzzy wuzzy this
you can just do that whie keeping discord.Role only i'm pretty sure
to do +addrole @sage tendon helpeur for example even with the name is not excatly helpeur
it will raise an error of bad agrument no ?
i know what you want
is there a way to trigger a function by changing an arg even with the wrong typehint
now that idk what that means
i will try to do something like so :
@add.error
async def error(self, ctx: LumabotContext, error: commands.CommandError):
if isinstance(error, commands.RoleNotFound):
if not ctx.is_app:
role_name = ctx.kwargs.get("role", None)
if isinstance(role_name, str):
roles = await get_role(role_name=role_name)
role = roles[0] if roles else None
if role:
await self.add(
ctx,
member=ctx.kwargs["member"],
role=role,
reason=ctx.kwargs.get("reason", None),
)
well, i guess
didnt you literally say it does
honestly your bot is so hard to debug because you have so much custom shit going on
like @add.error is just not a thing
it is...
it raise an error but not for the decorator, only in my dispatch thing
but i might have an idea
no.
its yet another of your custom things
that make it impossible for an outsider to help with your bot
All about handling errors.
i let u read that
yes it is
How can I safely test out an oauth application?
I dont wanna get rate limited by discord which makes them force me to verify my account, because they suspect me of potentional spam.
(once verified I cannot unverify myself or my account would be useless)
not on the docs, not on the guide
...
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...
LIGHT THEME AAAAAAAAAA (sry x3)
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...
its add becasue my command is name add...
its about the command name like @loop.error etc etc
what are you trying to do luma?
bruh since when do fucking per-command error handlers exist
that is so stupid
/ addrole @fresh sierra roleobject
+addrole @fresh sierra str
so here i will handle the error of a bad arg
is this a slash command or
to then check if its an str
its kinda bridge
clearly not, since there's also a prefix version
🤓
the role converter should accept role names
and if it is i will run the command after a func to get the role by a name
they want to fuzzy match too
that the thing, i dont want it to put the perfect name
but i think i know why my error is not trigger
so you want to reinvoke the command
yes but ig the code is good
@add.error
async def on_hybrid_command_error(
self, ctx: LumabotContext, error: discord.DiscordException
):
if isinstance(error, commands.RoleNotFound):
if not ctx.is_app:
role_name = ctx.kwargs.get("role", None)
if isinstance(role_name, str):
roles = await get_role(role_name=role_name)
role = roles[0] if roles else None
if role:
await self.add(
ctx,
member=ctx.kwargs["member"],
role=role,
reason=ctx.kwargs.get("reason", None),
)
raise error
you could write a custom converter
just my custom bridge does not trigger something
this will work with slash ?
idk about that one
wdym
discord.py calls them hybrid commands
sorry for pointing out errors??
i overwrite the invoke thing, so ig inside it should have something to trigger the decortor of the error
no reason to be rude then
im using a custom dispatch
async def invoke(self, ctx: LumabotPrefixContext):
if ctx.command is not None:
self.dispatch("hybrid_command", ctx)
try:
if await self.can_run(ctx, call_once=True):
await ctx.command.invoke(ctx)
else:
raise discord.errors.CheckFailure(
"The global check once functions failed."
)
except commands.errors.CommandError as exc:
if DEBUG_MODE:
await ctx.command.dispatch_error(ctx, exc)
self.dispatch("hybrid_command_error", ctx, exc)
else:
self.dispatch("hybrid_command_completion", ctx)
elif ctx.invoked_with:
exc = commands.errors.CommandNotFound(
f'Command "{ctx.invoked_with}" is not found'
)
self.dispatch("hybrid_command_error", ctx, exc)
if i said that to you you'd prolly be pissed and mute me
but whatever, have fun debugging luma's custom mess of a bot
what are you using that for
im using a custom bridge because rn bridge cant fit my requierment
and i have seen that with the event rn it trigger sometime the bridge event and sometime not
so i made my own that is trigger everytime
so your command error handler isn't getting called properly?
the decorator is not triggered at all
one sec
what is this overriding
what class is it in
commands.Bot
so dispatch_error is the method that calls the command error handlers
and it looks like you've stopped it from calling unless you have your debug mode enabled
let me try with debug enable, i was thinking about that
nope it still not triggering
but its raising the error inside the terminal
in addition as my dispatch
can you just take out the debug mode check entirely
now you just need to handle it properly
is there a way to handle that for it does trigger the decorator but not print inside the terminal ?
take out the raise at the end
no like i mean it still print everything for the other command even if i dispatch to my custom event
wdym
just override the default command error handler
so i mean if it dispatch to the hybrid_command_error so it does not
on_command_error
inside the discord.Bot ?
just adding a listener for it works
i will try because in my memory it was not
like it was working for some and not for other
(prefix or slash)
might be because of my custom invoke
yeah just add an on_command_error listener and have it just ignore errors
it is working
app commands do the same thing unless you have their error handler as well
you need help with anything else?
no thanks, i will finish to debug the rest, just a None in kwargs but should be okay
thanks you about that it really help and made me learned new things
maybe a last thing:
@add.error
async def on_hybrid_command_error(
self, ctx: LumabotContext, error: discord.DiscordException
):
logger.log(ctx.message.content)
logger.log(ctx.kwargs)
return
2024-08-14 18:25:21 [LOG] : +role add @fresh sierra member
2024-08-14 18:25:21 [LOG] : {}
but
i forgot i did *, for the debug eval...
Dumb thing, thanks for pointing it
this does not contain the role attr, is that because it was the wrong typehint and so it raise an error ?
@add.error
async def on_hybrid_command_error(
self, ctx: LumabotContext, error: discord.DiscordException
):
for arg in ctx.args:
logger.log(arg)
2024-08-14 18:42:18 [LOG] : <Slashs.Role.add.RoleAdd object at 0x7fe0bf62d950>
2024-08-14 18:42:18 [LOG] : <Utils.client.LumabotPrefixContext object at 0x7fe0bfc9c090>
2024-08-14 18:42:18 [LOG] : ghostfrost___ (!! 𝓰𝓱𝓸𝓼𝓽𝓯𝓻𝓸𝓼t)
probably a good assumption
it would've stopped parsing arts there so
args*
okay i will handle that diferetnly
the RoleNotFound class should have an attr with the thing it got for the argument
you can use that
error.argument
thanks
still an issue:
return await self.add.invoke(
ctx,
member=ctx.args[2],
role=role,
reason=ctx.kwargs.get("reason", None),
)
raise error
File "/home/container/.local/lib/python3.11/site-packages/discord/ext/commands/core.py", line 610, in transform
raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: ctx is a required argument that is missing.
do i have to handle it differently ?
why not just call add directly
self.add() give me add is not callable
also tried to edit the ctx.arg but then give me member is missing
wtf did you do to your command because normally it is lol
How is it not callable lol
at its base its just a function
how about ctx.invoke instead?
This is bridge I didn’t edit this part
hm if it's bridge... try calling add.slash_variant
or ext_variant idk what you're doing
i tried and here the thing :
return await self.add.ext_variant(
ctx,
member=ctx.args[2],
role=role,
reason=ctx.kwargs.get("reason", None),
)
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: RoleAdd.add() missing 1 required positional argument: 'ctx'
eh
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: Command.invoke() got an unexpected keyword argument 'member'
mhhh
last time it was saying role add has not attribute.is_app
so it mean now i might be able to just edit the ctx
weird error xd
(sry for ping and i'm not a good dev so I can't help u)
dw
dw ? wth does it mean ?
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: Command.invoke() takes 2 positional arguments but 3 were given
dont worry
posting that but still debugging
ahhh it mean don't worry 😂
u forgot 1 arg but where idk
no, its one too much
1 not optional arg imo
weird fr
if i remove the self ctx is not passed and else it raise that error
slash_variant works fine, for ext_variant just pass ctx twice
ctx.args.append(role)
ctx.kwargs["reason"] = ctx.message.content.split(role_name)[1]
for arg in ctx.args:
logger.log(arg)
logger.log(ctx.kwargs)
if role:
return await self.add.ext_variant.invoke(self, ctx)
u didn't use cogs ?
so
return await self.add.ext_variant.invoke(self, ctx, ctx) ?
nah just do ext_variant(ctx, ctx)
why is that
i do
idk the library handles invokes normally, i can't be bothered to look into it properly when circumventing the normal usage
return await self.add.ext_variant.invoke(ctx, ctx)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Command.invoke() takes 2 positional arguments but 3 were given
not invoke
finally
je savais pas ton bot était en py en plus
ngl thanks u so much nelo without u i will have to pass 1000 years on that
fix it by diong:
return await self.add.ext_variant(
ctx,
ctx,
member=ctx.args[2],
role=role,
reason=ctx.message.content.split(role_name)[1],
)
sry for speaking french I hope so I didn't got any sanctions or idk
well i will later find a fix for that decorator does not also trigger my custom dispatch cos i gotta go
thanks again nelo and plun for that
im fairly sure there's a better way of doing it but yeah that works lol, the first arg is always ignored
which is odd because calling prefix commands normally works fine
slash_variant also works fine, i guess ext_variant is wrapped differently
Hey there, i have a button that opens a modal but sometimes the modal throws an error but i don't know the cause of it:
Button and modal: https://paste.pythondiscord.com/VOJA
Error: https://paste.pythondiscord.com/KKNQ
my god
whoops
well, this discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction error most usually happens if you take longer than 3s to respond
you can fix it by deferring the interaction
alright i'll try, thanks for this too
and the response: await interaction.response.send_message() ?
it might be followup.send_message, not sure rn
.respond worked
none of these two worked:
await interaction.followup.send_message()
await interaction.response.send_message()
You can just do interaction.respond now they added a shortcut
It is followup.send btw
ah dang i thought about that but wasnt sure
but ig it makes sense, you cant followup a modal
if the bot cant send a message what exception is that?
discord.Forbidden
methods that can throw exceptions will list these on the docs with a description
how do i get the user who got kicked through a discord.AuditLogEntry whose action is AuditLogAction.kick? the target attribute seems to be None, and my member caching is turned on
activities = member.activities
if acitivties == discord.Spotify:
albulm = activities.album
is it right ?
No
check the docs on Member.activities please
Models are classes that are received from Discord and are not meant to be created by the user of the library. Attributes key, url. Methods def is_animated, async read, def replace, async save, def ...
the return type is a tuple
IK
so iterate over the tuple
You kinda don't know if you're quite literally comparing a tuple with discord.Spotify
i'm so confused
ty

A tuple is a basic concept...
Tuple items are indexed, the first item has index [0], the second item has index [1] etc.
i'm stupid I forgot it
Yes? But you have to iterate over the tuple to find the spotify activity
if you're fancy you can even use any()
So, how can I remove add app button
Thanks
sometimes my discord bot just randomly disconnects and wont turn on again in discord until i restart
is there some fix for this? so it auto reconnects or stop it from happening
do you have blocking code?
not really
like requests
all api calls are async
or sqlite3
Do you get any error in the console?
database is also async using asyncpg
pillow
actually it might be windows fucking i see theres a thing selected in the cmd
it stops all execution hten
that might be it
no errors in the console
yeah def was that
my bad
is this a bug with pycord 2.6
How can I get the number of users who have installed my bot using Pycord?
I only know that I can use len(bot.guilds) to get the number of guilds where my bot has joined.
len(bot.users) i think
but that is the total number of users that in all guilds
do you mean user installs specifically?
yes
That was [just](#discord-api-updates message) added to the API and will likely be in pycord in 2.7
oh! I see.
Thanks for the response!
until then you can check the discord dev page
umm actually it was added a few days before that
and the pr should be merged soon, just waiting for the green light from one of the core devs
imagine not learning lol
lol
or reading
lol
typed it like this but its a slash command, ig thats why xd
?
uhm
yeah
weird
double checked and its good
channel = (await ctx.channel()).name
TypeError: 'TextChannel' object is not callable
why is it typed as a method though
please use the docs lol
what
intellisense can be misleading
because here channel is typed as a method
it doesn't make any sense to try to call a channel object
probably a private class method or whatever
again, use the docs, intellisense can be misleading
i know how to make it work, just thought you guys had an idea on why it was typed weiirdly
but yeah
go to the definition and check what it does
any doc where it can guides me about slash cmd options or sub group command?
Learn all about Slash Commands and how to implement them into your Discord Bot with Pycord!
@oblique sable pylance has an issue
Install a previous version
And it will fix the typehint
This is correct.
I got the same issue
Luma, the suggestion is correct.
Like one of a month ago or something like so
And u will get back all of the autocomplete etc
Luma
i think older versions of pylance could type property methods as a variable and not as a method, because i remember before it wasnt like that
Same for ctx.author.name etc
It’s since the new release
Got the same thing and tbf it’s pretty annoying cos all of the autocomplete goes crazy
how to transform ctx.author.avatar.url into a byte (for await ctx.guild.create_webhook method)
I suggest u to first use ctx.author.display_avatar
Cos some author has no avatar etc
alr tysm
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 ...
let's try it
And then for the display_avatar u have an arg.read() normally that converge to byte
mb I forgot read function if is it an function
It is a corotine
in the doc it say "Returns the member’s display avatar." but is a discord.Avatar exist or no ?
Yes
But for exemple member.avatar will return none if the doesn’t have any
Display_avatar will return his default avatar
niceee, alr tysmmm
not default
the currently displayed one in the current channel / guild
and so it mean is it a bug from the doc ?
bcs it didn't say it return asset
Member.avatar returns Asset
and display_avatar does too
its not really a bug that it doesnt directly say the return type, ig its just missing
prob so i'm gonna say it again but tysm 😂
where can i find list of events i can use? 
at the docs under api reference>Event reference
that looks to be it doesnt it
(click "the regular events" near the top)
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...
congratulations
great, thanks
oh i didnt realise it was the wrong one mb
finally
i couldnt find an event if you kick the bot out of voice channel
https://docs.pycord.dev/en/stable/api/events.html#discord.on_voice_state_update i guess this could be used
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...
what should i write next to event
@cli.listen("on_voice_state_update",False)
async def left(event:Member):
print(event)
wdym next to the evn
what
async def left(event:here is next to event):
.rtfm on_voice_state_update
Does anyone happen to know what the channels, like https://discord.com/channels/881207955029110855/881309651260571648 are called? (in code)
async def autopublisher(self, ctx: discord.ApplicationContext,
action: discord.Option(str, ":rocket: • Wähle 'on' zum Aktivieren oder 'off' zum Deaktivieren",
choices=["on", "off"]),
channel: discord.Option(discord.TextChannel, ":rocket: • Wähle einen Kanal", required=False)):```
in the option, do channel_types=[discord.ChannelType.news]
wait its not completely correct 1s
ok
Can you change it here?
async def autopublisher(self, ctx: discord.ApplicationContext,
action: discord.Option(str, ":rocket: • Wähle 'on' zum Aktivieren oder 'off' zum Deaktivieren",
choices=["on", "off"]),
channel: discord.Option(discord.TextChannel, ":rocket: • Wähle einen Kanal", required=False)):```
just put what i sent it in the channel option instead of discord.TextChannel
ok
actually after, since its a kwarg
after the description
but you can still remove the discord.TextChannel
async def autopublisher(self, ctx: discord.ApplicationContext,
action: discord.Option(str, ":rocket: • Wähle 'on' zum Aktivieren oder 'off' zum Deaktivieren",
choices=["on", "off"]),
channel: discord.Option(":rocket: • Wähle einen Kanal", channel_types=[discord.ChannelType.news], required=False)):
here
Thanks
But I would like all channels to be suggested as news channels (I have 2 on the server)
what
this will show all channels marked as announcement channels
Yes, but somehow that's not the case for me
show the channel you're trying to use it on in the channel list
wait
yes
restart your client and try again
ok
(your own discord)
ik
I restarted but it still doesn't work
can you show your code as is rn
hm
try re-add discord.TextChannel to the option
ok
the news channels are not displayed
you still have channel_types right
no
yea duh... i never told you to remove that
okay sorry
async def autopublisher(self, ctx: discord.ApplicationContext,
action: discord.Option(str,
":rocket: • Wähle 'on' zum Aktivieren oder 'off' zum Deaktivieren",
choices=["on", "off"]),
channel: discord.Option(discord.TextChannel(channel_types=[discord.ChannelType.news]), required=False)):```
no
like this?
async def autopublisher(self, ctx: discord.ApplicationContext,
action: discord.Option(str, ":rocket: • Wähle 'on' zum Aktivieren oder 'off' zum Deaktivieren",
choices=["on", "off"]),
channel: discord.Option(discord.TextChannel, ":rocket: • Wähle einen Kanal", channel_types=[discord.ChannelType.news], required=False)):
I try it
yeah, it works
Thanks
hello, i'm having the issue of
it responds to commands fine
however,
[2024-08-16 01:19:27] [WARNING ] discord.gateway: Can't keep up, shard ID None websocket is 149.0s behind.
[2024-08-16 01:19:29] [WARNING ] discord.gateway: Shard ID None heartbeat blocked for more than 110 seconds.
do you have any long operations going on in your bot
or something new you added since it, well, didn't do that
not any that i'm aware of
oh wait you said it responds to commands fine, hm
might just be a minor discord issue then
I'd say wait a little and see if it still happens
usually its because of a blocking fonction
can be pillow, sqlite3, a def function etc etc
heartbeat blocked is usually your code's fault yeah
but wouldn't that also block commands?
if you do +ping -> code blocking -> result of +ping
it can explain both ig (big ping + warning)
ik i got that issue a lot cos rn my bot has a sync db but command still work, sometime just have a big delay
i'll just say, i don't have to do anything with my bot to get that
i can just run the bot and it does it
you code might run a blocking thing
also, any command that i use gives a response pretty much immediately
.tag paste
if you want put all ur thing here
it will be easier for us to find the issue
(make sure to remove token)
okay
(also it's apparently both 1280 and 260 seconds behind right now)
...actually that's just the heartbeat
cos something might block it
all of it or just a specific part/file
all since we dont know which part can cos that
just before
send pip list
it might give us a quick answer
Package Version
------------------ --------
aiohappyeyeballs 2.3.4
aiohttp 3.10.3
aiosignal 1.3.1
attrs 23.2.0
certifi 2024.7.4
charset-normalizer 3.3.2
frozenlist 1.4.1
idna 3.7
multidict 6.0.5
pillow 10.4.0
pip 24.2
py-cord 2.6.0
python-dotenv 1.0.1
requests 2.32.3
ruff 0.5.5
urllib3 2.2.2
yarl 1.9.4
pillow 10.4.0
requests 2.32.3
both of them are blocking
are you using them inside ur code ?
i'm not using requests at all

