#Basic Pycord Help
1 messages Β· Page 54 of 1
pass the bot variable to the RoleButton, then pass it on to the modal
currently your bot variable just points to the class
but when i dont user from bot Import Bot how can i use it herte? (this is outside a cog)
def __init__(self):
super().__init__(
label="Verifiziere dich hier!", # Text auf dem Button!
style=discord.enums.ButtonStyle.blurple, # Button-Fabre!
custom_id="interaction:RoleButton",
emoji=":greentickincircle_xenority:"
)
async def callback(self, interaction: discord.Interaction):
verify = random.randint(1, 2)
user = interaction.user
role = interaction.guild.get_role(SERVER_SYSTEM["verify_role_id"])
if role is None:
return
if role not in user.roles:
modal = verify1(Bot, title="Xenority")
if verify == "1":
modal = verify1(Bot, title="Xenority")
if verify == "2":
modal = verify2(Bot, title="Xenority")
await interaction.response.send_modal(modal)
else:
await interaction.response.send_message(f":x: Du bist bereits verifiziert!", ephemeral=True)
interactiomn.client?
You mean here?
async def on_ready(self):
view = discord.ui.View(timeout=None)
view.add_item(RoleButton(<here>))```
self.not
bot
Timeout None at the view class
async def on_ready(self):
view = discord.ui.View(timeout=None)
view.add_item(RoleButton(self.bot))```
so right
try it and see
ok thx β€οΈ
It's an existing message so I don't have to resend it
uh...
do you even call self.bot.add_view
Yeah on the sartup
and yea, idk how it works if you just take the bare View class to do that with
I'd always make a subclass
Is it working?
yeah
that probably makes all views of your bot permanent now lol
XD yeah
I subclass all the button and view classes
me only the views, i dont see a point subclassing the buttons
its a old code from me i do all in a class like button a class button a ::::
is there a way to put the funciton for each of my commands in different files to stay a bit more organized? the cogs are nice but I want to take it a step further if possible
i mean, make more cogs then lol
or do you mean moving the actual code of each command somewhere else? because that is pointless for most commands
this is what I mean
for most commands
just a few of my commands have a bit attached to them
Well, what's your idea of "a step further" with cogs
Hey there, i started to working on a feature in my bot and i thought about using the tasks extension although i have some questions. The feature should allow a user to start a monitor that sends a request every X seconds to an api endpoint till X parameter is true. With tasks how would i go about starting a task that is linked to a user?
If you have code that multiple commands need, you should put that into helper functions
But if its just one command with a big blob of unique code, i leave it like that
Do you mean that u want to have each subcommand in different cog ?
they want the command code in another place than the cogs
I didn't use the tasks extensions when doing something similar, but, I just made a function with a while loop and used asyncio.create_task
It surprisingly worked.
But I'm sure there's a better practice for it lol
if they're strictly short term tasks, while is probablyyyy easier?
the problem with using task loops when it comes to user customization is that it becomes a hassle at that point
Is not short, it could go for hours
eh then you probably do want tasks...
i guess you can fully create and start a task inside your command
Yeah, but i don't know how would i go about stopping a specific monitor instead of another, if i was able to let's say create a task and assign it a name it would be amazing
then the end of the task callback can just destroy itself if it's the correct result
just do it in a cog and have a dict
Like?
so let's say you're creating a task
alr
then you can do self.tasks["some_name"] = task
where task is the loop you've created
mhm
well that's basically it
now you have a reference to your task, you can do what you want with it
i would need to have multiple of these depending on how many tasks i want and assign it to a user right?
you only need a single self.tasks dict
just decide on a unique reference whenever a user creates a task
e.g. if a user can only have one task at once, just make it their user id
oh alr im going to try when im home, it isnt really clear but something should come out
though note that with a method like this, the tasks would be lost whenever the bot shuts off
so perhaps you want to save the necessary data required to re-create each task after a restart
i wouldnt be able to store the name of the task i assigned to a user and recover the task?
yeah this
well if you only store it in variables/dicts, you can't exactly save the function outside (well, you could, but it's not very pretty)
so just save the necessary parameters (link, seconds delay, user id, etc. etc.) and recreate it on startup
it would have been much easier if the task create function had a parameter like name to get it π΅βπ«
well the problem is that tasks aren't stored in pycord itself
asyncio handles their management
ah i see, im going to try your way even tho i didnt understand it fully
i guess i'll write a vague example
if you have time it would be amazing
VERY loose example, assuming this is in a cog context```py
...
self.bot = bot
self.tasks = {}
async def command_to_create_tasks(self, ctx, ...):
@tasks.loop(seconds=...)
def task():
x = await request(...)
... # other logic to determine if result is correct
self.tasks[...] = task
task.start()
include some way to write relevant data to a file or database
await ctx.respond(...)
is it possible to use discord.Spotify like get a song information by his name or we need use spotify api or smthing else
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 ...
alr let's see it
oh actually, perfect
just check in user.activities
list of all activities, spotify does show up
(i think it only works on members)
amazing you've been very helpful
nah imo u don't know wth I mean...
like a thing like this code :
async def get_spotify(ctx, name : str) -> discord.Spotify:
spotify = # get the spotify by his name
await ctx.reply(content=spotify.album)
ok bcs I though I can use the discord.Spotify class like discord.Embed
well users don't use the Spotify class
it's only used to retrieve someone's spotify status on their profile
ye it's with activities ik
ye so we can't
ty for the information also
they have a nice search api at least https://developer.spotify.com/documentation/web-api/reference/search
yooo this doc is amazing
wth meaning "nullable"
bar on the right makes testing very easy, have fun
nullable means either it can be null (None in python)
or it won't appear at all in the response
allgood
uhhh possibly? i'd just recommend testing it a fair bit and being careful when parsing the response
π
i'm beginner in slash command so what is "Autocomplete" ?
it's not this thing with multiple choice where I can choose
choices = const
autocomplete = based on current input
const ?
In simple terms, autocomplete returns options dynamically based on the previously selected option.
If you want options that do not change you must use the choices parameter
choices=["a", "b", "c"]
async def get_items(ctx: discord.AutocompleteContext):
# dynamic get e.g. database query, array filter
...
autocomplete=get_items
why that's fails :
async def auto(ctx : discord.AutocompleteContext):
return ctx.interaction.guild.members
@bot.command()
async def myslash(
ctx,
member: discord.Option(str, autocomplete=auto)
):
await ctx.respond(f"> {member.mention}", ephemeral=True)
yeye my mention don't work bcs I don't fetch the user but whyy it don't show me all members
@bot.command()
async def myslash(
ctx,
member: discord.Option(discord.Member)
):
await ctx.respond(f"> {member.mention}", ephemeral=True)
that's weird
Discord has a built in member option that is different from autocomplete.
That is what yoggies showed
ye but his thing don't work for me
π
idk why
Can you show your code
probably went wrong and fellback to string instead
That should be true by default, unless you made it false.
Also remember to always reload the discord client whenever you make changes to the command or command options
I didn't reload my discord
it's prob this
is there have a way to handle the error that from the autocomplete?
how to give custom view a new pagination, and not sync to the previous pagination anymore?
i mean, adding a new pagination to the custom view
not built in no, but you really shouldn't have any errors there because it must always complete within 3 seconds
Traceback (most recent call last):
File "D:\GitHub\fractal-rhomb\.venv\Lib\site-packages\discord\commands\core.py", line 138, in wrapped
ret = await coro(arg)
^^^^^^^^^^^^^^^
File "D:\GitHub\fractal-rhomb\.venv\Lib\site-packages\discord\commands\core.py", line 1078, in _invoke
await self.callback(self.cog, ctx, **kwargs)
File "D:\GitHub\fractal-rhomb\cogs\fractalthorns.py", line 272, in single_image
await ctx.respond(response_text, file=file)
File "D:\GitHub\fractal-rhomb\.venv\Lib\site-packages\discord\interactions.py", line 618, in respond
return await self.followup.send(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\GitHub\fractal-rhomb\.venv\Lib\site-packages\discord\webhook\async_.py", line 1769, in send
params = handle_message_parameters(
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "D:\GitHub\fractal-rhomb\.venv\Lib\site-packages\discord\webhook\async_.py", line 688, in handle_message_parameters
"value": file.fp,
^^^^^^^
AttributeError: 'NoneType' object has no attribute 'fp'
```...huh?
can file not be set to none or something?
file is used to upload; if you want to edit the current message, you use attachments
i mean
that doesn't address what i said at all
but also i'm not editing a message
just don't set file if it's None
(some methods still use utils.MISSING rather than None)
that's what i changed it to
it's just... why...
If I needed to impose a strict character set limit for the str input of a discord.Option (eg. "can only contain characters A-Z, 0-9"), would this best be done with input_type = <some defined ext.commands.Converter class>? I don't know much about Converters yet, but wanted to make sure I was on the right track before going down this rabbit hole, haha
in slash command @commands.is_owner, is other guys see this command ? or no ?
It only checks if the user is the owner of the bot but the command is still visible to others.
they can see it
because discord does not have it as a permission
I have uploaded emojis to my bot and am trying to retrieve them like this
emoji = self.bot.get_emoji(1277980926566994022)```
But I always get none in return
If I take an ID from my server then I find an emoji but if I take the ID from the developer portal of the Discord Bot from the emoji then I don't find it.
.tag 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.
Yes I am aware of that but there is no fetch_emoji method. How can I get the emojis into the cache then? π
Models are classes that are received from Discord and are not meant to be created by the user of the library. Attributes key, url. Methods def is_animated, async read, def replace, async save, def ...
?
This is from the Guild object.
But I uploaded emojis to the Discord Bot in the Developer Portal so that I can use them on several servers via the bot and don't always have to have them on one of my Guilds and have to search for them.
but for that you dont use the get_
How do I do this correctly so that I can use the bot emojis?
I dont know if its even got added to py-cord
Okay, so I can only implement the whole thing via the search on my Guild?
bruh
ty
How can i fix this
if not message.content and not getattr(message, 'interaction_metadata', None) and not getattr(message, 'interaction', None):
/home/container/.local/lib/python3.10/site-packages/chat_exporter/construct/message.py:184: DeprecationWarning: interaction is deprecated since version 2.6, consider using interaction_metadata instead. See https://discord.com/developers/docs/change-log#userinstallable-apps-preview for more information.
if not message.content and not getattr(message, 'interaction_metadata', None) and not getattr(message, 'interaction', None):```
You dont
Thats something the chat exporter lib's maintainers have to fix
well not even an error, just a deprecation warning
how to "add_command" (slash command) in a cog ?
you dont need that
you load the cog with the commands in it
Lately I have been seeing a lot of these warnings
28/08/2024 15:40:50 - WARNING - We are being rate limited. Retrying in 0.56 seconds. Handled under the bucket "1028291225255678022:None:/channels/{channel_id}/messages/{message_id}"
Does anyone know what causes it?
are you fetching messages a lot?
No but recently I removed the limit of purge() could that be the issue?
Okay good to know, I'll look into a method to reduce that
new_cls.__cog_commands__ = tuple(c._update_copy(cmd_attrs) if not hasattr(c, "add_to") else c for c in new_cls.__cog_commands__) # type: ignore```
so what to do with this
[ - ] Failed To Load COGs : Extension 'COGS.Stocks' raised an error: TypeError: 'BridgeOption' object is not callable
show your code
And maybe also your pip list
@stock.command(
name="quote",
description="Get The Current Price Of A Stock",
)
@BridgeOption(
"symbol",
description="The Stock Symbol",
choices=["AMD", "APPLE", "INTEL", "GOOGLE", "MICROSOFT"],
)
async def quote(self, ctx, symbol):
await ctx.defer(ephemeral=True)
valid_symbols = ["AMD", "APPLE", "INTEL", "GOOGLE", "MICROSOFT"]
if symbol not in valid_symbols:
embed = discord.Embed(
title="Invalid Symbol",
description="Please Enter A Valid Symbol",
color=0xFF0000,
)
embed.add_field(
name="Valid Symbols",
value="AMD, APPLE, INTEL, GOOGLE, MICROSOFT",
inline=True,
)
await ctx.respond(embed=embed, ephemeral=True)
return
symbols = {
"AMD": "AMD",
"APPLE": "AAPL",
"INTEL": "INTC",
"GOOGLE": "GOOGL",
"MICROSOFT": "MSFT",
}
try:
main_symbol = symbols[symbol]
except Exception as e:
main_symbol = symbol.upper()
try:
quote = self.finnhub_client.quote(symbol=main_symbol)
if quote:
embed = discord.Embed(
title=f"{symbol} Stock Quote",
description=f"### Current Price: ${quote['c']}",
color=0xD5E4CF,
)
await ctx.respond(embed=embed, ephemeral=True)
except Exception as e:
pass
please add py after the first set of back ticks lol
ah yea, it's probably @bridge_option
i generally do that, i forgot this time
kk
actually I'm looking at the docs rn and there doesn't seem to be a bridge option decorator (?)
yea, that's what i also saw .... still getting the error
/root/Fallen-SMP-BOT/COGS/Stocks.py:340: DeprecationWarning: Using Option for bridge commands is deprecated since version 2.5 and will be removed in version 2.7, consider using BridgeOption instead. See https://github.com/Pycord-Development/pycord/pull/2417 for more information.
async def buy(self, ctx, symbol: str, quantity: int):
/usr/local/lib/python3.10/dist-packages/discord/cog.py:234: DeprecationWarning: Using Option for bridge commands is deprecated since version 2.5 and will be removed in version 2.7, consider using BridgeOption instead. See https://github.com/Pycord-Development/pycord/pull/2417 for more information.
new_cls.__cog_commands__ = tuple(c._update_copy(cmd_attrs) if not hasattr(c, "add_to") else c for c in new_cls.__cog_commands__) # type: ignore
/usr/local/lib/python3.10/dist-packages/discord/cog.py:234: DeprecationWarning: Using Option for bridge commands is deprecated since version 2.5 and will be removed in version 2.7, consider using BridgeOption instead. See https://github.com/Pycord-Development/pycord/pull/2417 for more information.
new_cls.__cog_commands__ = tuple(c._update_copy(cmd_attrs) if not hasattr(c, "add_to") else c for c in new_cls.__cog_commands__) # type: ignore
then you'll probably have to use the typehint method
there it is π
is what
nth
what were you saying about typehint method
how do i use it ?
async def command(self, ctx, thingy: BridgeOption(stuff here))
nvm it worked
name: BrideOption()
using bridge_option
that would be for the @one
yea i missed one option
yes yes
that was giving the error
I thought everything was updated automatically by just reading the docs in the code
apparently not
especially the bridge commands, theier docs need to be updated
because they're special and weird
why can't you go slash only
I also only use slash commands
yea I refuse to do prefix too, and no one ever uses prefix anymore imo
since mobile users have trouble accessing slash cmds
what
i love using slash cmds but now i just can't
uh what
yes apperenly some users have ...
hmm ic
like i see people just typing /whitelsit
instead of triggering the whitelist cmd
that's a user issue
that's a skill issue
they're just doing it wrong, that's it
XD
i can also type /whitelsit on pc
on mobile you need to click the commands for them to actually register
if not you're just sending a message
on PC it will automatically select a command if you type the correct name
it's incredible how people are apparently still incapable of using slash commands
they're so old by now
true
Its incredible that people still not reading the docs
lol
hasn't it literally been 3 years?
if not more
can i trust this to work? I'm not sure at what stage in starting the bot cogs are loaded
just wanna make sure i can trust on this .get_guild
Its fire before on_ready
So get_guild might return None
cogs are loaded when you decide to load them
tasks have a handy dandy before_loop method that you can use to wait before starting
and bot has a wait_until_ready
I wonder if its working with client.login
I'm using the on_application_command_error event to handle my slash command errors. But when I raise them in my code they are still handled by the event, but I also see the error in console. Why is this?
Console error:
[ERROR] Error while executing /stats
Traceback (most recent call last):
File "E:\Anwender\Documents\GrinMaxTracking Bot\.venv\Lib\site-packages\discord\commands\core.py", line 138, in wrapped
ret = await coro(arg)
^^^^^^^^^^^^^^^
File "E:\Anwender\Documents\GrinMaxTracking Bot\.venv\Lib\site-packages\discord\commands\core.py", line 1078, in _invoke
await self.callback(self.cog, ctx, **kwargs)
File "E:\Anwender\Documents\GrinMaxTracking Bot\cogs\stats.py", line 30, in _display_stats
deals = await self.db.get_deals_in_date_range(date_range)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "E:\Anwender\Documents\GrinMaxTracking Bot\data\database.py", line 77, in get_deals_in_date_range
raise DatabaseEmptyError(date_range)
utils.exceptions.DatabaseEmptyError: No deals found in the database for the period: Today
I raise it this way:
if not documents:
raise DatabaseEmptyError(date_range)
here I call the error_reporter in bot.py :
async def on_application_command_error(
self, context: ApplicationContext, exception: DiscordException
) -> None:
await ErrorReporter(self).report_error(context, exception)
Error reporter:
error = getattr(error, "original", error)
if isinstance(error, DatabaseEmptyError):
await ctx.respond(embed=ErrorEmbed(error.message), ephemeral=True)```
Maybe because the error is not trigger inside ur command
Well it is
Can you share the code of the command ?
Yes:
@slash_command(name="stats", description="Display deal statistics and charts in the selected timeframes")
@option(
name="period",
choices=["Today", "This Week", "This Month", "Past 3 Months", "Past 6 Months", "This Year", "All Time", "Custom"],
required=False,
default="Today",
default_member_permissions=discord.Permissions(administrator=True)
)
async def _display_stats(self, ctx: discord.ApplicationContext, period: str):
date_range = DateRange(period)
deals = await self.db.get_deals_in_date_range(date_range)
deal_stats = DealStats(ctx, deals, date_range)
await ctx.respond(embed=await DealStatsEmbed.create(ctx, deal_stats, period))
I raise the error in the get_deals_in_date_range method
That why ig
yea
sadly still the same when I raise it directly in the cog:
date_range = DateRange(period)
deals = await self.db.get_deals_in_date_range(date_range)
if not deals:
raise DatabaseEmptyError(date_range)```
Error:
File "E:\Anwender\Documents\GrinMaxTracking Bot\cogs\stats.py", line 39, in _display_stats
raise DatabaseEmptyError(date_range)
utils.exceptions.DatabaseEmptyError: No deals found in the database for the period: Today
Does it trigger the on_command error ?
the event gets triggered and the error is handled correctly but then the error also gets raised in the console
If you just add a
on_command_error(): pass
Does it still occur ?
Donβt think it will resolve it but we never know
still not working maybe it is because I use also the ezcord library
yes it was because of the additional ezcord error handling
You shouldn't use two libraries for the same thing at the same time...
its a plugin for py-cord
simplifies some things like cog loading, database handling and so on
why do I feel like ezcord dosen't make things easier?
cog loading is a single line..
this error is being raised by ezcord https://github.com/tibue99/ezcord/blob/master/ezcord/bot.py#L513 py self.logger.exception( f"Error while executing **/{ctx.command.qualified_name}** {error_msg}", exc_info=error, extra={"webhook_sent": webhook_sent}, )
you can disable ezcord's error handler by passing error_handler=False in the Bot init
Yes, that worked. I also needed to remove the error_webhook_url in the Bot init
my IDE error :
my code
@discord.slash_command()
@commands.has_permissions(manage_messages=True)
async def say(self, ctx : discord.ApplicationContext, channel : discord.Option(discord.TextChannel, required=False), msg : discord.Option(str)):
await ctx.channel.send(msg)
use the @discord.option() decorator instead of the typehint method
alr ty
so after
how to use it
like a variable
Localizations are a way to make your bot more accessible to your users. Learn all about localizations now!
welp, guess no example for you rn :>
need I use it ?
wait why does a direct link to the guide work lol
https://guide.pycord.dev/interactions/application-commands/slash-commands#options--option-types read this after clicking on "using option decorator" above the code field
Learn all about Slash Commands and how to implement them into your Discord Bot with Pycord!
oh I see
that's work !
TY
hello, i am trying to make a slash command administrator only. i have the following code but a test user can see the command. is there a way to hide it from non admins?
@commands.slash_command(guild_ids=[guild_id], name='open', description='Opens game chat.')
@commands.has_permissions(administrator=True)
...
@discord.default_permissions(admininistrator=True)
thank you!
also you can use @discord.slash_command, bit shorter to type
If I needed to impose a strict character set limit for the str input of a discord.Option (eg. "can only contain characters A-Z, 0-9"), would this best be done with input_type = <some defined ext.commands.Converter class>? I don't know much about Converters yet, but wanted to make sure I was on the right track before going down this rabbit hole, haha
I guess there's no way to sanitize this during input, and will just have to do it in the function itself?
yes, this should be done after input
you can also use autocomplete
but just for user hints (it still can accept other things)
so something like:
def parse_input(value: str) -> str:
# let's say I want only 1-9
parsed_value = ""
for char in value:
if char in digits:
parsed_value += char
return parsed_value
def input_autocomplete(ctx: discord.AutocompleteContext) -> list[str]:
value = ctx.options.get("value", "")
return [parse_input(value)]
@discord.slash_command()
async def command(
self,
ctx: discord.ApplicationContext,
value: discord.Option(
str, autocomplete=input_autocomplete
)
) -> None:
value = parse_input(value)
...
strictly speaking building a custom converter and catching the issue in checkfailure would also work
How to shard a bot in pycord?
Tag not found.
.rtfm discord.AutoShardedBot
discord.AutoShardedBot
discord.AutoShardedBot.activity
discord.AutoShardedBot.add_application_command
discord.AutoShardedBot.add_check
discord.AutoShardedBot.add_cog
discord.AutoShardedBot.add_listener
discord.AutoShardedBot.add_view
discord.AutoShardedBot.after_invoke
discord.AutoShardedBot.all_commands
discord.AutoShardedBot.allowed_mentions
discord.AutoShardedBot.application_command
discord.AutoShardedBot.application_commands
discord.AutoShardedBot.application_flags
discord.AutoShardedBot.application_id
discord.AutoShardedBot.application_info
discord.AutoShardedBot.before_identify_hook
discord.AutoShardedBot.before_invoke
discord.AutoShardedBot.cached_messages
discord.AutoShardedBot.can_run
discord.AutoShardedBot.change_presence
Thank you
How do some bots don't have "playing" status but only that?
Using custom status
What if I want to host my bot in multiple servers?
How many servers?
Idk, 3/4
3 oder 4 only?
I mean VPS
Just for asking
I mean at how many server is your bot?
It's not related to this, I just wanna ask if it is possible to host a py-cord bot in multiple VPS
why?
Β―_(γ)_/Β― It's a question out of curiosity.
Just to know if it is possible and how
It is, you probably need something like docker swarm or kubernetes and have one container per shard
still why?
Got it, thank you!
I'm just curious if it is possible, I don't need it ATM
Why should you need it?
If you want ha and if you want to scale horizontally
for cluster maybe
Can I not use autocomplete in BridgeOptions for the SlashCommands?
?
like just dont put autocomplete in ur option if u dont want it
I want autocomplete. I ask if BridgeOptions support it
I do it like this. That should work then too
async def banned_users_autocomplete(
self, ctx: discord.AutocompleteContext
) -> List[discord.User]:
return [
banentry.user for banentry in await ctx.interaction.guild.bans().flatten()
]
@bridge.bridge_command(name="unban", description="Unbans a user")
@isStaff()
async def unban(
self,
ctx: bridge.BridgeContext,
user: bridge.BridgeOption(
discord.User,
"The user you want to unban",
autocomplete=banned_users_autocomplete,
),
):
Which permission can I ask more without having approved "intents"
You can have any permissions without needing intents. You will just receive less information for some things. IE you can have view message permission but you would only receive basic information about the message not the message content unless you have the intent
Like permission to set profile activity needs some extra permission from discord
This isn't possible over regular bots, you would need to set up a program with an oauth flow (beyond the scope of pycord)
Ok but it requires some extra permission from discord nah?
Oauth permissions generally don't require any permission from discord, because the end user has to authorize
There's like when I receive a message the bot answer as "me"?
Or isn't possible
That'd be userbotting, which is a no go
Hmm, with user installable apps what I can do?
Just app commands?
Well, user installable apps let the end user use the allowed commands anywhere rather than just specific guilds
Basically yeah, just app commands tied to the user
Is it possible to see who deletes the message in s server?
audit log could give you the answer
I just realized i never fixed this too
xd now u know how to fix it
Use decorator
- its not an error but a warning from vsc
ik "the toothy" said me that
it quite clearly says whats wrong
you're passing a positional argument to the slash_command decorator, and it takes no positional arguments
and you should add self.bot.wait_until_ready() in your task
and, what
ngl with the comments too it just feels like an outdated / bad bot template or chatgpt
gschmarre
bec you need intents.members in the code
No
yes
No.
Yes.
its unnecessary, hence i said that
test it
too
oh front
and the code
you need name="poll"
you dont even need that
it takes on the function name
i answer his question and he need if he use that in slash_comand the name=
that ist the error
or they can just leave it out entirely
Donβt u do also that with cog ?
Or cog.name is not the name of the class
cogs also use the class name
if you want to pass a different name, you have to use the name kwarg
So technically itβs the same here without ?
Or itβs different with discord.Cog
this is essentially the same, yes; you could completely omit name here
(and that is the correct usage)
Ok, why name is a kwarg and not an arg ?
I donβt really know the diff with arg and kways
Does arg are mandatory and lways not ?
technically all kwargs are args
.
if a python function has listed arguments, you can always refer to them by name
e.g. ```py
def foo(bar):
print(bar)
foo("bar")
foo(bar="bar")
The yes was for that ?
Yeah but I understood Dw
but ALSO in python, you can force options to be written as an arg or kwarg
e.g. ```py
def foo(bar, /):
print(bar)
foo("bar")
foo(bar="bar") # this errors
and the opposite ```py
def foo(*, bar):
print(bar)
foo("bar") # this errors
foo(bar="bar")
in the first i used / to force all args before it to only work as args
in the second, * forces all args after it to only work as kwargs
you see this a lot if you go through pycord's code
call me ignorant but why would you ever make something kw only
like whats the downside to just allowing either
generally if you don't want ANY ambiguity
And arg need to do bar=bar and kwazgs not ?
you are using vim
no
what
you can do either, unless the function uses the methods i described above to prevent it
(in the end, just try it and it'll make more sense)
Yeah gonna try tomorrow
Special Symbols Used for passing arguments in Python:
*args (Non-Keyword Arguments)
**kwargs (Keyword Arguments)
what
I don't use vim
letβs say you are using vim and you want it to be non-ambiguous
ah
import discord
from discord.ext import commands
import sqlite3
class Stats(commands.Cog):
def __init__(self, bot):
self.bot = bot
conn = sqlite3.connect('counter.db')
self.c = conn.cursor()
@commands.slash_command(description="How many link did you fetch")
async def stats(self, ctx: discord.ApplicationContext, member: discord.Member = None):
self.c.execute("SELECT * FROM counts WHERE id=?", (str(member.id),))
row = self.c.fetchone()
if not row:
row = [0,0]
val = self.c.execute("SELECT SUM(count) FROM counts;").fetchone()[0]
await ctx.respond(f"{ctx.author.display_name} has fetch {row[1]} links\nGlobal: {val} links", allowed_mentions = discord.AllowedMentions(everyone=False, users=False))
def setup(bot):
bot.add_cog(Stats(bot))
using the same code, the bot works locally for me, but it doesnt work on the host. any ideas?
yes
does anything appear in console after using the command
I think that's an issue on the client or discord site
else it would say application didn't respond
try to restart discord
I tested it with my local code using the anola token, and it still said this interaction failed
although the bot xDaaa1 works
did you restart discord after starting the bot?
nah
p sure no
think it only prevents you from adding the bot to more servers when you reach 100
do any other commands work?
actually I think I might know the issue lol
can you rename the function of the command, just add a letter or whatever
clueless
I thought the function name might have been the issue cause it has the same name as the cog except the lowercase s
both no: neither command name and change device
I gotta say idk what "this interaction failed" can be caused by
red errors outside of "application didn't respond" suck
I'd say ask discord support but that's hit or miss, with a big portion of miss

how to fix this space?
Which space?
I highlighted it in red square
PyCharm
@app_commands.command(name="test")
async def test(self, ctx):
loadingGifFile = discord.File("./bot_dc/assets/loading.gif", filename="loading.gif")
embed1 = discord.Embed(title="Loading...", description=f"loading")
embed1.set_thumbnail(url="attachment://loading.gif")
embed1Message = await ctx.guild.get_channel(1230207199855513705).send(file=loadingGifFile, embed=embed1)
await asyncio.sleep(5)
embed2 = discord.Embed(title="Success!", description=f"We have finished loading")
await embed1Message.edit(embed=embed2)```
this command produces the above image
and after the asyncio.sleep it edits said message to this
how do i make it remove the loading gif whenever it edits the message
nvm fixed it
await embed1Message.edit(
attachments=[],
)```
And this is discord.py btw
Not pycord
for slash commands, not at all really
for slash command specific stuff at least
the core parts are very very similar to exactly the same because pycord is a discord.py fork
so why use pycord over discord.py?
do they have more features or something
it's way better for slash commands
like it makes way much more sense
member join not working
code:
import discord
from discord.ext import commands
import config
from discord.ui import Modal, InputText, View, button
intents = discord.Intents.all()
bot = discord.Bot()
@bot.event
async def on_member_join(member):
await member.send(
f'Welcome to the server, {member.mention}! Enjoy your stay here.'
)
bot.run(config.TOKEN)
because its slash syntax makes much more sense and is way simpler
oh paillat already said lol
"not working" means?
just not workings, no message, no error
You havent added Intents
if i'm add intents:
File "C:\Users\V\PycharmProjects\ilias_Projects\bots\FCB\main.py", line 11, in <module>
bot = discord.Bot(intents)
File "C:\Users\V\PycharmProjects\ilias_Projects\venv\lib\site-packages\discord\bot.py", line 1154, in init
self.description = inspect.cleandoc(description) if description else ""
File "C:\Users\V\AppData\Local\Programs\Python\Python310\lib\inspect.py", line 750, in cleandoc
lines = doc.expandtabs().split('\n')
AttributeError: 'Intents' object has no attribute 'expandtabs'
intents=intents
what
oh, im so stupid
Traceback (most recent call last):
File "C:\Users\V\PycharmProjects\ilias_Projects\bots\FCB\main.py", line 183, in <module>
bot.run(config.TOKEN)
File "C:\Users\V\PycharmProjects\ilias_Projects\venv\lib\site-packages\discord\client.py", line 766, in run
return future.result()
File "C:\Users\V\PycharmProjects\ilias_Projects\venv\lib\site-packages\discord\client.py", line 745, in runner
await self.start(*args, **kwargs)
File "C:\Users\V\PycharmProjects\ilias_Projects\venv\lib\site-packages\discord\client.py", line 709, in start
await self.connect(reconnect=reconnect)
File "C:\Users\V\PycharmProjects\ilias_Projects\venv\lib\site-packages\discord\client.py", line 646, in connect
raise PrivilegedIntentsRequired(exc.shard_id) from None
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
Exception ignored in: <function _ProactorBasePipeTransport.del at 0x000001C46885CD30>
Traceback (most recent call last):
File "C:\Users\V\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 116, in del
self.close()
File "C:\Users\V\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Users\V\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 745, in call_soon
self._check_closed()
File "C:\Users\V\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 510, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed bruuuuh
idk
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
what me need to do? im so stupid bruh
read the message
how to do it?
go to the dev portal and turn the intents on
what tab?
your bot
nice,i found it, tysm
Learn how to use the commands extension for Pycord.
and please make triple sure to click "using the commands extension"
Thankiess
and it have a paginator
and auto process_command
Is there a way to see content of a message that a message is replying to?
Like if I ran "!test" instead of what I am currently saying, the bot would know the text of the message I am replying to
Yes
I have minimal idea of what I am doing, so can you help me with an example of how to?
What's your current code?
@bot.command()
async def quote(ctx: commands.Context):
if ctx.reference:
print("test")
await ctx.send(":)")
else:
await ctx.send(":(")
And this crashes
tracelog probably had that in there too
reference is an attr of message, not context
traceback*
traceback just said 'no attr named reference'
Does this work to give a role the ability to move members?
await team_one_channel.set_permissions(team_one_role, connect=True, move_members=True)
or is it a different attribute?
try it and see
Try it and find out,. If you get an error, feel free to share it and we can see what's wrong :)
but mind this
await team_one_channel.set_permissions(team_one_role, permissions=discord.Permissions(connect=True, move_members=True))
imo it's that
@quartz relic
I'll try that.
It's weird because the connect perm works, but I'm having trouble with the other one.
Thanks @opal swan
idk check that
discord.Permissions
.rtfm discord.Permissions
discord.Permissions
discord.Permissions.DEFAULT_VALUE
discord.Permissions.VALID_FLAGS
discord.Permissions.add_reactions
discord.Permissions.administrator
discord.Permissions.advanced
discord.Permissions.all
discord.Permissions.all_channel
discord.Permissions.attach_files
discord.Permissions.ban_members
discord.Permissions.change_nickname
discord.Permissions.connect
discord.Permissions.create_instant_invite
discord.Permissions.create_private_threads
discord.Permissions.create_public_threads
discord.Permissions.deafen_members
discord.Permissions.embed_links
discord.Permissions.external_emojis
discord.Permissions.external_stickers
discord.Permissions.general
the first one
is this the correct way to query a junction table for the values?
.tag sqli
SQL Injection is a technique used by attackers to interfere with and alter queries that an application makes to its database via input data. A vulnerability to this exploit can lead to attackers being able to read sensitive data, modify existing data (Insert/Update/Delete), perform administrative operations on your database and in some cases even issue commands directly to the operating system of the server.
More information on SQL Injection
w3schools, owasp.org
To avoid SQL Injection vulnerability, you should never directly merge or concatenate data into an SQL query through string operations (f-strings, + operator, string interpolation with %, etc.). Always use the parameterized queries included with the library you are using.
Examples of parameterized queries for popular libraries
psycopg2, asyncpg, sqlite3, mysql
bv
hey everyone :) Is there a way to get all the channels that were deleted in a guild?
no, there's no history that keeps track of that
audit log doesn't go back more than a week afaik
there are these invisible messages. Is there an event when you discard this message?
no
async def mycmd(ctx : discord.ApplicationContext):
await ctx.respond("Hello World!", ephemeral=True)
dont really understand how we should do then, here the thing say to not use interpolation with %, however in the guid u send its using that
e.g
insert_stmt = (
"INSERT INTO employees (emp_no, first_name, last_name, hire_date) "
"VALUES (%s, %s, %s, %s)"
)
data = (2, 'Jane', 'Doe', datetime.date(2012, 3, 23))
cursor.execute(insert_stmt, data)
ephemeral = the invisible msg
Hi, after I first run my bot my slash commands work fine. Then shortly after they disappear and I can't use them. If I run bot.sync_commands() they show up again, only to disappear again shortly after. Any idea what I am doing wrong?
okay u sure? because I just tried it with audit log and it seems to retrieve all deleted channels since I opened my test server (1 month ago)
Did u overwrite the on connect ?
And where do u load cogs
No, I don't use the on connect
I'm not using cogs, documentation said they were optional. Do I have to use them?
No
But it would help to build a structure
Could it be something with too many slash commands in my guild? I read something about that in the past and we have a ton.
Hmm, I'd have to make a count. Think they would show up and disappear like that because the limit?
Yes might be possible
U can check the number of slash command pretty easily with a control f
Sorry not sure what you mean. Do you mean ctrl-f in the discord and use the search or ctrl-f in my code (there are only 4 in my bot).
How many slash commands does your bot have?
4 slash commands
45 days
Here is an example of one:
async def initiatesummary(ctx, option : discord.Option(str, "Days back to evaluate (default 30)", required = False, default = "30")): ```
If you add guild its only gonna show up at the added ones
Yeap, I did that after having the issues. I'm only working in one guild atm anyway.
Can u check if u donβt have another instance of ur boy running ?
Yeap, I'll double check. I'll just kill and restart everything.
Heh, that may have been it
. They are holding up longer than normal at least. I may have accidently double clicked the file at one time. Thank you!
trying to made mute command with timeout, but getting this error.
code:
@bot.slash_command(name="mute")
@commands.has_role("Staff")
async def mute(ctx, user:discord.Member, reason = "None"):
embed = discord.Embed(color=discord.Color.red(), title="User has been muted", description="You just muted user")
embed.add_field(name="User", value=user, inline=True)
embed.add_field(name="Reason", value=reason, inline=True)
await ctx.respond(embed=embed)
embedl = discord.Embed(color=discord.Color.red(), title="Muted", description="You has been muted")
embedl.add_field(name="Admin", value=ctx.author, inline=True)
embedl.add_field(name="Reason", value=reason, inline=True)
await user.send(embed=embedl)
await user.timeout(datetime(year=2100, month=1, day=1),reason=reason) #not working
bot.run(config.TOKEN)
error is to big lol
error:
Ignoring exception in command mute:
Traceback (most recent call last):
File "C:\Users\V\PycharmProjects\ilias_Projects\venv\lib\site-
File "C:\Users\V\PycharmProjects\ilias_Projects\venv\lib\site-packages\discord\commands\core.py", line 1013, in _invoke
await self.callback(ctx, **kwargs)
File "C:\Users\V\PycharmProjects\ilias_Projects\bots\FCB\main.py", line 175, in mute
await user.timeout(datetime(year=210 0, month=1, day=1),reason=reason)
File "C:\Users\V\PycharmProjects\ilias_Projects\venv\lib\site-packages\discord\member.py", line 873, in timeout
await self.edit(communication_disabled_until=until, reason=reason)
File "C:\Users\V\PycharmProjects\ilias_Projects\venv\lib\site-packages\discord\member.py", line 847, in edit
data = await http.edit_member(guild_id, self.id, reason=reason, **payload)
File "C:\Users\V\PycharmProjects\ilias_Projects\venv\lib\site-packages\discord\http.py", line 373, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In communication_disabled_until: Invalid communication disabled timestamp
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\V\PycharmProjects\ilias_Projects\venv\lib\site-packages\discord\bot.py", line 1130, in invoke_application_command
await ctx.command.invoke(ctx)
File "C:\Users\V\PycharmProjects\ilias_Projects\venv\lib\site-packages\discord\commands\core.py", line 376, in invoke
await injected(ctx)
File "C:\Users\V\PycharmProjects\ilias_Projects\venv\lib\site-packages\discord\commands\core.py", line 139, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In communication_disabled_until: Invalid communication disabled timestamp
Hey there, i have this code that if the cookie session is invalid it fetches a new cookie and retry to send the message, although sometimes i get
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
and sometimes i only get the cookie error as expected:
Cookie Error: Cannot fetch session cookie from https://www.vinted.it, because of status code: 403 different from 200.
Might be because it takes too much time
You should defer then
i defer at the start of the callback, should i defer in the exception too?
Only at the start
If u already defer thatβs strange
Well then im already doing it
Cos after a after u have 15min to answer and I donβt think ur code takes 15min
Maybe this is the wrong way to defer?
well i dont really know what to do
Can you past the full callback ?
.tag paste
If its too big
wait, i have to get the error again as i cleared the terminal π΅
Not traceback
Dw
alright thanks
what
it's wrong?
no im just confused at that function lol
what function?
nvm
if it's the create_fake_chat, it's just image manipulation nothing more π
Anyway, it doesn't send the message "bot is working" is it normal?
Send any errors and the code you used
This is the modal: https://mystb.in/3004e4b613aa340933 and when i get the error again i'll send it, but i think it's just the classic Unknown interaction
this is the original message
Not sure if this is the issue but you should be deferring with ephemeral=True if the response is going to be ephemeral
yeah i forgot to add it ty, when im home i modify the defer, although this isn't probably the issue as you said
can you move your if file file.close() to a finally block?
just abest practice
i will do it thanks, the code is a little bit different now from the one i sent
there are probably a lot of ways to improve it
@dense summit i think i found ur error
its not directly inside this modal here but in ur code in general
you might have some not async function that block ur entire code
like the time.sleep
It should be good now?
https://mystb.in/9e0a9ce86b69f7137e
As I told u I think itβs somewhere else in the code but this is still better
Also why do u do file.close ?
Since u donβt open it
I open it in the create fake chat function and i dont know why if i close the file there it doesn't work
It always throws like File is used by another process
Uhm are u sure? I get this error only when using this modal
Why donβt u do with file β¦
I think the issue is
Callback => blocking code for more than 3s, defer but too late
Im opening an image with PIL
that is blocking
You can run blocking code (such as PIL/Pillow) in an executor to run it in a separate thread: ```py
def my_blocking_func(*args):
...
@bot.command()
async def test_command(ctx):
ret = await bot.loop.run_in_executor(my_blocking_func, 'put', 'args', 'here')``` See the python documentation for more info.
i probably should have said this earlier
Like this right?
file = await self.bot.loop.run_in_executor(discord.File(create_fake_chat(lang.lower(), full, item_info.photo.url, item_info.title, format_float(item_info.price), price, output_path)))
try and see
is it possible to get the guild object from an id even if the bot is not in ?
its to check if the id passed is a guild or not
not always
i suppose technically you can attempt a fetch and if it returns forbidden it's a valid guild
just kidding
it returns 404
but i was thinking of guild widgets
is it possibile to save bot cache?
can you do it? absolutely
is there a built-in way? no
you'd be messing with the attrs in discord.Client._state
bro
py-cord is so annoying to use i should go back 2 discord.py
idk why i switched
go for it
cya
goodbye
damn
it probably isn't that difficult, you'd just have to screw with internals quite a bit
Man thought we'd beg
storing dictionaries isn't very hard
yeah
Β―_(γ)_/Β―
he's been here for months, should've figured out options by now
lol for me discord.py is more annoying, pycord is easier in some things
i agree pycord is better at some things
but idk what happened
everything was working well
i've made lots of apps in py-cord since i started
then today
well nobody can tell you because we don't know what you're doing
they js suddenly stopped working
i checked for conflicting packages
i used a venv
idk whats going on
π€·ββοΈ
code helps usually
that is a problem of your environment or what you are doing, not of the library
this
import discord
from features import create_embed, check_role
intents = discord.Intents.default()
intents.message_content=True
intents.moderation=True
intents.guild_messages=True
#We are using slash commands
bot = discord.Bot(intents=intents)
@bot.event
async def on_ready():
print(f"Logged in as {bot.user}")
is returning an error
and that error is
discord has no attribute bot
reinstall
can you drop a pip freeze
π
that might be a good idea
see if it does anything
why does pycord use the discord module and not its own module called pycord?
old relic from when we forked discord.py
didn't want to change the namespace because it would have been more work to migrate
if we ever go to v3 we'll probably change it
is that part of the plan?
it should be
ok so i installed it in a venv
i'll bring it up if we ever discuss it again
now lets see
wait
the first error went away
now i have a diff one
Option object is now callable
not
is that a python error or your ide being a little shit
if its the latter you can ignore it
idk i think python
well does the code run
you got a traceback?
in this case it is better to use the decorator ?
PS C:\Users\[redacted]\Desktop\vscodeprojects\mys_bot> & C:/Python312/python.exe c:/Users/[redacted]/Desktop/vscodeprojects/mys_bot/main.py
Traceback (most recent call last):
File "c:\Users\[redacted]\Desktop\vscodeprojects\mys_bot\main.py", line 21, in <module>
@discord.Option(
^^^^^^^^^^^^^^^
TypeError: 'Option' object is not callable
PS C:\Users\[redacted]\Desktop\vscodeprojects\mys_bot>
i prefer decorator because our typehints are known to be buggy asf
have fun!
ok it works :)
but
the options dont actually register
like
it wont set description and stuff
Why my options name and description doesnt fill with the values i passed? Also autocomplete doesn't work even tho i pass a valid list?
I tried to print the list, the name and the description values and they work
You could create a help post with your current code
Have you restarted discord?
ctrl + r is fine?
Yeah
yeah i did that
In your option. You have type=
It should be input_type=
Also put it after name= not sure if that is 100% necessary but it might help
still nothing :p, i have other code structured the same way as this and it works
Printing the value works, although it really doesnt want to show up
the command name and description works fine tho
Remove () after
get_filters_names()
Just want to check
You know the difference between choices and auto complete, right?
Choices are a static list of options, autocomplete is a dynamic list that updates depending on the list you pass?
Yeah i already tried this still nothing
Just wanted to make sure you were not mixing them up
Can you show the auto complete function
Yeah probably something wrong there
There isnt much
If i print db.get_all_filter_names()
My guess is the DB is taking a while to respond. Can you try changing the function to just return a static list temporarily
How are you loading your cogs, and do you override on_connect
Does this function return "filter_name"?
get_commandsinfo('bot_commands', ['filters_remove_command', 'options', 'filter_name_name'])
It returns "Nome"
I should probably change the key now that i read it, anyway this is not the issue :p
I think that is the problem.
The decorator is looking for a parameter with the name of Nome and cannot find one so it does not create the option. But than it seems that there is a filter_name parameter so it creates a default string option
If this was the case, if i print the function shouldn't it return None?
So when you use the option decorator you need to tell it what parameter of the function it is describing. You are telling it to look for Nome
async def filters_remove(self, ctx, Nome: str):
I assume that you want the option name on discord to be Nome and the name in the code to be filter_name?
parameter_name="filter_name" add this to the option
Also just a fyi I think discord requires option names to be lowercase
Looking at the code when I said use input_type before I was half right. You can use input_type or just type
if they are the same i get the description but empty autocomplete even if the list is still the static one
Can you show your updated option decorator
finally
what changed?
i did what you said https://mystb.in/2e51c5373214bb012f
sorry for all the troubles man
i didnt really know about the parameter_name arg
It is kinda hidden in the docs
No problem, I am here to help :)
this was exhausting, wasnt it?
maybe if we create a tag?
yeah just tested this
got this error on startup when making a new bot. on the newest version when doing pip install py-cord
container@PingHost:~$ python main.py
Traceback (most recent call last):
File "/home/container/main.py", line 3, in <module>
from cogs.utils import *
File "/home/container/cogs/utils.py", line 2, in <module>
from discord.ext import commands, pages
File "/home/container/.local/lib/python3.9/site-packages/discord/ext/pages/__init__.py", line 10, in <module>
from .pagination import *
File "/home/container/.local/lib/python3.9/site-packages/discord/ext/pages/pagination.py", line 31, in <module>
from discord.ext.bridge import BridgeContext
File "/home/container/.local/lib/python3.9/site-packages/discord/ext/bridge/__init__.py", line 26, in <module>
from .bot import *
File "/home/container/.local/lib/python3.9/site-packages/discord/ext/bridge/bot.py", line 31, in <module>
from discord.commands import ApplicationContext
File "/home/container/.local/lib/python3.9/site-packages/discord/commands/__init__.py", line 26, in <module>
from .context import *
File "/home/container/.local/lib/python3.9/site-packages/discord/commands/context.py", line 69, in <module>
class ApplicationContext(discord.abc.Messageable):
File "/home/container/.local/lib/python3.9/site-packages/discord/commands/context.py", line 271, in ApplicationContext
@discord.utils.copy_doc(Interaction.respond)
AttributeError: type object 'Interaction' has no attribute 'respond'
nvm github branch install fixed it
lol
is that at your main file?
that should be at the setup func. at the cog
yes
I have it in the cogs and main file
why at the main file?
At the main file you should have something like this load_extension
hey, can someone tell me what I did wrong?
@bot.listen("on_application_command")
async def on_application_command(command: discord.ApplicationContext):
if not command.guild:
if not command.interaction.context.bot_dm or not command.interaction.context.private_channel:
await command.response.send_message("This command is not available in dm's.", ephemeral=True)
I am calling the on_application_command event to get application commands and check their context. if they are executed in a guild I want them to be executed normal by the defined function. but if they are executed in a dm and do not have either of the bot_dm context nor the private channel context I want to suppress their execution. now I've encountered this error
Ignoring exception in on_application_command
Traceback (most recent call last):
File "E:\Programming\PyCharm\Dragons-BotV2\venv\Lib\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "E:\Programming\PyCharm\Dragons-BotV2\main.py", line 50, in on_application_command
if not command.interaction.context.bot_dm or not command.interaction.context.private_channel:
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: '_EnumValue_InteractionContextType' object has no attribute 'bot_dm'
Its not command but ctx since its a context (that not the issue)
You need to compare it
To
if you don't have the dm context set, the command won't show in dms anyway
If you had to guess what eta would you give for pycord 2.7 ?
Cause I'm hesitating between 2.7 before rewriting a really huge project that, notably, uses bridge, or just doing it because it really needs it.
uhhhhh 2.7 itself idk, we might be skipping it and be doing breaking changes with v3 instead...? but if that's the case, it'll be announced well in advance
imo pycord should go full semver at least from 3.0 on
I agree 100%
Wdym by semver ?
wel
plun
ig im still here
how can I see if a message has been reacted to with a given emoji?
as in, you wanna wait for that reaction, or you just want to read it from a message
I dont want to wait
I just want to see if it has a reaction
cause I am enumerating through messages
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 ...
ty
sometimes i cant find what im looking for in the docs
i mean, message.reactions is only logical lol
I asked the a different day but is there a way to make it so that I have a seperate file for each subcommand/view and such?
for views you can ofc just make different files but i think for the subcommands you need an extension called multicog, just google it, never worked with that tho
damn, you think I could I just define all my commands in one file then import functions and put them in there, like
@mm.command(name="1v1", description="Challenge someone to a 1v1 money match")
@option("player1", discord.Member, description="Player 1 Username",)
@option("player2", discord.Member, description="Player 2 Username",)
@option("value", int, description="value",)
@option("sponsor1", discord.Member, description="Sponsor for Player 1", required=False,)
@option("sponsor2", discord.Member, description="Sponsor for Player 2", required=False,)
async def mm1v1(self, ctx: discord.ApplicationContext,
player1: discord.Member,
player2: discord.Member,
wager: int,
sponsor1: discord.Member,
sponsor2: discord.Member,):
mm1v1function(paramters) ```
I agree, but it's slightly less messy than having all the subcommands in one cog
still way better than name: Option() stuff ;3
thats not what we're talking about tho :3
is there such thing as a subcog? that is what it seems the multicog is attempting but you said it doesn't really work

Hi ! This is a quick question. Is there a way to count the usage of slash commands of another bot ? For example the command /ping from bot X was run 40 time last week ?
no
Ooh I see thank you !
I currently have
reply = await ctx.fetch_message(ctx.message.reference.message_id)
await ctx.send(reply)
How do i get the content of a message instead of getting
<Message id=nuhuh channel=<TextChannel id=nuhuh name='general' position=0 nsfw=False category_id=nuhuh news=False> type=<MessageType.default: 0> author=<Member id=nuhuh name='nuhuh' global_name='nuhuh' bot=False nick='Not Nuhuh' guild=<Guild id=nuhuh name='Not a Discord Server' shard_id=0 chunked=True member_count=32>> flags=<MessageFlags value=0>>
Why do you want the context?
message.content?...
that is the content of the message sent by the user who ran the command
reply.content
When I say message it's a reference to the message object you're getting
Logged in as Not a Quote Bot#0518 (ID: 1279177215929745509)
------
quote
Ignoring exception in command quote:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.11/site-packages/discord/ext/commands/core.py", line 180, in wrapped
ret = await coro(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/container/bot.py", line 41, in quote
reply = await ctx.reply.content(ctx.message.reference.message_id)
^^^^^^^^^^^^^^^^^
AttributeError: 'function' object has no attribute 'content'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/container/.local/lib/python3.11/site-packages/discord/ext/commands/bot.py", line 349, in invoke
await ctx.command.invoke(ctx)
File "/home/container/.local/lib/python3.11/site-packages/discord/ext/commands/core.py", line 959, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/home/container/.local/lib/python3.11/site-packages/discord/ext/commands/core.py", line 189, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'function' object has no attribute 'content'
im trying to create a quote bot. If you reply to a message, I want the bot to get the content of the message that the user replied to
What the hell did you do
reply = await ctx.fetch_message(ctx.message.reference.message_id)
reply.content # <-- That's your content
Description: Get a tag
Cooldown: 5 seconds
Usage:
?tag get (optional category) [tag name]
Example:
?tag get how2invite
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.
hey, is the @discord.guild_only() decorator broken? I've tried decorating many commands with it but I can still execute them in a direct message with the bot. Or do they need (up to) 1 hour to be removed from the dm's?
Its not removed from dm`s
guild_only is just a check if the command was executed at a guild or not
but it's also not raising any error
Use contexts
okay, I guess I'll do that for every command, thanks :D
You can pass that directly in group
For they it apply to each subcommznd
Is there an overview on the differences between discord.Bot and discord.ext.commands.Bot? Which one should I use?
I want to support prefixed commands as well as slash commands.
pls ping me with a response, thanks
.tag client
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
bridge.Bot # above + bridge commands (application commands and text commands in one)
Alright, so I should use commands.Bot then, thanks!
hmm, after changing most of my slash commands to use contexts I now get this error
Ignoring exception in on_connect
Traceback (most recent call last):
File "E:\Programming\PyCharm\Dragons-BotV2\venv\Lib\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "E:\Programming\PyCharm\Dragons-BotV2\venv\Lib\site-packages\discord\bot.py", line 1214, in on_connect
await self.sync_commands()
File "E:\Programming\PyCharm\Dragons-BotV2\venv\Lib\site-packages\discord\bot.py", line 742, in sync_commands
registered_commands = await self.register_commands(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "E:\Programming\PyCharm\Dragons-BotV2\venv\Lib\site-packages\discord\bot.py", line 541, in register_commands
desynced = await self.get_desynced_commands(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "E:\Programming\PyCharm\Dragons-BotV2\venv\Lib\site-packages\discord\bot.py", line 364, in get_desynced_commands
elif _check_command(cmd, match):
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "E:\Programming\PyCharm\Dragons-BotV2\venv\Lib\site-packages\discord\bot.py", line 278, in _check_command
as_dict = cmd.to_dict()
^^^^^^^^^^^^^
File "E:\Programming\PyCharm\Dragons-BotV2\venv\Lib\site-packages\discord\commands\core.py", line 962, in to_dict
as_dict["contexts"] = [ctx.value for ctx in self.contexts]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "E:\Programming\PyCharm\Dragons-BotV2\venv\Lib\site-packages\discord\commands\core.py", line 962, in <listcomp>
as_dict["contexts"] = [ctx.value for ctx in self.contexts]
^^^^^^^^^
AttributeError: 'str' object has no attribute 'value'
No traceback to my code, but I don't understand the libary code enough to find the origin of it
show what you changed
^ btw the commands are still available in the dm's and can be executed
@pycog.subcommand("mod", independent=True)
@commands.slash_command(
name="warn", description="Warns a given member", contexts=(discord.InteractionContextType.guild)
)
@is_team()
@discord.option("member", description="The member you want to warn", input_type=discord.Member, required=True)
@discord.option("reason", description="The reason for the warn", input_type=str, required=True)
async def warn(
self,
ctx: discord.ApplicationContext,
member: discord.Member,
reason: str,
):
...
I've a few more of these commands and just added the contexts parameter to them with just InteractionContextType.guild
before there was just contexts not in the slash command
ohh, but I don't have a "main" mod command
Still
subcommand contexts are the same as the contexts for the group itself
(also, you cant have the group also be a command on its own)
pycog is a decorator from pycord-multicog -> https://pypi.org/project/pycord-multicog/
ah
yeah, most likely I have to refactor the code to have a "main" SlashCommandGroup
and just not let it be autogenerated
also you dont need input_type if its a str, and you also dont need required=True
just to be shorter
also, i have no idea if multicog supports contexts at all lol, so take this with a grain of salt
hasnt been updated since they released
but there is still no libary native way to split slash command groups over multiple cogs/files, is there?
not that i know of
okay, thanks I'll try refactoring it and be back if the error persists/change/resolves :D
Uhhm, so I've started debugging a little in core.py, maybe someone with more knowledge of the core libary and python should look at this xD
It seems like here originates the problem. I've changed the code for debugging purposes to this
if not self.guild_ids and not self.is_subcommand:
as_dict["integration_types"] = [it.value for it in self.integration_types]
for ctx in self.contexts:
print(ctx)
print(type(ctx))
try:
print(ctx.value)
print(type(ctx.value))
except Exception as e:
print(e)
print(type(e))
as_dict["contexts"] = [ctx.value for ctx in self.contexts]
the output is this
guild
<class 'str'>
'str' object has no attribute 'value'
<class 'AttributeError'>
0
<class 'int'>
'int' object has no attribute 'value'
<class 'AttributeError'>
I'd suggest moving this to a thread to save this place for "quick questions" π
Thread -> #1280616860509016125
What is ur issue ?
And what do u want to do
Slash commands are still showing in dm's even through the contexts attribute of the SlashCommandsGroup does not allow it.
Make a group then
contexts needs to be an iterable
Discord.SlashCommanGroup()
U make that and u make sure to load the cog with that before the other
with how you have it set up: (discord.InteractionContextType.guild) is not an iterable
Then u use ur multicog like normal without the independent
ohh, okay? but I only want it available in guilds, since everywhere else it's not working. How can I do that?
Do like so
either slap a comma on the end:
(discord.InteractionContextType.guild,)
or make it a set (it's supposed to be one):
{discord.InteractionContextType.guild}
when im loading my bot I'm getting this error, I mean the bot still loads but I don't know what's causing this
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In 1.options.4.options.5: Required options must be placed before non-required options
In 1.options.4.options.6: Required options must be placed before non-required options
In 1.options.4.options.7: Required options must be placed before non-required options
okay, thank you <3
U have pute = None before some other
If u want to do it for the whole group do like so @hexed herald
Else u will have to do it for each command
(The goal is to create a group and the. To load it before the other)
I've tried both solutions but it's still throwing the same exception.
Ignoring exception in on_connect
Traceback (most recent call last):
File "E:\Programming\PyCharm\Dragons-BotV2\venv\Lib\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "E:\Programming\PyCharm\Dragons-BotV2\venv\Lib\site-packages\discord\bot.py", line 1214, in on_connect
await self.sync_commands()
File "E:\Programming\PyCharm\Dragons-BotV2\venv\Lib\site-packages\discord\bot.py", line 742, in sync_commands
registered_commands = await self.register_commands(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "E:\Programming\PyCharm\Dragons-BotV2\venv\Lib\site-packages\discord\bot.py", line 541, in register_commands
desynced = await self.get_desynced_commands(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "E:\Programming\PyCharm\Dragons-BotV2\venv\Lib\site-packages\discord\bot.py", line 364, in get_desynced_commands
elif _check_command(cmd, match):
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "E:\Programming\PyCharm\Dragons-BotV2\venv\Lib\site-packages\discord\bot.py", line 278, in _check_command
as_dict = cmd.to_dict()
^^^^^^^^^^^^^
File "E:\Programming\PyCharm\Dragons-BotV2\venv\Lib\site-packages\discord\commands\core.py", line 962, in to_dict
as_dict["contexts"] = [ctx.value for ctx in self.contexts]
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "E:\Programming\PyCharm\Dragons-BotV2\venv\Lib\site-packages\discord\commands\core.py", line 962, in <listcomp>
as_dict["contexts"] = [ctx.value for ctx in self.contexts]
^^^^^^^^^
AttributeError: 'str' object has no attribute 'value'
also as list it's still failing for me, it's already it's own group without independent
Can you show me how u did it ?
import discord
from discord.ext import commands
from utils import Bot, CustomLogger
class CommandGroups(commands.Cog):
def __init__(self, client):
self.client: Bot = client
self.logger = CustomLogger(self.qualified_name, self.client.boot_time)
mod = discord.SlashCommandGroup("mod", contexts=[discord.InteractionContextType.guild]) # creating the command group
def setup(client):
client.add_cog(CommandGroups(client))
from datetime import datetime
import discord
import pycord.multicog as pycog
from discord.ext import commands
from discord.utils import format_dt, get_or_fetch
from utils import (
Bot,
ButtonConfirm,
ButtonInfo,
CustomLogger,
InfractionsEnum,
SettingsEnum,
is_team,
)
class Kick(commands.Cog):
def __init__(self, client):
self.client: Bot = client
self.logger = CustomLogger(self.qualified_name, self.client.boot_time)
@pycog.subcommand("mod") # <-- adding it to the subgroup
@commands.slash_command(name="kick", description="Kicks a given member", contexts=(discord.InteractionContextType.guild))
@is_team()
@discord.option("member", description="The member you want to kick", input_type=discord.Member, required=True)
@discord.option("reason", description="The reason for the kick", input_type=str, required=True)
async def kick(
self,
ctx: discord.ApplicationContext,
member: discord.Member,
reason: str,
):
...
def setup(client):
client.add_cog(Kick(client))
Donβt pass context in the command definition
U already put it inside the group
yeah, I didn't see that one my bad and after changing contexts to a set (as it's supposed) it's no more throwing errors, thanks for all the help
With pleasure
Does anyone have experience with the multicog plugin? I'm looking to separate each of my sub commands into a separate file
yeah, I guess I can help you

