#Basic Pycord Help
1 messages · Page 56 of 1
what is discord protos
idk
Im not really sure the issue here. As the code looks like it should work. Could you try downgrading to py-cord 2.6
Did nothing
why buttons are not permanent like as default? there's no way to be permanent to default?
why not? i mean, what is the reason about that
got it
it would take up a bunch of bot memory if people never properly closed them
i wanna make a ticket bot, so if i need to restart it it will be a problem
so i wanna make them default without using the PersistentBot()
well then make your views persistent
pass no timeout to the super constructor, run bot.add_view(Your view()) in on ready and give your buttons custom IDs
(timeout=None)
im not really sure what to tell you. You could ask in the python discord why your class is not treating the first arg as self.
discord.gg/python
I've figured something out
it doesnt happen when 1 command group is in a cog
but only whenever there is another
oh that is strange. I guess just split up your command groupd then because we dont have a better solution
seems like a bug report waiting to happen
I am trying to create a simple slash command to ping a specific role in a server
how to I get the bot to actually ping the role instead of printing the name of the role (without the ping)
thanks
Is the role the same thing every time?
yes
so what does the current message and code look like?
am I able to send attachments through a modal dialog?
using allowed mention
discord.AllowedMentions
discord.AllowedMentions.all
discord.AllowedMentions.everyone
discord.AllowedMentions.none
discord.AllowedMentions.replied_user
discord.AllowedMentions.roles
discord.AllowedMentions.users
discord.Bot.allowed_mentions
discord.Client.allowed_mentions
discord.mentions.AllowedMentions
discord.ext.commands.Bot.allowed_mentions
@sage tendon Command Choice in Py-cord bridge command??
BridgeOption??
or what
@errant trout i'm correct ??
BridgeOption is correct yes
ok thank u so much
Dont ping people for support please.
imagine reading the docs
that man was panicked, 2 ping, 6 ?, i hope it was not a matter of live
Dumb question. In this example, the checks uses .predicate. Is that required for all types of checks, like commands.has_permissions(kick_members=True), or is that statement enough?
Hm. Well I can confirm that .predicate doesn't actually restrict it. Let's see if removing that has any effect.
I cannot seem to get this to work, btw. Dunno if you've ever personally modified a command like this that we can compare notes.
moderation_group = SlashCommandGroup("mod", "Moderation Tools and Settings", checks=[commands.has_permissions(kick_members=True)])
This doesn't prevent people without the kick_members permission from seeing the slash commands, like the previous conversation suggested.
default_permissions is separate from checks and has_permissions
It is its own kwarg that you pass a permissions object to I believe.
default_member_permissions is the correct name i guess
default_member_permissions=Permissions(kick_members=True) instead of checks=...
You only need Permissions(...), not commands.has_permissions?
correct
commands.has_permissions is the check that is preformed bot side only
Where default_member_permissions is sent to discord upon command registration, so discord enforces it
Yay. there we go; some sensical restrictions until being able to change the Integration. Thanks for the sanity check.
When you say user_command
are you talking about user installs or when you right click on a user and can select a command from the list?
yeah talking bout the "apps" when right clicking on a user
It should be the same as other commands in a cog
@discord.user_command()
the callback just takes 1 argument of user (after self and ctx)
yeah makes sense, thank you
i saw this example, and i wondered how to use it in a cog, because it requires the argument self
def is_me():
def predicate(ctx):
return ctx.message.author.id == 85309593344815104
return commands.check(predicate)
@bot.command()
@is_me()
async def only_me(ctx):
await ctx.send('Only you!')
i tried this now:
import discord
from discord.ext import commands
from globalsupport import emoji, colour
from datetime import *
import os
class BanListenerCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.team_role_id = 919707797208305666
@staticmethod
def has_serverteam_role(self):
def predicate(ctx):
return self.team_role_id in [role.id for role in ctx.author.roles]
return commands.check(predicate)
@commands.Cog.listener()
async def on_message(self, message):
..........
@discord.user_command(guild_ids=[], name="addSperre")
@has_serverteam_role()
#@commands.has_permissions(administrator=True)
async def addSperre(self, ctx, member: discord.Member):
await ctx.respond(f"{emoji().success} {ctx.author.mention}, test test", ephemeral=True)
def setup(bot):
bot.add_cog(BanListenerCog(bot))
but i get 'staticmethod' object is not callable
lol remove the self if you use staticmethod
No valid attachments found
Does pycord supports the Guild subscriptions of the monetization category of Discord API ? referenced here
Yes I believe
sadly I saw there is a PR for the 2.7 about this implementation.
And without much tests because plun1331 does not have a verified app or can't in his country
Lala gave him perms for a test bot. Idk if he ever got around to testing it though
@edgy nest Did you test that PR? ^
nope
Can I distinguish between a scheduled event that was deleted by a member and one that was completed (and essentially removed automatically).
I'm only seeing on_scheduled_event_delete (and possibly on_scheduled_event_update), not sure how they react in those two cases.
I'd just check if the event's end time is within 1 or 2 seconds of now and if that's the case, its most likely just normally completed
or actually, maybe once its normally completed its updated and you can check its status
not really sure, never used events myself
but the status might be the better choice https://docs.pycord.dev/en/stable/api/enums.html#discord.ScheduledEventStatus
The API provides some enumerations for certain types of strings to avoid the API from being stringly typed in case the strings change in the future. All enumerations are subclasses of an internal c...
status is the answer, yes
I'm a bit confused and intrigued. I'm storing current event ids with guild.events. That doesn't pull completed events though, only ones that are still upcoming (or active I believe). So does this imply I can reference a completed event, that doesn't pull from guild.events? Hopefully referenced via event id.
You just wanna compare if a completed event matches an event ID you stored right?
Yeap, looks like I can check if a event ID was cancelled or completed (which is awesome). I just assumed if it was no longer in guild.events it was gone and couldn't be referenced (seems like I assumed wrong, which is awesome).
Now I just need to see if on_scheduled_event_delete triggers cancelled or completed.
delete is for actual deletions, almost certainly not the other two
if you can't find them in the events cache, consider fetching them using guild.fetch_scheduled_events
(the library attempts to cache them where possible, but it's not guaranteed)
Hmm, if that's the case maybe I could use the fact that it can't be found at all, it was manually deleted.
Maybe on_scheduled_event_update triggers to check cancelled or completed.
mhm
the official docs show some examples on how certain values update https://discord.com/developers/docs/resources/guild-scheduled-event#guild-scheduled-event-status-update-automation
Awesome thanks for your help. This will work then. Would of took a butt load of testing to parse this out.
am I crazy or can you not include a timestamp (eg. <t:0:f>) in an embed?
depends where
i'd like to put it in the value of a field. but i can't seem to get it to work anywhere
i also want to put it in the embed description
well i'm just literally seeing <t:0:f> instead of <t:0:f>
show the embed
you cant put comma values lol
i forgot to convert to an integer
i should get more sleep
thanks for being my rubber duck
lol i was literally just thinking about the rubber duck thing cause of this
Hey all, qq about how slash commands refresh, I have a slash command with options option_a and option_b, if I update the description of the options I see it reflected immediately upon discord refresh, but if I change option_a to Option1 it doesn't refresh
I'm assuming this has something to do with how they're being stored in discord, is there a way to update the options within a command? or do I need to make a brand new one?
show your code
you dont need the name option in the slash command decorator btw
and you dont need an option type if its str
I mean they don’t need to add the type hint inside the decorator since they already put it inside the register
You do
no
Try and see
If using only the type hint from the command definition and I have every type hint working fine
Apparently u don’t by thinking decorator needs it
yea now you edited the message and it means the opposite
I mean I just change twitch to hint
And add decorator for more context which is kinda not needed cos what can it be else than the decorator
to be clear about the decorator and type
@discord.option(name="test", type=discord.Role, description="")
async def test(self, ctx: discord.ApplicationContext, test):
is the same as
@discord.option(name="test", description="")
async def test(self, ctx: discord.ApplicationContext, test: discord.Role):
but you lose the autocomplete so the 2nd is better and it useless to have both typehint (except you want it for u)
where can i see the differences between discord.py and pycord?
At the code
no like i mean why use pycord if theres discord.py
Pycord and other forks exist because discord.py stopped receiving updates, but it's back now. Just use whichever you prefer lol
d.py stopped when interactions were introduced
Then Danny resumed its maintenance
Since interactions, the implementation between d.py and pycord is different
no, it was a bit after that. It was closer to when message content intent as a privileged intent was introduced
yeah, but slash commands and other interactions were introduced nearly a year prior
albeit early versions
is it possible to only show specific members in a slash command discord.Member option or do I need to use autocomplete?
not possible, also discord.Member does not really exist in slash command, so you will also need to check if that user is also a member
is it possible to stream my Desktop audio to a voice chat?
Are you talking about through a bot into the vc or from your discord app to the vc?
Like, i'm watching a video on yt and the bot streams the desktop audio
at that point just use watch together
Anyone know offhand whether animated emoji can be set to a Button's emoji property? I would think yes but worth asking
yes
One thing that would be great for the Guide is some sort of visual of what's targeted with interaction.edit, interaction.edit_original_response and interaction.edit_original_message 😵💫
And is interaction.response.edit_message (as printed in the Guide) the same as interaction.edit_original_message?
no
anything under interaction.response is a direct response to an interaction (also, edit_original_message is deprecated in favor of edit_original_response)
edit_original_response is essentially a regular message edit
i still think something like interaction.response_handler would be a better name
it keeps confusing me, the fact that its called response
meh
So that won't trigger a 'responded'? I want to disable buttons when they're pressed but I am still going to be doing operations on the interaction. Don't want to hit "already responded to" or whatever it's called.
just use interaction.respond and interaction.edit, it handles the logic for you
(same usage as ctx.respond and ctx.edit, these were added in 2.5 or so)
Then this (with the correct methods) is doubly needed 😅
An image of a message with UI elements, highlighting the messages with which exact methods will change what parts of the flow.
guide PRs are always welcome (or even just raising an issue, if you don't want to change it yourself)
How can I get a message sent before the bot restarts (sent by the bot) to edit it? I understand it has to do with the cache and that for reactions, you have to use the raw event instead, but what about for editing?
just fetch the message
discord.errors.NotFound: 404 Not Found (error code: 10008): Unknown Message
oh wait, hold on. I think I'm using the wrong channel ID
But this should work?
"Unknown Message"
Wouldn't it return that if it was a message it didn't have cached either?
no, it would just be None
Ah, gotcha.
Hmm, how can I use fetch_message without knowing the channel?
Ok, thanks
If i pass a message url instead of a message ID, is there a way to parse that directly in pycord or should I just split by backslash (or url parsing)?
Why do you have the message link lol
I'm trying to make a slash command to edit messages that the bot previously sent in case of factual errors (an FAQ of sorts)
Because the bot already sent the messages. And now I need to edit one out of tens
If I was planning this in advance, I would. But the messages have already been sent. Tens, months ago.
MessageConverter handles URLs
ah
Whatever, it's fine. I pass a channel and message ID to the bot and it works
Oh, great. Thanks!
TIL
Doesn't seem to work for forum channels. Hmm
eh it's just guildid/threadid/messageid, but i guess get_channel might fail for forum threads...?
It seems to be the same format, but I think the middle is the forum thread instead of channel
did you get an error
oh guild
Yeah, discord.ext.commands.errors.ChannelNotFound: Channel "1197763716037476423" not found.
thread id imagine
mmmmm if it's stuck at the thread then there's no way around it on converter unless it's patched separately
butttttt you can use the related functions to parse the IDs anyway
guild_id, message_id, channel_id = PartialMessageConverter._get_id_matches(ctx, argument)
see https://github.com/Pycord-Development/pycord/blob/master/discord/ext/commands/converter.py#L345
(in the long run you might find it more useful to just write your own regex, whatever works)
yeah i'm inclined to agree
Is there a way to pass a message with newlines to a slash command (without modals)?
It does. Thanks
Is there a better alternative to on_interaction? I need to run some code before every slash command/componenet that is used. (I.e. checking if there is a cooldown, checking if the command/component is disabled, etc.)
cooldowns raise exceptions, if a component is disabled then it would not allow it to be interacted with in the first place, to check whether the command is disabled then use a custom check
how do I put a file in embed.set_image()?
if you're handling both commands and components, then on_interaction is probably the best one
alright
for command cooldowns there is a built in system which you can see in examples
.tag local-file
f = discord.File("some_file_path", filename="image.png")
e = discord.Embed()
e.set_image(url="attachment://image.png")
await messagable.send(file=f, embed=e)```
Is there a way to get the full command name rather than just part of it?
Currently I'm using interaction.data. It returns a json, but not the full name
let me see
i'd say either:
- use
on_application_commandinstead if you have to use on_interaction, runnvm that doesn't workawait bot.get_application_context(interaction)and then accessctx.command
tl;dr just use on_application_command to save you the headache, then handle components in on_interaction
ig
And last question, how do I have the command or button stop running within on_application_command or in on_interaction
preview = discord.File('C:/path/preview.jpg', filename='live_preview.jpg')
game_icon = discord.File('C:/path/game_icon.jpg', filename='live_game_icon.jpg')
embed.set_image(url='attachment://live_preview.jpg')
embed.set_thumbnail(url='attachment://live_game_icon.jpg')
what`s wrong?
its empty
are you sending the files with the message as well?
no, should i?
ye now it works
thanks The Toothy 💕 and The Nelo
Discord having an issue?
DiscordServerError: 503 Service Unavailable (error code: 0): no healthy upstream
yes
What is a simple way to remove all mentions in a message's content?
Dépends if u want to keep the mention but remove the ping or just remove the mention
It’s either allowedmention
Either
like for example " @dusk violet hello"
I would keep that message the same but remove the whole @Mimi part
and just leave it as "hello"
Is there a way to get the channel creator of a text channel?
@fossil valve You get the audit logs for around then the channel was created and there you can maybe find who created it. Idk if that works but yeah
I see thought also this would be an option. But found a simpler solution, still thank you for your help :)
is there an argument to be able to get some slash commands to work only with the users I have here ? I want to make some commands only available for me for beta version
Custom check
Why doesn't on_application_command or on_interaction run before the command is executed?
they do, but they are listeners
or, well let me phrase differently, ultimately they are just events
if you make them as listeners, they won't intercept anything - you'd have to override the original events
Application Command raised an exception: DiscordServerError: 503 Service Unavailable (error code: 0): upstream connect error or disconnect/reset before headers. reset reason: overflow
what is this error?
(for commands, there's multiple systems such as checks or before_invoke instead)
probably just discord issues
it happened around 12 hours ago
i found it in my bot logs
oh alright then
damn that's crazy, https://discordstatus.com/ shows a spike in errors exactly 12 hours ago
is there currently a way to create client emojis?
What is the global rate limit for adding reactions?
not yet
alright
how do I fetch a message with a message id with a user bot?
U can’t as far as I know
it's a message the bot sent
User bot => user app ?
yes
Since they don’t have access to the channel I don’t see how u can fetch a message since to fetch a message u also need a channel
id still reckon you cant
Maybe you can implement a cache system to get each message of ur bot in case you really need
I need to edit the message the bot sent
Can’t you do
msg = …
await msg.edit ?
Maybe store it as an object for then u can use it again
Never really used user app but as far as I know it’s just limited asf
do I need guild id?
discord.PartialMessage
discord.PartialMessage.add_reaction
discord.PartialMessage.channel
discord.PartialMessage.clear_reaction
discord.PartialMessage.clear_reactions
discord.PartialMessage.created_at
discord.PartialMessage.delete
discord.PartialMessage.edit
discord.PartialMessage.fetch
discord.PartialMessage.guild
discord.PartialMessage.id
discord.PartialMessage.jump_url
discord.PartialMessage.pin
discord.PartialMessage.pinned
discord.PartialMessage.publish
discord.PartialMessage.remove_reaction
discord.PartialMessage.reply
discord.PartialMessage.to_message_reference_dict
discord.PartialMessage.to_reference
discord.PartialMessage.unpin
.rtfm PartialMessageable
discord.PartialMessageable
discord.PartialMessageable.can_send
discord.PartialMessageable.fetch_message
discord.PartialMessageable.get_partial_message
discord.PartialMessageable.history
discord.PartialMessageable.pins
discord.PartialMessageable.send
discord.PartialMessageable.trigger_typing
discord.PartialMessageable.typing
.tag 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:")
whelp
File "/usr/local/lib/python3.11/site-packages/discord/commands/core.py", line 138, in wrapped
ret = await coro(arg)
^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/discord/commands/core.py", line 1078, in _invoke
await self.callback(self.cog, ctx, **kwargs)
File "/prunbot/cogs/simple.py", line 58, in post
await partial_message.edit(content=to_post)
File "/usr/local/lib/python3.11/site-packages/discord/message.py", line 2220, in edit
data = await self._state.http.edit_message(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.11/site-packages/discord/http.py", line 368, in request
raise Forbidden(response, data)
discord.errors.Forbidden: 403 Forbidden (error code: 50001): Missing Access```
Uh
@slash_command(name="post", integration_types={discord.IntegrationType.user_install, discord.IntegrationType.guild_install})
async def post(self, ctx: discord.ApplicationContext):
"""Post a sales ad. Format: /post <location> <item> <price>..."""
db = await aiosqlite.connect("/data/prunbot.db")
await db.execute("CREATE TABLE IF NOT EXISTS posts (username TEXT PRIMARY KEY, channel_id INTEGER, message_id INTEGER)")
to_post = ""
for username, posts in self.posts.items():
for location, items in posts.items():
to_post += f"**{location}**\n"
for item in items:
to_post += f"- {item['item']} - {item['price']}\n"
to_post += f"last edited: <t:{datetime.now().strftime('%s')}:R>\n"
message_id = None
channel_id = None
async with db.execute("SELECT message_id, channel_id FROM posts WHERE username = ?", (username,)) as cursor:
post = await cursor.fetchone()
if post:
message_id, channel_id = post
print(message_id, channel_id)
if not message_id:
interaction = await ctx.respond(to_post)
response = await interaction.original_response()
message_id = response.id
channel_id = response.channel.id
else:
partial_channel = self.bot.get_partial_messageable(channel_id)
partial_message = partial_channel.get_partial_message(message_id)
await partial_message.edit(content=to_post)
print(message_id)
async with db.execute("INSERT OR REPLACE INTO posts (username, channel_id, message_id) VALUES (?, ?, ?)", (username, channel_id, message_id)):
await db.commit()```
I'm confused why it's giving you forbidden
yes
It is the bot's own message right
Can the bot see the channel? Idk if that gives you issues
it's the bots own message yes
try using edit_original_response
As that uses the interactions endpoint rather than /channels/.../messages/...
The interaction token is only valid for 15 min iirc.
If u do
msg = send
Await msg.edit
Does it works or give u forbidden
this makes no sense
msg = await ctx.send()
await msg.edit()
(I didn’t look to his code, more about the partial that give him forbidden)
jab is trying to edit a message using a channel id and a message id; no message is being sent
I know, is to check if it’s possible to edit a message with user app or not
if you cannot see the channel you cannot arbitrarily edit the message
you can still update it in response to an interaction
slay I was correct
so a user bot can't arbitrarily edit its own messages?
do you have to be able to see the channel to edit?
I would like to respond to an ephemera interaction after editing an ephemera but the problem is that it gives a 404 error
How could I solve it?
Show your code how you're doing it
await interaction.response.send_message(f"{video_urls[fruit]}", ephemeral=True)
# Update the view after sending the video
self.update_fruit_options()
embed = discord.Embed(
title="Selección de Fruta",
description=f"Selecciona tu fruta para el torneo (Página {self.current_page + 1}):",
color=discord.Color.blue()
)
embed.set_thumbnail(url=self.avatar_url)
await interaction.message.edit(embed=embed, view=self)
return
when pass the interaction.message.edit it gives error 404
Use interaction.edit
I'm going to try
I thought it was going to handle that.
Try interaction.response.edit_original_response
like this?
# Update the view after sending the video
self.update_fruit_options()
embed = discord.Embed(
title="Selección de Fruta",
description=f"Selecciona tu fruta para el torneo (Página {self.current_page + 1}):",
color=discord.Color.blue()
)
embed.set_thumbnail(url=self.avatar_url)
await interaction.response.edit_original_response(embed=embed, view=self)
await interaction.response.send_message(f"{video_urls[fruit]}", ephemeral=True)
return
else:
embed = discord.Embed(
title="Selección de Fruta",
description=f"Selecciona tu fruta para el torneo (Página {self.current_page + 1}):",
color=discord.Color.blue()
)
embed.set_thumbnail(url=self.avatar_url)
await interaction.response.edit_original_response(embed=embed, view=self)
await interaction.response.send_message(f"La fruta {fruit} no está permitida en el torneo. Intento {self.forbidden_attempts[fruit]}/3", ephemeral=True)
return
Yes
Sorry, remove the response
I'm going to scream
XD
someone
I'm going to have to make a threat, right?
You're responding incorrectly
You should first send the response and then edit it
Alternatively you can switch the responses
Respond editing the message and send an ephemeral followup
the problem with doing that, what would give this result
and the idea is that the first embed is edited
You can try this way:
we already tried that
oh wait
await interaction.response.edit_message(embed=..., view=self)
And then
await interaction.followup.send("{video url}", ephemeral=True)
with respond() and defer()?
no, let me try
@summer knot do this
ok
but respond() is easier, it automatically checks if it is a followup or not
I'm going to try both solutions
it worked
it works too
thank you
np
Having trouble reading Option handling. I see choices= can be a list when name and value are the same, but for name/value pairs, can choices= be a k:v dict, or must it be a list of OptionChoice(name, value)?
ah, nm, I should've read the docstrings (doesn't seem that's supported; might make a PR cuz I like being lazy)
list, but you could always make a function that converts a k:v pair to said list
or just [OptionChoice(name=k, value=v for k, v in dict.items())]
Yeah, realized I was doing that in one part of my code. But would be nice to be able to directly pass it in. Because again, lazy. Pycord should do everything I want in the least amount of userspace code 😛
I like your sense of humor
can we make the custom status sentence like YAGPDB does ?
I saw the activity and the status in the docs, but did not notice anything about it
Target not found, try again and make sure to check your spelling.
Target not found, try again and make sure to check your spelling.
okay thanks
we can do an hybrid command ? if yes how to do it ? (send me the guide link or an example)
Check ajout bridge
Well it’s outdated so check in the doc
ty a lot
in a cog bridge is build like that ? :
@bridge.bridge_command(name="mybridgecommand")
.tias
it send me an error
can you send a screenshot pls
will all those info u gave we will be able to give u the best help, yeah 100%
How in select, by selecting select type discord.ComponentType.role_select, can I make it so that only certain roles can be selected?
no
only all roles
Extension 'cogs.moderations' raised an error: TypeError: issubclass() arg 1 must be a class
(not a screenshot but that's work too lol)
@errant trout can i map command choices
wdym
mapping
solana = sol
$balance solana
$balance sol
in both case i want same output
@bridge.bridge_option(name="currency", description="Choose currency", choices=['solana', 'usdt', 'usdc', 'zack-morris', 'giga', 'mother-iggy', 'pollux-coin', 'vibe-shift', 'michicoin', 'neiro-3'])```
Mapping the Choices @errant trout
it can be possible??
use OptionChoice
ok
it takes a name which shows on the UI, and a value which is recieved in the variable
so you can have different names with the same value
thank u so much for helping me 🥹🥹
You could also use an Autocomplete, so if someone does type 'sol', it would direct them to the de facto "Solana" entry. You'd also be able to create a mapping that way
plz provide me docs link
Gotta learn to search the docs yourself. "Autocomplete" is pretty specific.
https://guide.pycord.dev goes over it, as well
thank u for helping me
I'm trying to get a modal to edit the original view
but I can't get the original view via the interaction
therefore, should I just store the initial view on modal creation?
nvm that's what I'm dong
doing*
But now if I want to update a select do I just remove and re-add the select?
A drop-down menu?
i figured it out ty
i just
newView = self.view
newView.remove_item(self.view.get_item('cardSelect'))
newView.add_item(self.upper.upper.cardSelect(self.setName, self.cur, interaction.user))
await self.upper.upper.message.edit(view=newView)
upper is just the class that's above the class
i have a weird structure
To update the user-selected options, I follow this method:
if there are more options it also works
I don't know if there is a better way to do it
i was adding an option and it was from a modal so
self.view prolly wouldn't work
I completely forgot that modals don't have that property, I'm not very familiar with modals, I only used them once for something very simple 
ye
@errant trout is it possible my bridge command only show in one guild??
@bridge.guild_only ??
how does the new bot emojis system work
same like guild emoji work
yeap
oki
you have to add the guild ID to the command with guild_ids=[]
can u give me example plz
that is only a check if the command was run at a guild or dm
command will only show in that guild na @little cobalt
Yes, that's what he literally said
The command will only register in the specified guild id(s)
yeap
i check
Please stop pinging people for help. Someone will eventually see your message. You have to be patient.
sorry for that i will never ping any one
Very mature...
do u play valo or minecraft
just for fun i do it
in which language tip.cc bot is made??
google it yourself
ok
it is not available
is it possible to take a file as an argument to a slash command?
you're 2(?) years late 
guh????
I guess I dont use bots a lot but still
🫃
so do I just do file: discord.Option(discord.Attachment, name="file")?
@sage tendon
yea
no
darn
(for all i know)
can you edit an ephemeral message?
try it
oki
Only with the interaction token/object
do boolean options exist or should I do str, options=["True", "False"]
oki
its so I dont have to take the time to bring the bot online and use the commnd
like sure its not a lot of time but its enough
i mean that takes all of 5 seconds
im running a few discord bots on large discords now. in total they are using about 3.5 GB RAM. are there any tips to increase performance
RAM usage doesnt affect performance*
*very sometimes it does
RAM is best used, not empty
Hi gang. Question: How can I retrieve messages that were sent to a channel while my bot was offline, and/or how can I retrieve the message history of a channel in general? I feel like I'm probably missing something obvious, but for the life of me I can't find anything related to this in the docs.
i mean its called channel.history https://docs.pycord.dev/en/stable/api/models.html#discord.TextChannel.history
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 ...
dumb question, how do I use choices with the option decorator
Here's the slash options example.
I assume you answered your question?
no
@option("gender", description="Choose your gender", choices=["Male", "Female", "Other"])?
@slash_command(name="post", integration_types={discord.IntegrationType.user_install, discord.IntegrationType.guild_install})
async def post(self, ctx: discord.ApplicationContext, user: str):```
I think so, Im a typehints user, toothy would know better 🙃
i think the slash dec goes first
How can I make a mention(role or user) but without notifying those of the mention?
uhh depends on what exactly you want
either:
- allowedmentions (normal message, no mention, no notification)
- silent (visible mention/highlight, but no notification)
- embed
silent
then just set silent=True in your send function
and when is it in respond?
(this is the same as adding @silent to the start of your message in discord)
when is ctx.respond the same?
for ctx.respond it doesn't exist, but i think the default behavior in respond is to not mention anyway
if you want to be safe, you just set allowed_mentions=discord.AllowedMentions.none()
oh the reply mention
yep
let me see the code
for replies, set mention_author=False
you must be using bridge no?
you can just do this then
no?
no uh
I'm going to try
i mean that if you use bridge.Bot, it'll force Context to BridgeExtContext even if it's not a bridge command
which is why you can use ctx.respond in a normal prefix command
I didn't know that curious fact
neither
This works within @bot.events, right?
as long as it's a regular channel.send or message.reply etc.
docs will have all available params https://docs.pycord.dev/en/master/api/abcs.html#discord.abc.Messageable.send
allgood
@commands.Cog.listener()
async def on_member_join(self, member):
welcome_channel = member.guild.system_channel
if welcome_channel:
welcome_message = await self.generate_welcome_message(member)
await welcome_channel.send(welcome_message, silent=True)
yes, that is how silent works
it shows the highlight, but they will not recieve a desktop/mobile notification
however the mention is notified to the users
uh
let me try
if you don't want the highlight/ping at all, then use allowed_mentions as such
also this shows that the message was silent
Is there a nice way i can stop mypy from complaining when declaring arguments to a command? For example:
argument: str = discord.Option(str, choices=SOME_CHOICES)
Gives the following error:
Incompatible default for argument "argument" (default has type "Option", argument has type "str") Mypy(assignment)
dont use the typehint way, use the @option decorator
also you're doing it wrong lol, you'd have to typehint it as option, not set the option as the default value
(still use the decorator)
Well damn
Does seem to work
Thanks
I coppied an pasted the example code from the pycode website to try it and start editing, and it's not working in discord. I've made sure discord.py is uninstalled and that i have py-cord not pycord installed and the bot has admin perms in the discord. The command does nothing though
import discord
import os # default module
from dotenv import load_dotenv
load_dotenv() # load all the variables from the env file
bot = discord.Bot(intents=discord.Intents.default())
@bot.event
async def on_ready():
print(f"{bot.user} is ready and online!")
@bot.slash_command(name="hello", description="Say hello to the bot")
async def hello(ctx: discord.ApplicationContext):
await ctx.respond("Hey!")
bot.run(os.getenv('DISCORD_TOKEN')) # run the bot with the token
is the bot invited with application commands?
all bots default to the application.commands scope now iirc?
Do you see the command at all?
Thank you so much, that was the fix. I feel silly
is possible to run 2 bots with the name script without creating another file?
like, just client.run(token1, token2)
why?
yes
client.run(token1)
client.run(token2)
client.run is a blocking line isnt it
just need to do 2 threads, use bot.start, etc etc
there is a lot of way to do that
.start()?
same bot with different name
(?)
https://github.com/Rapptz/discord.py/issues/516
This is old af but ig it works
i see but i need to rewrite the commands
@bot1.slash_command() @bot2.slash_command()
No other solutions right? i don't wanna rewrite them
You could technically subclass the bot and cover everything there, then just create two instances and run them?
Not quite sure tbh
Wouldn't this work then? With cogs
class MyBot(discord.Bot):
def __init__(self):
super.__init__(blah blah)
for cog in COGS:
self.load_extension(cog)
bot1 = MyBot()
bot2 = MyBot()
?
I'm genuinely tempted to see if it works
Time to open my laptop
thank you, so i will implement it ASAP. ❤️ 
It is completely stupid that Discord doesn't allow emoji for Options
Edit: It is also completely stupid that you can't have autocomplete for Selects. There needs to be parity between Options and Selects since you can't accept an arbitrary number of entries.
That is all.
Anyone able to tell me how to make a channel with pycord? I cant find any info except the discord.py way and that isn't working. I'm looking to make a channel in a specific catagory as well
(its the exact same as discord.py)
hi, quick question, is it possible with pycord to create those discord polls? ty
.rtfm polls
Target not found, try again and make sure to check your spelling.
discord.Poll
discord.Poll.add_answer
discord.Poll.allow_multiselect
discord.Poll.answers
discord.Poll.duration
discord.Poll.end
discord.Poll.expiry
discord.Poll.get_answer
discord.Poll.has_ended
discord.Poll.layout_type
discord.Poll.question
discord.Poll.results
discord.Poll.total_votes
discord.PollAnswer
discord.PollAnswer.count
is there a way to get an application command based on the id ?
get_application_command use the name for
ah tahnks, was searching on UI on the doc, thats why I didnt found
Bot._application_commands is a dict of id(str) : command
thanks
Hello, how can I make the buttons and menu selector (view) work even after a bot restart?
.tag persistent
The Issue
When you send a message with a view, button for example
if your bot restarts, you will lose the ability to use this button.
How To Fix This
- Set your view timeout to
None
- By default, the view timeout value is set to 300 seconds
- Pass a
custom_idvalue to the view
- Custom ids must be unique
- Chose a custom id that has a meaning in relation to your view
- Add the view to the bot
- You can use the method
Bot.add_view(YourViewClass()) - Make sure to add the view when the bot begin ready
Here's the persistent example.
Start with these and we can help if you have further questions:)
ooh ok thanks i only have to put a custom_id and add the view to the bot
(timeout=None is already done)
I forget -- A single Embed description has a limit of 4096 characters, can I split that up into two embeds in the same message, or is that essentially a message limit?
You can have up to 10 embeds in a message with all characters adding up to 6000
6K, gotcha. Thank you
"all characters" -- does pycord have any helpers to pre-determine the size of a message?
I don't believe so
len(embed) seems to work, at least; gives a starting point.
Interesting!
🏆 I have taught Wolfy something.
Any ideas?
bot | 2024-09-25 17:16:26,854 | Task exception was never retrieved
bot | future: <Task finished name='Task-31' coro=<ApplicationCommandMixin.on_application_command_auto_complete.<locals>.callback() done, defined at /usr/local/lib/python3.12/site-packages/discord/bot.py:876> exception=HTTPException('400 Bad Request (error code: 40060): Interaction has already been acknowledged.')>
bot | Traceback (most recent call last):
bot | File "/usr/local/lib/python3.12/site-packages/discord/bot.py", line 879, in callback
bot | return await command.invoke_autocomplete_callback(ctx)
bot | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
bot | File "/usr/local/lib/python3.12/site-packages/discord/commands/core.py", line 1111, in invoke_autocomplete_callback
bot | return await ctx.interaction.response.send_autocomplete_result(
bot | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
bot | File "/usr/local/lib/python3.12/site-packages/discord/interactions.py", line 1182, in send_autocomplete_result
bot | await self._locked_response(
bot | File "/usr/local/lib/python3.12/site-packages/discord/interactions.py", line 1292, in _locked_response
bot | await coro
bot | File "/usr/local/lib/python3.12/site-packages/discord/webhook/async_.py", line 224, in request
bot | raise HTTPException(response, data)
bot | discord.errors.HTTPException: 400 Bad Request (error code: 40060): Interaction has already been acknowledged.
the service_autocomplete func correctly returns a list of OptionChoice
Make sure you arent running your bot twice
I am not.
The autocomplete is running multiple API calls and DB queries, could time be an issue here?
After doing some testing, it does indeed raise the unknown interaction error.
That means you're not responding under 3 seconds.
nope
Does your caching work?
I think that interaction.id will be different for each autocomplete call so your cacheing will never actually be used
Oh actually, I messed up the caching dictionary
yeah
I switched it to the user id and it works now. The first call fails but oh well.
Thanks.
Yeah, that is very common for autocomplete
Why is that private btw
the library exposes Bot.application_commands as a list instead
private doesn't mean that you can't use it, but rather it may change without warning
I seem to be unable to post a local image inside of an embed even following https://docs.pycord.dev/en/stable/faq.html#how-do-i-use-a-local-image-file-for-an-embed-image. if the image is behind a http(s) url it inserts inside the embed, but if local using attachment:// is sends the image above the embed
is there a difference between sending it as a discord.File object vs discord.EmbedMedia?
make sure the filename is exactly right
and just send it as file, never seen embedmedia personally
this is the difference
unless there are size restrictions for the embed image
i will try the same image on https:// instaead of attachment:// and see if it will embed then
well, show your code
channel = ctx.channel
filename = f"{ctx.author.name} & {member.name}.png"
file = discord.File(f"images/{filename}", filename=f"{filename}")
embed = discord.Embed()
embed.set_image(url=f"attachment://{filename}")
await channel.send(file=file, embed=embed)
weird
i thought maybe a banner has to be specific dimensions
If I did that way always working for me ;3
maybe the file name?
spaces
try remove the ampersand
okay
and spaces too maybe yea
good guess cause i assume the spaces automatically convert to %20
instead of the space use _
tested 3 cases:
❎ no space
❎ no ampersand
✅ no space and no ampersand
you're not done yet :)
i'm not sure what .name even maps to anymore, but if it's NOT the "account" name, then you also have to watch out for spaces there
spaces are allowed in display names and not usernames right?
yea
but from what i see in the docs, .name is the account name
aka no spaces there
so all good
well i was planning to use the display name but that will only be inside the image..
cool thanks guys
say i want to contribute somehow. what makes more sense.. do more research and find out the test fail cases (or look in the code to see if its obvious) and edit the docs or include some kind of raised error in the actual code / type checking or whatever warns my ide of improper syntax before the code is run
i mean it's not really a bug or anything
shouldn't the ampersand and the spaces been converted to %20 and %26 url encoding?
u might need to put unicod
idk if its that
we already fixed it
mb then
i broke my general rule of don't f with spaces w/ filenames
the file names werent the issue
how so?
the URL was the issue because it replaces the spaces
ampersand made it fail too
same thing
Is it possible to call discord slash commands directly the pythonic way?
What do you mean
like lets say I have another discord command and need to call this discord command function directly and programmatically
You could simply extract the command functionally into a general function and use it on both commands.
u can invoke the command
can you ip ban somebody from a server so that even with his alts that never joined the server he's not gonna be able to get in?
when you ban someone I believe discord ip bans too by default
might be wrong tho
What paillat said
There is no additional way to IP ban someone. It just depends on what discord does by default
gotcha, thanks 🙌
i remember you can run commands through mentioning the bot without message intents, is it not possible anymore?
its possible
ah i just realised there's something wrong with my code
anyways is it possible to invoke application commands?
It is but it would be better to put all of the code in your app command in a separate function that you call from the app command callback and whereever else you want to invoke it
.rtfm invoke_app
discord.Bot.invoke_application_command
discord.AutoShardedBot.invoke_application_command
discord.ext.bridge.Bot.invoke_application_command
discord.ext.bridge.AutoShardedBot.invoke_application_command
discord.ext.commands.AutoShardedBot.invoke_application_command
discord.ext.commands.Bot.invoke_application_command
yeah that's what i did and my code is a complete mess
if u <ant pprerix and slash iu can use bridghe
bridge?
yes
I am trying to invoke an application command with parameters through discord with normal message, is it possible?
for instance, @bot <user1> profile <user2> will invoke the application command profile with the ctx author being user1
it should be possible if parameters can be passed into the invoke_application_command
ctx.author will never be different than the author of the message
i can just change ctx.author to the user's id and get the new context through get_context
because the context is given by the message
you can edit the message object and then process it
it will be easier
(if its possible)
like message.author = ..., await process message(message)
basically this is the code i wrote two years ago, and it works fine for message commands back then
right now idk how to make it work for application command
wdym by for application command ?
for a prefix trigger a app command ?
invoke is only for invoking normal commands, if i change it to invoke_application_command, idk where i can pass the command arguments into the application command
because apparently changing msg.content wouldnt work
the thing is
to invoke an invoke_application_command i think you need to have an interation
so i dont see how with a message content u will be able to trigger an application command
or you mean do /command @user image
and it will use @user as an author for the image app command
so i have to make the command triggered by slash command, so i can get the application ctx?
without an interaction u cant invoke an app context as far as i know
so yes you will need that
but if i understand ur trying to make a command to run another command changing the command author ?
what if creating an application context myself?
yes
you will still need an interaction
it's a lot more complicated than simply changing the author
like that's how discord works
maybe overwrite the command invoke to do ur change on the ctx there
btw shouldn't this be ApplicationContext?
how long does it require for new slash command to register?
instant, but you need to restart discord
ctrl + r works too
how do i get the command entered including the arguments from application context?
ctx.message returns None and ctx.command only returns the command
oh i thought they meant options in general oops
you're trying to recreate a sudo-esque command?
yes
but i just couldn't figure out how to make it in slash commands
you have to trigger it from some sort of interaction, either another slash command or a component such as a button
to modify stuff, you edit ctx.interaction (e.g. reassign ctx.interaction.user)
yeah i made the command a slash command but it still wouldn't work
if it's the method you used in the screenshot, of course not
i am still figuring out how to pass the arguments to invoke
it's because invoke_application_command runs entirely on context which has the args filled separately
you could just call the command's function manually instead
oh
let me try that rq
but i would need a dispatcher to show which command i am calling?
nvm i got it working, but i still have to find a way to pass the args
use respond() with slash commands
is reply deprecated?
its not for slash commands
oh
if you're insisting on this method, you need to look at the source yourself to understand how args are passed
https://github.com/Pycord-Development/pycord/blob/master/discord/bot.py#L1123
https://github.com/Pycord-Development/pycord/blob/master/discord/commands/core.py#L431
https://github.com/Pycord-Development/pycord/blob/master/discord/commands/core.py#L966
and understand that trying to approach slash the same as you did with prefix doesn't work
genuine question what is the plan here
sudo command that can run any command as any user
it can
it's significantly easier to just call the function directly though, instead of going through invoke
well, going through invoke makes the library treat it like a normal command call and goes through all the events and checks properly
but i would have to create a dictionary as a dispatcher to all the commands
why
otherwise how would i convert str inputs into command functions
just use get_application_command
(also autocomplete can list the commands out nicely)
using invoke won't help with your options because it relies on raw interaction conversions that discord would do for you
wait i can call the application command function directly?
so whats the point of having invoke command
that's basically what nelo is saying lol
invoke does all the necessary conversions that discord gave the client, and then calls the function at the end
look at the last link i posted, that's what it has to deal with
alr
assuming you're the only one using the sudo command, you handle the conversions yourself and just make sure you're doing the correct inputs that would safely pass any validation
yeah i ran into another issue and it's about the argument type conversions
i dont wanna hard code and manually convert everything though
you gotta
even if you were to use the invoke function, you'd have to manually recreate the interaction dict that holds options
yes and it's worse when i realise i have to manually change the "name" key for every command in the dict
do you really need an all-round sudo command, or do you only need it for one or two commands?
all-round
then you got a lotta manual work in store
well
if you want the quickest way, probably:
0. Decide how you're parsing the command string
- in your command, get the original command and check all the option types (Command.options -> Option.input_type)
- use
CONVERTER_MAPPINGfrom ext.commands to map the option type to a converter - use the converter and pray it works
then just call i guess
converter_mapping? i cant find it in the docs
because it isn't
from discord.ext.commands.converter import CONVERTER_MAPPING havefun
great
(don't bother for string/int/bool/float etc, this is for discord models)
and i thought luma was already too deep in the library
luma fucks with the library at a relatively surface level because he wants it to work with his own classes and models
(which isn't necessarily bad, but at that point you have to forgo regular help requests because most helpers aren't digging through the lib)
fair
How do I get the commands list JSON output to send over to discordbotlist
What's the format it expects?
Hello everyone,
Anyone free to help? 👀 😄
https://discord.com/channels/881207955029110855/1288898368831098937
how can i create forum tags? this is my code, but i have error
category = get(interaction.guild.categories, id=1284833150375166033)
overwrites = {
interaction.guild.default_role: discord.PermissionOverwrite(read_messages=False, send_messages=False),
interaction.user: discord.PermissionOverwrite(read_messages=True, send_messages=False)
}
channel = await category.create_forum_channel(name=self.children[0].value, overwrites=overwrites, topic=self.children[1].value)
tags = [
discord.ForumTag(name="pl", emoji="🌙"),
discord.ForumTag(name="re", emoji="📝"),
]
await channel.edit(available_tags=tags)
await channel.edit(require_tag=True)
Error:
Ignoring exception in modal <cogs.shop.Register_ShopInfo object at 0x000001E46D23B4C0>:
Traceback (most recent call last):
File "C:\Users\itskimlot\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ui\modal.py", line 341, in dispatch
await value.callback(interaction)
File "c:\LucyStudio\LucyStore\bot\cogs\shop.py", line 48, in callback
await channel.edit(available_tags=tags)
File "C:\Users\itskimlot\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\channel.py", line 1173, in edit
payload = await self._edit(options, reason=reason)
File "C:\Users\itskimlot\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\abc.py", line 428, in _edit
options["available_tags"] = [
File "C:\Users\itskimlot\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\abc.py", line 429, in <listcomp>
tag.to_dict() for tag in options.pop("available_tags")
File "C:\Users\itskimlot\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\channel.py", line 172, in to_dict
payload: dict[str, Any] = {
TypeError: unsupported operand type(s) for |: 'dict' and 'dict'
I tried to click on ForumTag in the documentation to check it, but it doesn't show up, so I'm asking my questions here. please ping me
sorry... the person who implemented this function used a feature only present in python 3.9 and above
no, it's not your fault at all
i'll update my python version and retry it!!
because the current library should fully operate on 3.8 still
but indeed, upgrading would be the easiest fix
(soon)
well, hence current
every command has a to_dict function
you can iterate through bot.application_commands
oh ok
async def test_photo(ctx, photo: List[discord.Attachment] = None):
can i do this?
no
These image sharing domain names..
Is there a good way to search number of messages by a user in a list of channels by doing backwards searching, or would it be better to monitor realtime and keep periodic updates
I think the latter is better
Why does this line
member = discord.Guild.fetch_member(182315234793488391)
give me this error?
TypeError: fetch_member() missing 1 required positional argument: 'member_id'
2 things.
discord.Guild is a class, not an instance. You should use an instance of discord.Guild
fetch_member is a coroutine, which needs to be prefixed with an await keyword
Hey, I may not get smth: it seemsn that I cant acess the Poll class through my code, whats the import? I now have those:
from discord import option, slash_command
from discord.commands import Option
from discord.ext import commands, tasks
from discord.utils import get
from discord.ui import Button, View, Select
discord.Poll
discord.Poll.add_answer
discord.Poll.allow_multiselect
discord.Poll.answers
discord.Poll.duration
discord.Poll.end
discord.Poll.expiry
discord.Poll.get_answer
discord.Poll.has_ended
discord.Poll.layout_type
discord.Poll.question
discord.Poll.results
discord.Poll.total_votes
discord.PollAnswer
discord.PollAnswer.count
that doesnt awnser my question: which import do I have to use to be able to call discord.Poll pls?
What do you mean ? For type hinting ?
Traceback (most recent call last):
File "/usr/local/lib/python3.9/dist-packages/discord/bot.py", line 1114, in invoke_application_command
await ctx.command.invoke(ctx)
File "/usr/local/lib/python3.9/dist-packages/discord/commands/core.py", line 375, in invoke
await injected(ctx)
File "/usr/local/lib/python3.9/dist-packages/discord/commands/core.py", line 132, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: module 'discord' has no attribute 'Poll'
@bot.slash_command(name="poll", description="Crée un sondage")
@option("question", description="Question du sondage", required=True, type=str)
@option("answers", description="Réponses du sondage", required=True, type=str)
@option("duration", description="Durée du sondage", required=False, type=int, choices=[1,4,8,24,72,168, 336])
@option("multiselect", description="Autoriser le multiselect", required=False, type=bool)
async def poll(ctx, question: str, answers: str, duration: int, multiselect: bool = False):
"""
Commande permettant de créer un sondage
"""
answers = answers.split(",")
poll = discord.Poll(question, duration=duration, allow_multiselect=multiselect)
for answer in answers:
poll.add_answer(answer)
await ctx.send(poll=poll)
.tag install
1. Uninstall discord.py or any other forks of discord.py you might have with the namespace discord.
python -m pip uninstall discord.py discord -y
2a. Install py-cord
python -m pip install py-cord
2b. Update py-cord
python pip install -U py-cord
Installing other builds:
Note: You need to have git installed. Use ?tag git to find out how to install git.
Updating the module to master branch (unstable):
pip install -U git+https://github.com/Pycord-Development/pycord
already did, and still the same :
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/usr/local/lib/python3.9/dist-packages/discord/bot.py", line 1114, in invoke_application_command
await ctx.command.invoke(ctx)
File "/usr/local/lib/python3.9/dist-packages/discord/commands/core.py", line 375, in invoke
await injected(ctx)
File "/usr/local/lib/python3.9/dist-packages/discord/commands/core.py", line 132, in wrapped
raise ApplicationCommandInvokeError(exc) from exc
discord.errors.ApplicationCommandInvokeError: Application Command raised an exception: AttributeError: module 'discord' has no attribute 'Poll'
are you using a venv ?
if not pelase set one up
Tag not found.
.tag venv
Sometimes you want to keep libraries from polluting system installs or use a different version of libraries than the ones installed on the system. You might also not have permissions to install libraries system-wide. For this purpose, the standard library as of Python 3.3 comes with a concept called “Virtual Environment”s to help maintain these separate versions.
Read more here
Learn how to set up a virtual environment for Pycord.
@summer scroll what's your pycord version
py-cord 2.6.1.dev114+ga2117adb
Try to stay away from the master branch when you dont need it
Just to be sure can you show your entire pip list
sure:
That looks fine. Like zery said try downgrading to a stable version 2.6.1. I can help more later
I had the same problem on the stable version tho, but I thought that upgrading could help
apparently no
maybe the problem is the way I use poll?
@bot.slash_command(name="poll", description="Crée un sondage")
@option("question", description="Question du sondage", required=True, type=str)
@option("answers", description="Réponses du sondage", required=True, type=str)
@option("duration", description="Durée du sondage", required=False, type=int, choices=[1,4,8,24,72,168, 336])
@option("multiselect", description="Autoriser le multiselect", required=False, type=bool)
async def poll(ctx, question: str, answers: str, duration: int, multiselect: bool = False):
"""
Commande permettant de créer un sondage
"""
answers = answers.split(",")
poll = discord.Poll(question, duration=duration, allow_multiselect=multiselect)
for answer in answers:
poll.add_answer(answer)
await ctx.send(poll=poll)
did you install plain 2.6.1 now?
can you print discord.__version__ anywhere in your code
if you try from disord import Poll is that working ?
neither Poll and poll
Im not sure if this can also create a issue
why?
can you try this too please
Poll gibt es bei mir auch nicht bei discord
should not be that since he cant even import poll from discord
works for me
uh Im at 2.5
duh
now its working
can you show us the init.py from the discord package ?
@summer scroll uninstall py-cord and reinstall it
bruh lmfao
they already changed the version, thats basically a reinstall
to check if there is this .poll import *
ok well found the problem
for some reasons, the systemctl that start the bot use a wrong version of python, even if I specified python3:
[Unit]
Description=MonkeyLand - Lancement de main.py au démarrage
After=network.target
[Service]
WorkingDirectory=/srv/Monke-Land
ExecStart=/usr/bin/python3 main.py
StandardOutput=file:/srv/Monke-Land/output.log
StandardError=file:/srv/Monke-Land/output.log
Restart=always
[Install]
WantedBy=multi-user.target
COULD it be like a cache problem?
import os
import dotenv
import discord
from discord.ext import commands
dotenv.load_dotenv()
DISCORD_BOT_TOKEN = os.getenv('DISCORD_BOT_TOKEN')
#intents = discord.Intents.all()
bot = discord.Bot()
@bot.event
async def on_ready():
print(f"{bot.user} is online.")
@bot.command(name="hello", description="testing")
async def hello(ctx: discord.ApplicationContext):
await ctx.respond("hi")
bot.run(DISCORD_BOT_TOKEN)
@sage tendon
I do, but the one I use on my systemctl and the one when I try to start it by hand is technically the same (cf my screen)
which pycord version?
no idea then
2.6.1
and you got the token from here, right?
@willow dune did you fix it?
Is there a way to force discord not to cache autocomplete values?
Do you mean it just caches them if you gave it values but then you dont respond in time for the next call?
Not yet, I've tried different variations of it and still get the same error.
I wanted to respond with an empty list to prevent it from failing, but then send the correct autocomplete for the same input later
can you send the full error here
that doesnt work
I thought you deleted the error, for got it was in #general sorry 
if you take longer than 3 seconds? to respond to autocomplete, you are doing something wrong
If you really want just reply with ["Loading..."]
but you cant like, "follow up" without the user changing inputs
or can you
because for all i know autocomplete is also a type of interaction that can only have one response
I meant:
" " -> "a" -> " "
It caches the first response for the " " input
so refreshing it by typing in it will still show "loading..."
ah
yea you can't prevent that cause its probably done on the client
and typically if you type the same thing, the results dont change
Here is the traceback and error.
discord.errors.HTTPException: 400 Bad Request (error code: 50240): You cannot remove this app's Entry Point command in a bulk update operation. Please include the Entry Point command in your update request or delete it separately.
I am pulling data from 2 separate APIs + a database.
Sadly using choices is not an option
Do you have an activity on your bot?
Nope, nothing, I have the exact code from the guide (except some variable values), just started making the bot. https://guide.pycord.dev/getting-started/creating-your-first-bot
Excited to create your first bot? Once you install Pycord, you can start right
I forgot what your autocomplete is doing but it sound like you are taking the first autocomplete interaction and using its value to call the APIs?
You should cache all possible values on the first autocomplete interaction and filter based on the content from there.
@willow dune
That is exactly what I am doing, however I wanted to display all possibilities once the data is cached
Yeah, got the token from there. The bot goes online, but doesn't recognize any commands.
db -> billing
2 apis -> shared hosting & dedicated machines
can you try make a new application on discord, and do absolutely nothing but copy its token and try using that in your bot?
i feel like the issue is somewhere there
I think you enabled activities on the dev portal and that is breaking it becaue syou dont have a command for activites
yea
You
I have to let it fail it seems. It will retry with the same inputs.
You just click on activities and click ok on the pop up I guess. Did it for the first time right now.
That might actually be something that we need to fix in the lib. Im not sure.
I understand what you are doing about 80%. If you could post your autocomplete code that would be great (you can slim it down by removing the api call info and such)
Thank you both, I didn't realize that it could be the Discord app's activity, I thought you meant if the bot was in an activity. Disabling activities from the Discord app's setting fixed it.
👍 If you are planning on using activities you just have to get that far in the code before enabling in the dev portal
everything private should be behind classes already
This is a typical nitpick of mine but why are you typehinting variables when you could just typehint the return type of the functions
I actually did that about 15 seconds ago so you can see that it returns a list
They are all typehinted
I might just need to micro optimize it until I can get it down to under 3 seconds.
depending on the size of your services you can improve this by not calculating the entire list and then limiting it to 25. Rather stop the for loop once it finds 25 items.
True, thanks.
This might be entirely unfeasible and stupid but since you basically run 3 things, what about threads
I am currently in the process of checking how many API calls I make on average.
Since this bot will be running on the same machine as one of the APIs, I expect a significant performance increase from that.
Re reading your question:
I dont think that it is possible to respond again if a user types /command option:hi really fast before you can load the values for option. And then does not type again. If you cant get it below 3 seconds. I would add "Please keep typing" to the results of the autocomplete or in the option description.
just wondering but about how many options do you typically return
So it turns out the culprit was attrs.define?
This doesnt sound right...
Thats the only thing I changed and I managed to get everything down to 1.21 seconds, with the same data
Do keep in mind i think DBs have caches so that if you are calling the same data a bunch it might get slightly faster as well ¯_(ツ)_/¯
I am using docker compose with mariadb so I doubt that keeps its cache between restarts
Using a simple class without the decorator is infact 0.5s faster.
Using @attrs.define is 0.5s slower than a class with only an __init__ constructor.
This is most likely due to the number of instances it has to create of said class.
can you show that? never seen it before


