#Basic Pycord Help
1 messages · Page 60 of 1
nah sounds good
What's the best way to get the timezone of a user?
you can't natively
Discord does have a way to show time in each user’s timezone, if that happens to be what you want
I would recommend you use a "time to live cache" to limit API calls
aiocache
hey
Helloo
does discord are buggy at this moment? embed attachments (photos) are not generating
Not afaik but keep an eye on https://discordstatus.com/
Welcome to Discord's home for real-time and historical data on system performance.
can you try it by urself?
they said they were messing with the media proxies this week
Oh yeah almost forgot that
nvm that was last week
wouldnt be surpised they still are this week
People in DDevs are reporting this
same here
switzerland airport
I’m using pycord’s cache 👍
https://discordstatus.com/incidents/tfqyj3yyp90g just came up
unfurling lol
If I have guild = bot.get_guild(X), and then kick a member, will the guild var be updated? or do I need to get_guild again to get the updated object
I wanna say, try that
i cant, thats why i ask
and?
was busy talking in #general
i guess
hello, Is possible to use users install applications with voice channels ?
user installed applications can be used inside voice channel's chat. If you are asking if a user installed application can join a voice channel without being in the server, the answer is no
so it only works on DM's and in servers you need to owner to add it?
sorry my english reading isn't the best
thanks you
the last question, I used to join to a voice channel with await ctx.author.voice.channel.connect() but in DM's instead of a Member object I get an User Object so how can I connect without voice attribute?
bots cant connect to group calls afaik
oh, thanks you 😦
Unfortunately not, I need to use the user timezone for a backend query
they'd have to specify it, no built in method for getting that info
i'd personally approach by entering timezone -> convert to UTC -> check with them if it's correct by displaying with <t:> format
heck, make it autocomplete so you can display the current time in each timezone directly on the option
has there been any changes to task loops? my code used to work fine but recently discord.ext.tasks.Loop.next_iteration returns "None"
are you on master or something
oh i guess the loop isnt running but that's weird too
If the loop isn't running then why would it have a next iter 
nvm the loop wasn't running because there was a silent error in another file caused it to stop running
Hi, is there any way for a bot to publish a message to all the servers that are following a channel using Pycord ?
sorry for my english
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 ...
yea
Do you have an example?
I might as well have used it wrong 😅
hardly
using pycord (2.6.1)'s default paginator here, the embed image is just.. not showing up? rest everything is as expected through, and the image url is also correct when i print it onto the console.
here's the relevant part:
my_pages=[]
for item in samples:
emd = Embed(
title=f"[Sample info for [{song}](<{url}>)",
description=""
)
field_name = f"{item['title']} ({item['year']})"
field_value = f"Artist: {item['artist']}\nType: {item['type']}"
print(str(item['img']))
emd.set_image(url=str(item['img']))
emd.add_field(name=field_name, value=field_value, inline=False)
my_pages.append(
Page(
embeds=[emd]
))
paginator = Paginator(pages=my_pages, timeout=None, author_check=False)
Discord had issues yesterday related to media rendering, wonder if it's relted.
I mean I did cross check that on my other bot except that one works with bytesIO instead of direct image link, wonder if that's the difference?
and that one works just fine
when you have an image link, discord needs to process it trough its media proxy, when it's bytesio it's a discord cdn asset directly
Is there a builtin function to create a timestamp from a datetime?
yup
Thanks
If I have a button in an ephemeral message, how can I make it so that the message is deleted when the button is clicked? So what do I have to have in the callback of the button to be able to delete the ephemeral message?
ephemeral messages getting autodeleted after some time
Yes, I know that, but I have buttons in the message for a selection and clicking on the button opens a modal. But I want the message to be deleted when I have the modal open so that the message is gone again after sending the modal.
i'm pretty sure you cant
delete_original_response() works I think
if you still have the interaction that triggered the ephemeral message
i think it'll cause unknown message
Yes right
Unfortunately it does not work...
await interaction.response.send_message("Choose the attribute to edit:", view=AttributeEditView(), ephemeral=True,)
class AttributeEditView(discord.ui.View):
def __init__(self,):
super().__init__(timeout=None)
@discord.ui.button(label="Title", style=discord.ButtonStyle.blurple)
async def button_callback(interaction: discord.Interaction):
message = await interaction.delete_original_response()```
await interaction.response.send_message("Choose the attribute to edit:", view=AttributeEditView(interaction), ephemeral=True,)
class AttributeEditView(discord.ui.View):
def __init__(self, old_interaction):
super().__init__(timeout=None)
self.old_interaction = old_interaction
@discord.ui.button(label="Title", style=discord.ButtonStyle.blurple)
async def button_callback(interaction: discord.Interaction):
message = await self.old_interaction.delete_original_response()
I mean something like this
It might still not work tho. Depend on if delete_original_response is not a response
where is the self and button at your button?
true that
defer with invisible=False and then delete
wait wrong way
invisible=True (which is default in components anyway)
tl;dr just defer before deleting
What do you mean exactly?
The message can be deleted, but how can I send the modal?```py
await interaction.response.defer(ephemeral=True)
await interaction.delete_original_response()
await interaction.followup.send_modal()```
not possible
modal has to be the first response
can't even defer if you want to send a modal
Then the whole thing does not work that I can delete the message with button click and still send the modal or ?
well
either delete the message in your modal callback, or after sending the modal use modal.wait to wait for a submission so you can delete it in the same function
tbh idk maybe send_modal -> instant delete works but i havent tried it
just experiment and come up with something 
When I pass the message ID to the button and try to fetch the message and then delete it. Would that work?
can't fetch an ephemeral
well
that's blatantly wrong, you can just do fetch_original_response
Very simple way how it works:
await self.message.delete()
wtv works
i didn't bother with .message since it used to have some issues
The button is in the view and the view object has the message object that I can delete
hey nelo
if i do guild = bot.get_guild(), then kick a member, and access guild.members, will that be the old or updated list?
Im not really sure if get_x is also updating the cache
no im getting first
It was the updated list for me but idk cache can be weird sometimes
updated
ok
how?
because half of python stuff is just referencing what's in memory
not really
i feel dumb now
wtf
how
i mean that's kinda the point
get_guild returns the guild object from ConnectionState via _get_guild, you kick a member, this triggers on_member_remove which also gets the guild from state and removes the member
of abstraction
it's never at any point made a new reference to guild
man
idk
i thought like if you return something it returns that as a new object
and not as a quasi pointer
usually you need to copy for that
wait
huh
no i give up that makes no sense
so if i return a private list of an object, save it to some var, then that object changes the list, and i access the list where i save it, its also changed?? Wtf
idk man
python is funny
i hate python now
Python is mostly pass-by-reference
thats how most languages work
it doesn't copy the entire object
when im using
view = discord.ui.View.from_message(message).disable_all_items()
await message.edit(embed=final_embed, view=view)
it will remove the view of the message instead of disable it, is it intended ?
uh
?
Can you send a minimum reproductible code
Smth containing the view creation etc...
class TestView(LumabotView):
@discord.ui.button(label="Click Me", style=discord.ButtonStyle.primary)
async def button_click(
self, button: discord.ui.Button, interaction: discord.Interaction
):
view = discord.ui.View.from_message(interaction.message).disable_all_items()
await interaction.response.edit_message(view=view)
and send just a command that send the view
why are you doing it this way like why don't you use self ?
because i dont have access to the view in my real usecase
class TestView(discord.ui.View):
@discord.ui.button(label="Click Me", style=discord.ButtonStyle.primary)
async def button_click(
self, button: discord.ui.Button, interaction: discord.Interaction
):
view = discord.ui.View.from_message(interaction.message) # returns the View
view.disable_all_items() # returns None
await interaction.response.edit_message(view=view)
;)
yeah, i should i think about it, thanks man
np
btw if you can set up python debugger, then you can add breakpoints everywhere and check the value of all your variables at runtime
didnt know that, but since im using pterodacyl i cant really do that
I am addited to the debugger
You should really set up a local dev environment imo
idk if i can do that through pterodacyl, because my debug bot is there with all db etc etc and api etc
pterodactyl uses docker -> you can get docker on your pc, run db etc... in docker on your own computer, connect your locally ran bot to the docker-ran database
Does anyone else have a problem with
ModuleNotFoundError: No module named 'audioop'
when updating/installing Pycord 2.6.1
https://mldchan-loves.femboy-fri.day/9hhj224m.png
One of my project is stuck on 2.5.0 and trying to update it doesn't work
Nvm it happens on 2.5.0 as well
Nvm, suggestion, add audioop-lts into the dependency list
It'll be fixed in 2.7 by using a different implementation altogether, and not audioop
Oh ok
Hi! Does py-cord 2.6.1 support python 3.13?
I get the following error in 3.13 when trying to import it:
File "/Users/_/venvs/_/lib/python3.13/site-packages/discord/player.py", line 29, in <module>
import audioop
ModuleNotFoundError: No module named 'audioop'
.tag audioop
Py-Cord 2.6.1 works with Python 3.13, but you may need to pip install audioop-lts for voice features until Py-Cord 2.7 includes a Python-based audioop implementation.
Fixed it sorry just there
Np
yk for like has_permission is there a place where i can find all of the different options in the docs? I can't find it
I mean, just all the permissions in the role permissions
well i tried manage_server=True and that wasn't found
I think there's a list of them all in the discord docs but I always check the role list
manage guild
well then that lets ppl who don't have the permission to use the command
unless it doesn't work w bridge commands
no
alr
yea thats what i set
you said server
i did that before
then i changed
@bridge.has_permissions(manage_guild=True) # type: ignore let's see
@bridge.bridge_command(
description="ADMIN ONLY: Send a message as the bot to a given channel!"
)
async def say(self, ctx, message: str, channel: discord.TextChannel | None = None):
"""Sends the given message to the specified channel
Args:
ctx (_type_): given by py-cord
message (str): The message to send
channel (discord.TextChannel | None, optional): If not given, sends message in the channel the command was run. Defaults to None.
"""
if channel != None:
await channel.send(message)
return
await ctx.channel.send(message)
@tasks.loop(time=)
what should i insert for "time"?
hm. "time" is underlined in yellow in pycharm. but "datetime" not
you import time from datetime
i.e. datetime.time
also in the docs :)
when i try this:
@tasks.loop(time=datetime.time(6, 30, 0))
it says "unexpected argument" for "30" and "0"
you need to specify what those values are
i have searched in the docs, but haven´t understand it
check the python docs for datetime.time
all options and everything is explained there
I mean it just says it takes datetime.time essentially 
ok. thanks for help
Remember that timezones suck
the default is UTC I believe so it probably won't run on the time you specify if you aren't in UTC
yeah ik. I set it to 1 hour earlier
you can also set the timezone in the time object
now with the docs, i set it to "@tasks.loop(time=datetime.time(hour=6, minute=30, second=0))" but it says "unexpected argument" for hour, minute, second
oh wait. only time. withour datetime, right?
show the error
i haven´t run the programm. it only says "unexpected argument" in pycharm
show
and never trust your IDE if you think it's right
run it first
pycharm also has a few bugs where it won't re analyze a file and tell you old errors
here. but i just write the datetime
does it run
yeah. without the datetime
wdym
with datetime:
TypeError: unbound method datetime.time() needs an argument
then I think you're importing something wrong
it´s running, when you set it to "@tasks.loop(time=time(hour=6, minute=30, second=0))"
show your imports
yea that's the issue
you're basically using datetime.datetime.time() because you import datetime from datetime
just do import datetime
then it'll work
but isn´t it the same, when you import time from datetime or writing datetime.time()?
yea but from imports should be limited
says Google in their official python style guide
because it makes it less clear where stuff comes from if you don't check every import
ah ok
if you just write datetime.time everyone knows what it is, but time could be a third party library too
hm. right
in the end it's preference so do what you feel looks best
ok. thanks for helping me
np
In rtc_region: Value must be one of ('brazil', 'hongkong', 'india', 'japan', 'rotterdam', 'russia', 'singapore', 'south-korea', 'southafrica', 'sydney', 'us-central', 'us-east', 'us-south', 'us-west').
https://docs.pycord.dev/en/stable/api/enums.html#discord.VoiceRegion
the documentation shows dubai, europe, eu_central, frankfurt as regions as well. but appear to be unselectable
prolly not updated to the new ones
weird, those have been around for years from what i can see
ive never heard of dubai myself
i've had it appear in automatic mode
but automatic mode likes to throw my middle-eastern user base into hongkong, which is absolutely un-usable lol
well if the API tells you no then thats a no 
ill submit an issue to remove those from the documentation then lol
voiceregion enum needs a general update to be in line with the results of the List Voice Regions endpoint
(the enum should probably be deprecated in favour of a VoiceRegion class?)
how can here i get the function that got trigger and in which the error occurs (basically the function from the item)
async def on_error(
self,
exception: Exception,
item: discord.ui.Item,
interaction: discord.Interaction,
):
error_message = await format_error(exception, item.callback) # here need to get the real fonction with the __name__
use the traceback module
Im using it but im using the fun name to find the part of the trace ack about that error
I don’t really know how I can get the good func name from it
item.callback?
item.callback.func.name
found it later since callback is a partial func
Can a bot accept a image as command argument?
Here's the slash options example.
And is there a way to accept multiple types? For example Attachments and Links?
no
Rip
well you can create two optional arguments, one for each type
how should i do, im getting int has no attribute status
raise discord.errors.Forbidden(50013, "missing permissions")
When are you getting this ?
im trying to raise the error by myself, but im not doing it correctly
and i would like to know how should i do to raise it correctly
you shouldn't have to raise forbidden yourself
just write your own error class
Ok gonna do it
hi so i have a simple /say bridge command whereby you choose a channel and a message, the bot will say it. Since it's a bridge command, it works fine as a prefixed command, but when used as a slash command, it gets "The application didn't respond", even when it did send the message. Is there a way to either: remove this message, or, send an ephemeral response that's only responded when its a slash command, but not a prefixed command? Thanks
Can you send your command's code ? That should def. be possible tho :)
(he didn't use respond)
Yeah but he said so
1 sec
I think he wants to isinstance ctx bridge.SlashContext
very simple command
@bridge.bridge_command(
description="ADMIN ONLY: Send a message as the bot to a given channel!"
)
@bridge.has_permissions(manage_channels=True)
async def say(self, ctx, message: str, channel: discord.TextChannel | None = None):
"""Sends the given message to the specified channel
Args:
ctx (_type_): given by py-cord
message (str): The message to send
channel (discord.TextChannel | None, optional): If not given, sends message in the channel the command was run. Defaults to None.
"""
if message == None:
await ctx.respond(
embed=discord.Embed(color=0xFF3333, title="You must specify a message!")
)
if channel != None:
await channel.send(message)
return
await ctx.channel.send(message)
you just check ctx.is_app
that a bool?
oh right there's that
yes
alright thanks
(it's just isinstance but it's shorter)
yeah I assumed that
another thing which is kinda unrelated, which discord permission corresponds to the mute_members permission in discord.Permissions?
Because i have the timeout members permission in a server, yet the bot says I don't have the Mute Member(s) permission?
oooh
alr thx
wait but
1 sec
yeah i have the vc mute members permission, so that still shouldn't be an issue
what exactly is the issue
i have a timeout command
is checks for has_permission, and even though i have the permission it says i doesn't
Can you send the code for the command pls ?'
bet 1 sec
btw ctx is bridge.BridgeExtContext | bridge.BridgeApplicationContext
alr thanks
code to the command
uh
so it's raising a checkfailure?
yea
is there a full traceback or do you have some custom handling on that
I handle it here: ```py
@timeout.error
async def on_mute_command_error(self, ctx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.respond(
embed=discord.Embed(
color=0xFF3333, title="You don't have the permissions to run this"
)
)
else:
raise (error)
and that gets called (embed shown)
mmm just in case, MissingPermissions has an additional missing_permissions attribute - 1) could you check that as well, and 2) has_permissions uses channel.permissions_for - could you use this to validate it returns true in that channel
i.e. channel.permissions_for(some_member_object).mute_members
if for some reason you have mute members denied in that channel then it'll fail even if you have it on the guild level, in which case you want has_guild_permissions (though there isn't a dedicated bridge decorator for this so you might have to build a custom check instead)
how i can register different command names (according to language)? like loritta do
.rtfm discord.Option
use the name_localizations kwarg in your command decorator
discord.SlashCommand
but this is not for options name?
Was about to say
in command?
ahh
You have it for option and command
hmmm
you're trying to translate names?
yes, loritta have this
both commands and options support that
allgood
there's also an extension https://github.com/Dorukyum/pycord-i18n which will load names from a json file instead
slashcommand and command is the same thing right?
if you're using discord.Bot yeah
if you are using discord.Bot ye
okay, I'll try 
you can see .tag client
.tag client
discord.Client # just for events
discord.Bot # events + slash/user/msg commands
commands.Bot # above + prefixed commands
bridge.Bot # above + bridge commands (application commands and text commands in one)
How does the dictionary search work? Will it look for the key with the original command name within the language key? And where does it define the language?
name_localizations is just the dictionary for a specific command or option
e.g. py {"pt_BR": "brazilian_command_name"}
if you're looking to use a single file to load everything, consider the extension here
looks like this
{
"en-US": "help",
"fr": "aide"
}
Etc...
aaaaaaaa, then i need to configure a key for the command name, and after this configure a {"pt_BR": "brazilian_command_name"} in the key? if want to keep all commands in one dict?
here's an example of the extension https://github.com/Dorukyum/pycord-i18n/blob/main/sample-german.json
if you want it somewhere else yes
yaml better
like: {"command": {"pt_BR": "brazilian_command_name"}, {"en": "en_command_name"}}, in the argument: dict["command"]

aaaaaaaa
this isn't in the library
doruk built an extension to support it instead
maybe we can make something more convenient for v3 but for now if you want json support that's how you do it
ok, I'll try then, thanks 
v3?
next major version
of pycord?
nothing too exciting so far lol

I thought v3 just going to be a normal update with breaking changes, nothin exciting XD
remember that minor pycord updates are also ripe with breaking changes :3
Hi, my bot is responding twice to prefixed bridge commands. This doesn't occur with slash commands. My bot is a bridge bot. Here's my main.py: ```py
import discord
from discord import Embed
from discord.ext import bridge
from loguru import logger as log
from dotenv import load_dotenv
import os
Load the .env file
load_dotenv()
TOKEN = os.getenv("BOT_TOKEN")
GUILD_ID = os.getenv("GUILD_ID")
intents = discord.Intents.all()
bot = bridge.Bot(command_prefix="$", intents=intents)
@bot.event
async def on_ready():
log.info(f"Bot logged on as {bot.user} successfully!")
@bot.bridge_command(description="Get the bot's ping", guild_ids=[GUILD_ID])
async def ping(ctx):
embed = Embed(
title="Pong! 🏓",
description=f"The bot's ping is {round(bot.latency * 1000)}ms",
colour=0x33EE33,
)
await ctx.respond(embed=embed)
Load all extensions
cog_list = ["utilities", "moderation", "economy"]
for i in cog_list:
bot.load_extension(f"cogs.{i}")
log.debug(f"Loaded extension: cogs.{i} successfully.")
bot.run(TOKEN)
even $ping responds twice. Occurs in all cogs. This is only running instance of bot as no command works when I stop execution.
Thanks
logs: ```
2024-10-28 22:41:20.121 | DEBUG | main:<module>:38 - Loaded extension: cogs.utilities successfully.
2024-10-28 22:41:20.122 | DEBUG | main:<module>:38 - Loaded extension: cogs.moderation successfully.
2024-10-28 22:41:20.417 | DEBUG | main:<module>:38 - Loaded extension: cogs.economy successfully.
2024-10-28 22:41:26.809 | INFO | main:on_ready:20 - Bot logged on as The LeagueMC Helper#7907 successfully!
can you put a print / log in one of the commands and see what happens?
will do in a second
The print statement only prints once, implying its an issue with ctx.respond?
are you sure your bot isn't running twice in some terminal / unkilled process ?
@bot.bridge_command(description="Get the bot's ping", guild_ids=[GUILD_ID])
async def ping(ctx):
log.debug("About to pong!")
embed = Embed(
title="Pong! 🏓",
description=f"The bot's ping is {round(bot.latency * 1000)}ms",
colour=0x33EE33,
)
await ctx.respond(embed=embed)
That sounds very much like that
yep, otherwise when i stopped the current execution, it would stop, wouldn't it
nvm it was it 😭
but then
how does it stop working whaat
thanks
np
bro istg i don't find it when i know thats the first thing to look for but when i post and someone else says it i find it immediately 😭
When my bot is connecting to discord, its instantly getting rate limited. Is this normal? All it does on connect is change its presence once.
@bot.event
async def on_connect():
await bot.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name="the system boot up"))
print(f'{Colors.YELLOW}Connected to Discord! Locking commands and web access until bootup.{Colors.RESET}')
print(f'{Colors.BLUE}Caching started (this may take a few minutes)...{Colors.RESET}')
Yes, it is normal you are getting ratelimites, as you are changing presence in it
You have to set the status and activity kwargs on the constructor
i made it not set its presence and its still happening. makes me thing its something with pycord caching as the bot isnt doing anything else
Do you have any more connection-related events? E.g: on_ready
do you have members intent enabled? If so, it's just fetching all the members for cache which is normal
you, uh, literally put "Caching started (this may take a few minutes)"
Guys, can anyone help me? I'm following the guide but I get this error, not sure if I missed something
class TasksTest(Cog):
def __init__(self, bot: Bot):
self.bot = bot
self.test.start()
@tasks.loop(minutes=1)
async def test(self):
print("test")
@test.before_loop
async def test_2(self):
await self.bot.wait_until_ready()
Error:
Level: ERROR
File: test.py
Function: setup
Message: There is no current event loop in thread 'MainThread'.
Traceback (most recent call last):
File "C:\Users\Usuario\Desktop\Bot de discord\Michi Explorador\cogs\tasks\tests\test.py", line 107, in setup
bot.add_cog(TasksTest(bot=bot))
^^^^^^^^^^^^^^^^^^
File "C:\Users\Usuario\Desktop\Bot de discord\Michi Explorador\cogs\tasks\tests\test.py", line 19, in __init__
self.test.start()
File "C:\Users\Usuario\Desktop\Bot de discord\Michi Explorador\.venv\Lib\site-packages\discord\ext\tasks\__init__.py", line 333, in start
self.loop = asyncio.get_event_loop()
^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Usuario\AppData\Local\Programs\Python\Python312\Lib\asyncio\events.py", line 702, in get_event_loop
raise RuntimeError('There is no current event loop in thread %r.'
RuntimeError: There is no current event loop in thread 'MainThread'.
I think you need to start the task in an async environment
Like on_ready or create a task
# class
def __init__(self, bot):
...
asyncio.create_task(self.async_init())
async def async_init(self):
self.my_task.start()
...
...
can you show use how ur starting ur bot ?
Do you mean my execution code or how I execute it?
i mean ur main.py file
i think you are starting it using another asyncio.run tasks or thread
and it might be the issue
ok a moment
class MichiBot(Bot):
def __init__(self):
self.intent = Intents.default()
self.intent.message_content = True
self.intent.guilds = True
self.intent.members = True
self.intent.messages = True
super().__init__(
command_prefix=prefix_server,
intents=self.intent,
case_insensitive=True,
strip_after_prefix=True,
help_command=None,
)
def execute(self):
try:
logging.info("Loading...")
data = asyncio.run(data_db_cache())
if not data:
logging.error("Failed to recover data")
return
logging.info("Loading extensions...")
self.load_extensions("cogs", recursive=True)
token = dotenv.get_key(dotenv_path=".env", key_to_get="TOKEN")
if not token:
logging.error("Token not found")
return
logging.info("Starting...")
self.run(token)
except Exception as error:
logging.exception(error)
bot = MichiBot()
if __name__ == "__main__":
bot.execute()
If I start the task with a command manually it works
It's because you already used asyncio.run
In your code
Before starting the bot
Oh! I didn't know that detail
Is there another alternative to execute an async function?
1 sec
make execute an async def, then data = await data_db_cache() and use await self.start() and asyncio.run(bot.execute())
and then do asyncio.run(main)
Works! Thank you so much!

np
Hey, is it normal that slash command decorators are not working for a command group ?
Very basic example:
group = discord.SlashCommandGroup("example", "Test group", guild_ids=[...])
@group.command(name="test")
@discord.option(name="Echo", input_type=str, description="Echoes something")
async def echo(ctx, example: str):
await ctx.respond(example)
For my command, I'll have /example test example: and not /example test Echo:
i mean with the code you gave, /example test example: is just how its supposed to work
to match the option onto the parameter name, if the name differs, you need to pass parameter_name="example" to your option decorator
or, well, just name it the same and not completely different things lol
does @discord.Option, and choices, work with Bridge commands? Especially prefixed bridge commands?
also, you can pass name and type positionally
check the docs for bridgeoption
alr thanks
ah so it won't so you have to handle it manually, alright thanks
btw the decorator is lowercase @discord.bridge_option
Yea not of use to me tbh if it doesn't support Choice.
where does it say it doesnt?
it does?
it's literally a subclass of discord.Option
sure
is it possible to send data to a view?
like?
like say an int
just pass it to the constructor?
so like im tryna make an economy bot, and if you press the button, you get that much which is predetermined
and i can just use __init__ if i call super.__init__()?
just pass whatever int you want and then do self.value = value or whatever
you dont have to change anything else
in __init__
Can someone tell me why I can't delete the message even though it is displayed in print?
<Message id=1300816740560801845 channel=<TextChannel id=1176093845214208002 name='text' position=1 nsfw=False category_id=1176093845214218001 news=False> type=<MessageType.reply: 19> author=<Member id=1153983766665545738 name='Test-Bot' discriminator='2710' bot=True nick=None guild=<Guild id=1176093844324444395 name='Test Server' shard_id=0 chunked=False member_count=11>> flags=<MessageFlags value=64>>
async def button_callback(interaction: discord.Interaction):
print(self.message)
await self.message.delete()```
discord.errors.NotFound: 404 Not Found (error code: 10008): Unknown Message
might not have the permission to view the channel
if it's an interaction response u can't
Where do you set self.message ?
Can you send the full view code
is it ephemeral?
It is a view with buttons. And when I click on the button, I want to delete the message.
Yesterday it still worked. Today I always get the error 😄
is the bot admin ?
Yes
well i also have this error a lot in my log, i was thinking it was because of lack of permission but maybe no
await Interaction.delete_original_response() or something like that for Interactions
I am extremely surprised because it worked yesterday and I didn't change anything and have just tested the function again and now it no longer works 😄
I had the same with my command builder
That's very strange 😄
I was using decorater for it and it just stopped working after some time
Now I use _on_pending_application_commands
Okay if I don't set the message with the view and the buttons as ephemeral it works again.
Yesterday it also worked with ephemeral message.
I send the message with
await interaction.followup.send
Do you know why there are problems with ephemeral?
its a weird type of message
It's driving me crazy right now because I can't understand why it worked yesterday and suddenly doesn't today 😄
If the ephemeral message no longer exists it will not be able to delete it. So if you are clicking dismiss message or have just waited a few minutes it will not exist anymore
I send the message with the view. And then click on the button directly in the view within 10 seconds.
await interaction.followup.send(embed=edit_prompt_embed, view=AttributeEditView(self.bot, uuid), ephemeral=True)
class AttributeEditView(discord.ui.View):
def __init__(self, bot: discord.Bot, uuid):
super().__init__(timeout=None)
self.bot = bot
self.uuid = uuid
# Add buttons for each attribute that can be edited
attributes = [
("Title", "title"),
("Starting Price", "starting_price"),
("Description", "description"),
("Minimum Bid Increase", "min_bid_increase"),
("Currency", "currency"),
("Duration", "duration"),
("Quantity", "quantity"),
("Scheduled Start", "scheduled_start"),
("Category", "category"),
("Subcategory", "subcategory"),
("Message", "message"),
]
for label, name in attributes:
button = discord.ui.Button(
label=label, style=discord.ButtonStyle.primary, custom_id=name
)
button.callback = self.create_button_callback(name, label)
self.add_item(button)
def create_button_callback(self, attribute_name, attribute_label):
async def button_callback(interaction: discord.Interaction):
logger.info(self.message)
await self.message.delete()```
the message delete endpoint isn't rated for ephemeral messages, which is why delete_original_response exists https://discord.com/developers/docs/change-log#delete-ephemeral-messages
idk why it worked before/doesn't work now, but regardless you're meant to use that method
Yeah I just have some capital in the name and I want to respect conventions. Also, it’s not in the code I provided, but when I add choices=[…] to the decorator it’s simply not registered thus there is no auto complete. Did I do something wrong ?
show your code how it is right now
I’m on phone, I’ll just show an example
you probably didn't pass parameter name if it still doesn't work
group = discord.SlashCommandGroup("example", "Test group", guild_ids=[...])
a_list = [ "one thing", "something else"]
@group.command(name="test")
@discord.option(name="Echo", input_type=str, description="Echoes something", choices=a_list)
async def echo(ctx, example: str):
await ctx.respond(example)
yea you didn't do what I said
I didn’t have the time to change, like I said, I’m on mobile lol. Didn’t thought it was related
it is, because as it is now, your decorator does nothing
That’s what I guessed
because it can't find a parameter called Echo
So to fix that, I just add something like parameter_name="example"
yes
Ok perfect, will do
The docs got me a little confused on that part lol
Strangely enough, when I do it this way, it works again...
view = AttributeEditView(self.bot, uuid)
interaction = await interaction.followup.send(
embed=edit_prompt_embed,
view=view,
ephemeral=True,
)
view.interaction = interaction
And in the Button Callback:
await self.interaction.delete()
That works because followup is a Webhook, and followup.send returns an appropriate WebhookMessags
It works on its own logic, not by using the regular delete endpoints
heya, i am trying to add a modal to a slash command. the modal pops up and when i enter text and hit submit, it pauses for a few and then i get a Something went wrong. Try again
all it does currently is async def on_submit(self, interaction: discord.Interaction): await interaction.response.send_message("Send message")
im guessing its something simple but i cant figure it out
They dont have a on_submit
its on_callback for py-cord
works now, thank you!
Is it possible to register slash commands only on one server without them being displayed in the DM's?
Because with @commands.guild_only() they are still displayed in the DM's.
My only solution is currently:
@slash_command(name=“”, description=“”, guild_ids=[GUILD_ID])
but this is not the way I want it because I would have to specify every Guild ID. I would like to have it registered on every guild but not displayed in the DM's.
@commands.guild_onlyis for prefixed commandsguild_onlyis deprecated in favor if contexts, see this
you did the right thing
guild_ids=[] is the only way to do it
How can I do it right then?
they still would see it with guild_only
Okay, that's bad. Because I can't do that dynamically for every guild that the bot joins automatically
You want the commands to be visible in all guilds but no dm, right ?
Yes right
try with this then
Have I understood that correctly?
@discord.InteractionContextType.guild
@discord.slash_command(contexts={discord.InteractionContextType.guild})
like this
Ah okay
Works - thank you!
np
and they still gonna be a normal slash command?
yeah ?
But i wanna check smth
Yeah the issue was it used commands.guild_only instead of discord.guild_only but the latter is deprecated anyways soo
Do App Emojis (##2501) make for a breaking chance since
Emojihas been renamed toGuildEmoji.
(...although it turns out I don't use that class directly, so I suppose it doesn't matter for me. But curious in general)
no, since whatever code that used Emoji will still work
Does anyone know why I sometimes have problems when several users use a button at the same time?
I have an embed with a button that is in a view. When a user clicks the button, an ephemeral message with 8 buttons opens. Each button is for a category. If the user then clicks on a category, a paginator opens in an ephemeral message. This should be a separate instance for each user, so that if 4 users click the first button at the same time, each user should have a separate instance of the category selection and then also have a separate instance of the paginator, so that there should be no problems and everyone can browse through their paginator without any problems, right?
But currently I often have the problem that when several users click the first button, the interaction fails. What can I do about this? Or is this unavoidable because it is due to the speed of the Discord API that it cannot process multiple button clicks so quickly?
I'm already working with response.defer in the button callback to give the response to the interaction more time, but that still hasn't made it work properly.
Does anyone have an idea or a solution?
How do I ban someone who’s not in the server?
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 ...
You mean with pycord or just in discord
lol
It tries to load the page initially then before it does it shows that
here
Does anyone have an idea how I can best manage many simultaneous button clicks so that I don't get interaction failures?
Hey is there a way to reload autocomplete for slash commands (without restarting the bot). I've tried reloading the cogs but it doesn't seem to work
why?
hey, how can we get attached medias link?
They should do that without any restart
you dont know what exactly they want tho lol
they sound pretty clear to me?
if you made an autocomplete function, it'll reload whenever you reload the cog
yea but a function doesn't need reloading
its stateless
thats why i asked why to find out why they want to reload a function
...? all functions in a cog update their logic whenever you reload
are we really arguing the semantics of cog reloading
bruh?
the funciton doesnt suddenly change
it still has the same result with the same input unless it uses other variables
we're talking about when someone updates the file
that's the implication whenever someone's trying to "reload" it
are we though? not part of their message
thats why i asked them instead of assuming
also to prevent the x-y problem
and we're back here
ohwell
thanks
I’m using choices= not an autocomplete function
Perhaps that’s issue
choices are bound on discord, so it needs a resync/restart
I tried to reload the cogs tho it’s not changing choices
To be clear, the autocomplete relies on a database
choices
choices are command metadata, so it requires a restart
Full restart ?
Damn
yes
if you're trying to get something from a db, you should be using autocomplete
since that is fully dynamic
Well I guess I’ll switch to that
Here's the slash autocomplete example.
Yup but it’s also a lot slower
no?
On my experience it is
unless your db operations are stupidly slow
autocomplete generally loads within a second
under 3 seconds is required
It's slower because it needs to go discord > bot > discord
instead of discord inherently knowing the choices
Yeah tbf not like I would need it to be instant
i mean, "slow" being "not instant" sure
I’ll switch thanks
allgood
see nelo this is why I ask before making assumptions
they said autocomplete lol
typical case of X Y problem
The difference is pretty subtle lol, I assumed both were the same
Hey I have a dumb question ... can you pass arguments to the function that autocomplete= uses..? For cases where I might want to re-use the AC method but add additional logic
you could just overload it
hwat
or i think adding defaulted kwargs should worK?
To give more context, I have a command with two options. I wanted to have the second one use an argument flag so that my AC function will compare it with the value of the first option.
oh, not that way i think
but you can access other command options
so if first option isnt set, you know you are currently in the first option (98%)
I suppose. But there may be other commands that use this AC without having two of the same options
I was hoping to avoid making super-specific AC methods 🙂
why not move your autocomplete to another function, then your original autocomplete function can pass arguments depending on ctx.options
is it possible to accept multiple types in a slash command option ?
I am trying to accept str and GuildChannel but it does not work :
@option(
name="output_channel",
description="Set up the channel where the flag reaction message will be sent",
required=False,
type=Union[str, GuildChannel],
choices=[
"None"
],
channel_types=[
ChannelType.text,
ChannelType.voice,
ChannelType.stage_voice,
ChannelType.news,
ChannelType.forum
]
)
you can only accept a single type of input
i mean why do you want a string input?
the user can select every channel anyway in the selection popup
yeah but I want something like this :
if it is None, then don't touch the configuration
if it is a channel, then add the channel ID to the DB
if it is a string (like "None"), then remove the channel ID from the DB
just make it optional (as you already did), then its None if not used
yes but what about the deletion ?
wdym?
make a separate command or use a command group
if the users type "remove" in the field, then it just remove the channel from the DB, like as default
..and if they leave it empty, itll be none, and then you can just do that as well
i dont see the need for a specific user input
if it is a NoneType (like None), then I don't touch it, I have few optional arguments on my command, I don't want the user to fill all arguments everytime he changes 1 setting
Yeah I will do that
is it possible to make a command, and a subcommand of it like if it was a group ?
example :
/command (some options)
/command test (some options)
Unfortunately no
would be very cool but the way discord handles commands it probably will never happen
because subcommands are handled as options for the main command..
how to get member count without bots ?
Something like sum(member for member in guild.members if not member.bot)
at the bottom of your server's members tab
thanks mannn
okieee, there is no attribute, i have to do it manually, ty
there is in your bot
guild = await bot.fetch_guild(id, with_counts=True)
count = guild.approximate_member_count
Sorry for the delay. Yes we do cache members but I assumed this wouldn't rate limit us
Can anyone tell me why my messages are either all sent ephemeral or not at all?
If I do this:
await ctx.defer()
await ctx.followup.send(“Hello”, ephemeral=True)
await ctx.followup.send(“Hello 2”)
await ctx.followup.send(“Hello 3”, ephemeral=False)
everything is not sent ephemeral.
If I do that:
await ctx.defer(ephemeral=True)
await ctx.followup.send(“Hello”, ephemeral=True)
await ctx.followup.send(“Hello 2”)
await ctx.followup.send(“Hello 3”, ephemeral=False)
everything is sent ephemeral
With
interaction.response.defer(ephemeral=True)
it works without problems.
uhh
afaik ctx.defer is just a shortcut to interaction.response.defer tho so idk why it acts differently according to you
Might be a bug where ctx sends every follow-up as ephemeral if you use ctx.defer because it somehow saves that it was deferred, even if it shouldn't do that for future follow ups that aren't a response to the original interaction
but that's just blind guesses
Can someone perhaps also test whether this is a bug?
Then you could submit it for a fix?
i mean it literally just calls interaction.response.defer
so it shouldnt behave differently
can't repro
I have tested it again in an extra cog.
Result:
Normal
Normal
Normal
ephemeral
Normal
Normal
class TestCog(commands.Cog):
"""A Cog for testing defer and followup behavior with slash commands."""
def __init__(self, bot):
self.bot = bot
@commands.slash_command(name="test_followup_1")
async def test_followup_1(self, ctx: discord.ApplicationContext):
"""Test command with defer and multiple follow-up messages."""
await ctx.defer()
await ctx.followup.send("Hello", ephemeral=True)
await ctx.followup.send("Hello 2")
await ctx.followup.send("Hello 3", ephemeral=False)
@commands.slash_command(name="test_followup_2")
async def test_followup_2(self, ctx: discord.ApplicationContext):
"""Test command with defer (ephemeral=True) and multiple follow-up messages."""
await ctx.defer(ephemeral=True)
await ctx.followup.send("Hello", ephemeral=True)
await ctx.followup.send("Hello 2")
await ctx.followup.send("Hello 3", ephemeral=False)
# Setup function to add the Cog
def setup(bot):
bot.add_cog(TestCog(bot))```
Aren't those results exactly how it's supposed to work tho
But in my cog both messages are sent ephemerally although the lower message should not be if no error occurs ?
await ctx.defer(ephemeral=True)
result = await HPCGame.play_game(
discord_server_id=ctx.guild.id,
discord_server_name=ctx.guild.name,
discord_user_id=ctx.author.id,
discord_user_name=ctx.author.name,
bet_amount=bet_amount,
chosen_element=element,
)
if not result["success"]:
embed = discord.Embed(
title=result["title"],
description=result["message"],
color=BOTCOLORS.ERROR,
)
await ctx.followup.send(embed=embed, ephemeral=True)
return
embed = discord.Embed(
title=result["title"],
description=result["message"],
color=(
BOTCOLORS.SUCCESS
if result["win_amount"] > bet_amount
else (
BOTCOLORS.ORANGE
if result["win_amount"] == bet_amount
else BOTCOLORS.ERROR
)
),
)
await ctx.followup.send(embed=embed)
Exactly. But for some reason it doesn't work for me in the other cog 😄
And I can't find why.
You defer ephemeral so it should always send it ephemeral right ?
In my test cog, only the message await ctx.followup.send(“Hello”, ephemeral=True)
is sent ephemerally and await ctx.followup.send(“Hello 2”)
normal.
But in my real cog, both messages are sent ephemerally
because your last followup line replies to the deferred interaction
which is forced to be ephemeral
And there is no point to use followup.send
ctx.respond handles followups all on its own
I didn't even know that yet.
So I only need followup.send for interaction.response.defer?
really the only things you ever need are ctx.defer and ctx.respond
all the followup stuff isnt necessary to be used by you
And how do I do it in a button callback?
yea well views are different lol
Okay, that's exactly what I meant 😄
But can I then somehow make it so that I receive the error message as a ephemeral and the other message not ?
dont defer
:>
bit uglier way is to
defer ephemeral
if it worked successfully, respond with something to the ephemeral message, delete it (optional), then respond again (this will not be forced ephemeral)
its kinda ugly and hacky tho
Hmm, I already had that option in mind, but I don't like it 😄
does your play_game stuff really take almost 3 seconds tho?
I'm surprised because it works with my buttons with interaction.response.defer and interaction.followup.send without any problems 😄
yea because views are different
No, not really. But I wanted to take precautions in case many users use the game at the same time and this leads to a longer processing time so that no interaction fails
It would make no sense if a follow-up to an ephemeral isn't one
What am I doing wrong? I get TypeError: 'BridgeOption' object is not callable: ```py
@bridge.bridge_command()
@bridge.BridgeOption(
str,
description="Which fruit to bet on",
choices=[
discord.OptionChoice("banana"),
discord.OptionChoice("apple"),
discord.OptionChoice("orange"),
discord.OptionChoice("mango"),
],
)
async def bet(self, ctx, amount: int, fruit: str) -> None:
it's bridge_option
also you don't need an optionchoice, just pass the values as strings
Is it possible to return a text with autocomplete and if the user has selected something a value in the background as with OptionChoice?
you can use optionchoices in autocomplete yes
like this:
matching_cards = [OptionChoice(name=card["card_name"], value=str(card["id"]))for card in cards]
return matching_cards
?
yea
Okay nice. Thanks 🙂
I forgot what was the line that was needed to be added so both slash commands and normal commands worked together?
You are looking for the bridge extension, I am not super familiar with it
i remember it being just a simple line that was needed somewhere and i dont remember it having bridge in it
maybe they changed it up
oh wait i dont mean that one command serving as both slash and normal
I meant that i've got 2 distinct commands in my code
one slash one normal
Oh, you need to use discord.ext.commands.Bot instead of discord.Bot
on the non slash commands?
For your bot instance
got it, thanks
Curious, whats the downside of using discord.ext.commands.Bot instead of discord.Bot?
id assume if it was the same they'd just let us use both types of commands by default
.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)
I wonder how much @bot.command aliasing to @bot.slash_command in discord.Bot is a good idea, as it means that whenever you change your instance to commands.Bot it breaks stuff
You will need to use @discord.ext.commands.command for prefix commands and @discord.commands.slash_command for slash commands
there’s also like discord.ext.commands.slash_command
am i the only one who feels like the library structure could use an overhaul?
TBH, there is little reason to use prefix commands anymore. Most people should only be using slash commands anyways
i legit have no clue why it's even ext
like its not an extension really
its about as main of a feature as you can get
I want the exts to be installed seperatly
it’s not native to the discord api
but doesnt it contain about everything command related?
before commands existed yeah
hm
but yea i still think this has to happen at some point
like some stuff feels duplicated, some feels random, there are tons of aliases
I do think there are way to many aliases
we already shot down the overhaul that was the old v3
Like dont get me wrong i do like top-level aliases like discord.option, because its not really ambiguous
but like
option / Option has like 3 more aliases at different levels
why?
you can use discord.user.User, too
they aren't exactly aliases
almost everything is made accessible at the root discord level, beyond that if you do something like discord.commands.Option or discord.user.User that's just regular pathing
it’s not specific to option
i mean thats just the full path really no?
I also still wonder, with stuff like the Option typehint
With almost every type checker disliking it, is it even supposed to work? Like it does feel wrong to make a function call that then returns a type essentially
Option typehint is explicitly coded in
yea in pycord, yes
but generally, i've never seen typehints being a function call
so it feels like it's discouraged?
or ive just not seen stuff where its used
this should be moved to #general or #discussion
yes lets go #general
speed
Hi! I have this code ```py
self.disable_all_items()
await interaction.response.edit_message(view=self)
It throws: ```
discord.errors.InteractionResponded: This interaction has already been responded to before
I don't know what I'm doing, this code was taken from the Guide, but the page for this is incorrectly formatted.
Learn all about implementing buttons in your Discord Bot using Pycord.
did you defer
or make any response before edit_message
I made a response. Do I write this before making any response?
use interaction.edit instead
alr
Also, do aliases work with slash commands? Or do you have to make a slash command for each
there isn't a good reason to have aliases for slash commands since typing / pulls everything up
and it matches descriptions too
strange, mine works
but i respond with the same view, updating it before
shouldnt this raise a badargument error ?
channel: discord.TextChannel | discord.VoiceChannel = None,
that is a badargument error
well, either BadFlagArgument or BadLiteralArgument or BadUnionArgument (the latter 2 are UserInputError)
its neither of those commands.BadArgument, commands.MissingRequiredArgument
why don't you check the type then 
it often give me error.class command invoke error as class, im gonna check for prefix it usually give the good one
if you got CommandInvokeError then you have to access error.original
yep its a BadUnionArgument
there you go
is there always a error.original in case of an command invoke error ?
if isinstance(error, commands.CommandInvokeError) or isinstance(
error, discord.ApplicationCommandInvokeError
):
error = error.original
am i using a wrong path ?
or it directly from command or discord
uhh those would be correct
thanks
also python related question but
is there a way to do isitance of multiple class
perfect !
though, ApplicationCommandInvokeError will only raise in on_application_command_error and vice versa
the easiest hack with error.original is to just re-raise the same handler
so just raise error.original ?
i mean i did put at the beginning of my on_application_command_error the isistance so i think its the same
mmmm that might work? but perhaps i phrased wrong, i'd just do await on_command_error(ctx, error.original) or so
I just do if hasattr original error = error.original
i havent ran this code in so long and i get this error 
did sync_commands() change or something?
the rest of the commands run fine, it just wont let me sync any of the commands
you have command which have the same name
i really dont
that not what its saying
check again
its ur 4th command
how many commands your bot has?
you really do
if i use thread.members, the data is not accurate, what should i do?
ok, i know how to do, tq
Is it possible to get a member's username color (the color of the highest colored role) ?
I can't read message.author.color
wont work with user apps, keep in mind
yup exactly
I'm confused about these intents, if I leave them as default, will my program try to respond to several events that I haven't even programmed a function for?
No, but there is not much reason to turn on intents that you do not need as it will lead to increased amounts of data discord needs to send you. And in some cases it will increase your RAM usage due to the bot using cache
generally default intents are fine, that's why they're default
on my soul i do not
ok i found the problem
the problem was that i had 2 @bot.slash_command
so you did
How can I completely avoid this 403 error?
[1;30;40m|[1;37;40m 2024-11-02 01:53:49【- test -】: POST https://discord.com/api/v10/channels/1301967446969946125/messages with {"content":"abcdefgh"} has returned 403[0m
this is my code:
dm = await self.member.create_dm()
if dm and dm.permissions_for(dm.me).send_messages and self.member.mutual_guilds != 0 and not self.member.bot: dm.send........
eh...
you dont have to create a DM btw, you can just use member.send()
and catch discord.Forbidden if the user disabled DMs
or no mutual servers
or blocked the bot
That's a long condition lol
And you dont need to check for permissions on a dm channel lol
You have all the text related ones allowed
try:
member.send(...)
except discord.Forbidden:
...
i think they wanted to use permissions to see if you can dm the user, but that doesn't work
you basically have to try/except dms
At what server count should a public verified bot be converted to an AutoShardedBot?
Discord sends you a message when needed
generally after 1000 or so if you notice your bot dropping in performance you should consider it
it's required at 2500
Is there any way to detect it in advance?
cloudflare will return 403 error
i want the log to be clean
the point of try-except here is to catch the error because there's too many conditions in which you can't dm a user, and it's not possible to validate without using send
alright thanks
hey there
can anyone explain me what is conditional statements?
and how to use it without getting error
do you mean if statements ?
yep
can you give some (code) example of what you want to do
are you new to python ?
yes
feel free to send your code here, we can help, also if you are new to python you have a ton of resources here
.learnpython
Resources For Learning Python
- Official Beginner's Guide
- Shortcut to guide for people new to programming and people with experience programming
- Official Tutorial
Other Resources To Learn Python
- Automate The Boring Stuff for complete beginners to programming
- Learn X In Y Minutes for people with experience programming
- Swaroopch is a useful book
- Code Abbey has practice for beginners
- W3Schools is a good resource for general use
okay
If you don't know what an if statement is, Pycord is too much to head into python with
Please learn programming at its base first
they don’t seem to care about pycord
This server is for py-cord a library for creating discord bots with python. If you are interested in that feel free to stay :)
If you are just looking for a general python hep community discord.gg/python is a better place

So I have a bit of a dumb question. I seem to remember that some parts of the UI classes auto-magically had access to the view that called it. But I can't find any code to support that.
Am I misremembering that with something else? If I want a Modal to get access to the parent View that called it, I'd have to still explicitly pass in the view instance?
i think yes, you create your view class to this
seeing that modals aren't directly related to views, that wouldn't be built in
when it comes to actual view items (Button, Select) they have a view attribute
modal.view?
Ah, thanks!
Back to Modals, what's the best way to no-op if they submit something and nothing needs to happen (e.g. the text input has a value already and they just submit)?
I lazily though return True would work here, but I guess there's no response to close out the interaction
defer
for any UI component, a plain defer is fine because it defaults to invisible
Hm, the callback passes interaction, there's no interaction.defer(). What should I be calling?
have you never deferred?
interaction.response.defer()?
yeah we were meant to implement the shorthand to match ctx.defer but it slipped past me
Ahhhh. response.defer, thanks
.rtfm delete
discord.Template.delete
discord.on_invite_delete
discord.on_thread_delete
discord.on_message_delete
discord.ScheduledEvent.delete
discord.on_raw_thread_delete
discord.RawThreadDeleteEvent
discord.RawThreadDeleteEvent.guild_id
discord.RawThreadDeleteEvent.parent_id
discord.RawThreadDeleteEvent.thread
discord.RawThreadDeleteEvent.thread_id
discord.RawThreadDeleteEvent.thread_type
discord.on_raw_message_delete
discord.RawMessageDeleteEvent
discord.RawMessageDeleteEvent.cached_message
discord.RawMessageDeleteEvent.channel_id
discord.RawMessageDeleteEvent.guild_id
discord.RawMessageDeleteEvent.message_id
discord.on_bulk_message_delete
discord.Role.delete
.rtfm message_delete
meh. What's the thing where you can tell a channel to delete messages beyond a certain point
purge?
Just to sanity check, I need to purge all messages after a selected message. I'm creating a Message command for that. Looks like after takes a date (or a snowflake time.. is that the same as ID or no? message.id is suggesting an error)
it should be able to take an ID
I guess because message.id is an int, and it's looking for SnowflakeTime specifically
does the code execute correctly?
SnowflakeTime is literally the union of Snowflake and datetime
Oh. Application Command raised an exception: AttributeError: 'int' object has no attribute 'id'
Guess I can just pass in the message itself
From the screenshot, I initially passed in message.id. If I just pass message (which is received from the message_command), then it's fine. Just a little docs weirdness.
It sounds like you got it working but this might be of use at somepoint
https://docs.pycord.dev/en/stable/api/utils.html#discord.utils.snowflake_time
right, abc.Snowflake is a protocol for classes that have the ID attribute, meaning the code was expecting the object
My bot went haywire and started spamming reminder messages, did about 4-5000 til I was able to kill it. Was trying to quickly get something to clear them out (which I have now done). Thanks again
How can i make a command required?
What do you mean ? Make a parameter required ?
Ye
slash command ?
Yes
Can you send the code you have rn and what option you want to be required ?
options are required by default. you dont have to do anything extra
yeah
They are not options, they are just in the def
I don't remember how to use the option
They are already required
pycord automatically makes those into options
alr
did you even test it lol
No
Didn't know that happens without the option @
discord.ext.tasks.Loop
discord.ext.tasks.Loop.add_exception_type
discord.ext.tasks.Loop.after_loop
discord.ext.tasks.Loop.before_loop
discord.ext.tasks.Loop.cancel
discord.ext.tasks.Loop.change_interval
discord.ext.tasks.Loop.clear_exception_types
discord.ext.tasks.Loop.current_loop
discord.ext.tasks.Loop.error
discord.ext.tasks.Loop.failed
discord.ext.tasks.Loop.get_task
discord.ext.tasks.Loop.hours
discord.ext.tasks.Loop.is_being_cancelled
discord.ext.tasks.Loop.is_running
discord.ext.tasks.Loop.minutes
discord.ext.tasks.Loop.next_iteration
discord.ext.tasks.Loop.remove_exception_type
discord.ext.tasks.Loop.restart
discord.ext.tasks.Loop.seconds
discord.ext.tasks.Loop.start
https://docs.pycord.dev/en/stable/ext/tasks/index.html#discord.ext.tasks.loop
And pass a datetime.time to the time keyword argument
One of the most common operations when making a bot is having a loop run in the background at a specified interval. This pattern is very common but has a lot of things you need to look out for: How...
Hello, to have a user's invitations, do you have to save them in a database (when the inviting member joins) or is there a way to have it with only {user.invites} for example?
the former
Oh okay!
Does pycord support linked roles? (App Metadata for Linked Roles)
It works with oauth - and oauth is outside of the scope of pycord. Also, you only need to register the metadata once with your bot so you can do it easily with a simple script / software like insomnia. I recently pred feature to know whether a role is a linked role, etc...
thank you
actually, I think it publishing the roles metadata might be in scope
as it's rest api
I'll open an issue
I asked the question for this 😂
Wait it's already there actually
https://docs.pycord.dev/en/stable/api/clients.html#discord.Bot.update_role_connection_metadata_records
oh
Hi, I was wondering if the documentation for the event on_guild_stickers_update was wrong because it claims it uses the type Sticker | None but in reality it's a tuple
Might just be me or my IDE but I was wondering this
Nvm it's just my IDE tripping
I don't know what's happening but the official docs say Sequence, it returns a tuple and my Pycharm thinks it's a Sticker | None?
whatever this is, its not pycord
events cant even be typed "from pycord" in that way because you write your own listeners for them
so you probably typed it that yourself
when i kill my bot script and the re run it with changes, none of the existing buttons on messages work anymore. the buttons' views have timeout=None set and have custom_ids set. is there a way for them to still work after restarting?
you need to do bot.add_view(YourView()) on startup
even if the view is per-message? it has things like a saved message id and originating user id
makes sense, ill play around with that. thx
wait but
if its only the data of the message the view is attached to, you can just do view.message
but i assume youre saving some other stuff too
@latent hare
something that might need checkout is command.ext_variant.aliases return None even if the prefix command have some alias
i have this issue but idk if because i change my implementation of bridge
Can you try repro with stock pycord ?
@obtuse star
https://docs.pycord.dev/en/stable/api/events.html#discord.on_thread_create
And then you check if the parent (or parent_id) is for the correct channel.
And applied_tags will get you the tags
Stock pycord is basic pycord ?
The thing that might change is that I changed the alias after the command creation with command.aliases = …
So at the point the bridge command might be already created and not edit
they mean test it without any of your modifications
is it a good idea to store module files in txt format in the database? so that i can update the file in the database and reimport the module without having to restart the bot
why just not reload the file ?
the file is hosted on the server lol what do you mean by reload the file
I mean why store the module in a database and not just have it inside a regular gile
if i update the file in my pc i need to reupload it
You can use git
Then u update ur file using the git
And you reaload the extension
No restart needed
If you are editing the file directly on the host
You can just reload every extension
And will not need any got
data.components.0.components.0.options would imply an issue with a dropdown, right? (even if it's not the first child)
Oh nvm, I see the issue now. Shit, I have more than 25 entries.
Does anyone do anything fancy with dropdowns with datasets of more than 25 options? Maybe having one of the options be a selection that changes the dropdown to a new dataset
What I usually see is just multiple dropdowns
which are labelled A-F, G-O, P-Z for example
yeah I do smth similar
hm. maybe. I guess it would be equally complex (for my application) as making a paginator for the dropdown.
or, which is a bit more weird to use, you make a dropdown that selects a range (as before, e.g. A-F) and then you edit the dropdown to show that selection, or add another one below that always shows the currently selected range
That's not wierd
(and a really good application for my pycord-reactive-views thing)
how should i use that ?
)
bot.load_extensions("Slashs", recursive=True)
print(bot.extensions)
because even if i have 2 files inside the Slashs, it only load 1
the recursive doesnt raise an error or return a error either with store = True when there is an error inside a file
default contexts should be a set @fresh sierra
{discord.InteractionContextType.guild}
i change that error
see it after, it was a stupid thing
except if im loading it directly
