#discord-bots
1 messages · Page 418 of 1
what is the server's name
As I said, you can use any language for anything
what is this channel name
discord bots
connect the dots
you seems to be obsessed with hacking
yea hacking is interesting
If you mean discord bots:
https://fallendeity.github.io/discord.py-masterclass/creating-a-bot/
A hands-on guide to Discord.py
But you need to know some fundamental python stuff
u sure it's not virus
Like classes and stuff
Use it if you want idc
idk about classes, what is it used for
At it's core it's meant to group data into a single namespace
classes are blueprints
But it can go deeper than that
!res
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
alr i will learn it
If you are truly interested in hacking you should check out cybersecurity capture the flags. They teach you the basic skills and allow you to practice them in a safe and legal manner.
Hack the box and PicoCTF are good starting points
SOMEONE HAVE A CODE BOT TREE FOR WHITELIST AND UNWHITELIST DISCORD BOT
CAPS LOCK AAAAA
How can i put a title in a layoutview (components v2)
How do you mean title? Afaik you can use markdown in text displays
Want to inject some flavor into your everyday text chat? You're in luck! Discord uses Markdown, a simple plain text formatting system that'll help you make your sentences stand out. Here's how to d...
SOMEONE HAVE A CODE BOT TREE FOR WHITELIST AND UNWHITELIST DISCORD BOT
SOMEONE HAVE A CODE BOT TREE FOR WHITELIST AND UNWHITELIST DISCORD BOT
no need to shout thrice
unwhitelist 💀
what even is a "whitelist and blacklist discord bot" bot
@idle current Please change your username, stop shouting and stop spamming.
What the purpose of my spamming if I can just do it to my self
👍?
That's a very good question isn't it
Discord bot written in Assembly 
Regardless, some languages have a bold advantage in certain things over other languages
Honestly I have yet to see a reason to code a bot in anything else except python
Python works with other stuff so If I need custom html or lua they do have modules that work eith them
So true
Hot takes in the python community server
how to install python
If you're on Windows then go to the website, pick the version you want, download and run the install executable, check the little icon at the bottom left that says add interpreter to path then proceed with installation like any normal piece of software.
Can also install it from the windows store
'b..b-but typescript performance is better' 
The funniest thing to me is people who use Java for Discord bots
As if life isn't hard enough already
Only real coders use binary
it is almost always recommended to install from python.org
The microsoft store version seems to cause a lot of issues
Even with the new installer?
Do it yourself brada
The new PyManager should work too.
Dude got a cdn for screenshots 
real coders first developer their own computer and developer binary and then make bots
Oh this guy's out? Good cuz he sent a weird dm
Yup
Anyone know of an easier way of writing buttons and their functions than just
@discord.ui.button(blah blah)
Async def function_name()``` for each and every button?
I plan on making a ticket system with like 40+ buttons and it's gonna be a pain to write it all out manually
What ticket system requires 40+ buttons...? Doesn't sound like a great design choice
If it's split across different commands/"pages" then that's fine, but you obviously need to define the callback function of the button
40 different buttons sounds like bad UX
If the buttons do different things, how do you envision not writing it out? Python can't magically infer what you want them to do
You can subclass the Button for a callback
class MyButton(ui.Button):
async def callback(self, interaction: Interaction) -> Any:
print(f"{interaction.user} clicked button with label: {self.label} and custom_id: {self.custom_id}")
...
btn = MyButton(label=..., ...)
<view>.add_item(btn)
it's gonna have a staff tools, cancel closure buttons, add users to ticket, remove users, force closures, timed closures, and more when I think of them
I made it with a block programming language and im trying to move it to python
Got this much done but its still only like 20% of the system
I'll check out subclasses thanks
and more when I think of them
Then why would you wanna make 40 buttons
-# You cant btw
In a single message, 40 aint possible
not in a single message
obviously it can only handle 25
its an advanced ticket system that can automate every need a user wants
Then why are you want to make 40 buttons inside a single view class
Then you just create 40 buttons decorators if they have different callbacks
Use a helper method if they share some logic
^
I was only asking if there was a simpler way cuz doing it takes a minute to write a button and its function
I want a quicker way to do this quickest way of doing different thing
It doesnt take a minute to write 2 bare bone lines of code
if you're gonna keep insulting me for asking questions then im just gonna block you
im here to learn not be berated
Like soheab said, you can subclass discord.ui.Button and instantiate how many ever you want of them (and add it to the view) if those buttons share similar functionalities
Sounds good I'll check it out thanks
33* (cv2)
For the hours one, just use a select menu
Yeah I thought of changing a few for select menus
good suggestion i'll look into it
I gotta learn unix and task.loops first
so I can actually make an autoclosure
unix? as in the timestamps?
yeah I know how they work and the basic just gotta learn to effectively implement them with the command
One problem with tasks is that you lose them on shutdown
Unless you don't experience unexpected shutdowns as much as I do
It should be simple 
hmm
not a big deal with a ticket system honestly, if need be it can be done manually
However saving to a DB shouldn't be very good either, Idk
I should also learn how to save buttons but thats a task for another day
Because you'd have to loop over the entries to see "if it's time yet"
You don't have to manually loop over all the entries, that's what the WHERE clause is for
Save them? Since you say that, I assume you use normal callbacks, no dynamic items or persistent views, do you
No i dont
All just basic stuff
Then you might wanna start using those
true I looked at how to do it but it was bit out of my zone since I didnt know JSONs at the time
discord.py:
Dynamic item is simple, you need to pass a template regex of how the custom id of that item should be structured
then you define from_custom_id which is a class method for making an instance from the custom id
and ofc, callback
Learn all about implementing Select Menus or Dropdowns in your Discord Bot with Pycord.
Check the docs if you're interested
I used this as a guide
oh u use pycord?
im using discord.py not pycord
Embeds don't support that, it's components V2
There's code exmaples to that but I'm not an expert with the docs
So many of these things just natively exist in threads already
im using text channels since im old school
That's not a good decision
threads arent private unless you make a modmail system and i hate those
they're ugly
They're private if you tell them to be what
Yeah.. just like text channels can be
Using normal channels is a mess, but go ahead
I use threads for suggestions and bugs and automate those
I havent quite learned how to manage things from the bots DMs
It doesn't have to be from the bot dm
as far as I've seen it's not possible to change an individual threads overwrites
Unless im missing something
Hmm yea I really don't see much here, but Idk how threads work to an extent
I did it a bit with discord APIs with block programming and the only way to achieve private threads was through a modmail system
from my personal expierence
Well I know for a fact it doesn't work that way lul
.
maybe fetch members, I havent seen that before
Fetch members fetches members..
I have nothing more to suggest than checking your library's docs
yeah creating a completely private forum channel and using fetch members to grab and pull them into the thread
I did try using just a private forum with a button from another channel but the issue there was people could see past tickets
and couldnt have that so I scraped that idea
There's all kinds of ways to go around problems like this, you just need to find one
maybe but I know the text channel way rigjt now and have a system built around it so until I find something else I'll just stick withj it
im gonna look into persistant buttons and stuff
🫡
Fair
I should figure out if I'm using pycord cuz when I started I sorta just installed everything and haven't changed much
I don't think I am
wait you've made a bot but you don't know what library you're using for it?
He's most definitely using discord.py
But man just go to the module file and see
Nah I learned by just looking up stackoverflow code and seeing if it worked if not moved on to a different article until I found one that worked and memorized that code
you should never memorize code snippets
import discord
click on discord
that's a really bad way of "learning", if even
I mean I learned some basics
but I did skip a lot
wish there was a roadmap to help
i did make small roadmap long ago https://paste.pythondiscord.com/YHOA
doesn't cover every single topic but it touches the main concepts of core python
I'll check it out after I wake up thanks
if you wanna use it, save it in your system, that link will expire in a few days
Oof
How can i put a actionrow button to the right side in a components v2 layoutview?
It's not action row, a button on the side is accessory.
section = ui.Section(
TextDisplay(...),
...,
accessory=ui.Button(...)
)
layoutview.add_item(section)```
`HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In data.components.0.components.0.accessory: Value of field "type" must be one of (2, 11).
In data.components.0.components.2.accessory: Value of field "type" must be one of (2, 11).
In data.components.0.components.4.accessory: Value of field "type" must be one of (2, 11).```
code?
same problem....
This is my code:
buttons1 = PanaszkonyvButtonUBKERELEM(self)
buttons2 = PanaszkonyvButtonSTAFFREP(self)
buttons3 = PanaszkonyvButtonEGYEB(self)
section1 = discord.ui.Section(ubreqtext, accessory=buttons1)
section2 = discord.ui.Section(staffreptext, accessory=buttons2)
section3 = discord.ui.Section(etcreptext, accessory=buttons3)
container = discord.ui.Container(
section1,
discord.ui.Separator(),
section2,
discord.ui.Separator(),
section3,
accent_color=0x0E2F86
)
self.add_item(container)
what is
buttons1 = PanaszkonyvButtonUBKERELEM(self)
buttons2 = PanaszkonyvButtonSTAFFREP(self)
buttons3 = PanaszkonyvButtonEGYEB(self)
class PanaszkonyvButtonUBKERELEM(discord.ui.ActionRow):
def __init__(self, view: 'PKReportView') -> None:
self.__view = view
super().__init__()
@discord.ui.button(label="Unban Kérése", style = discord.ButtonStyle.blurple, custom_id="unbankeres")
async def unbanrequest_button(self, interaction: discord.Interaction, button: discord.ui.Button):
``` and its just code below
^
you're not supposed to add an action row
Add either a button only or Thumbnail
@mild kiln Your message was removed for violating server rules 6 and 9
Uhhh
import discord as pycord
What if discord.py had an unknown_interaction event to handle shit like this? It's not like nobody uses regular callbacks
huh
If you use discord.ui.Button(...).callback, and bot restarts, you will no longer be able to control that button's response, not even to tell the user properly that it expired. I just think that the "this interaction failed" default response is so ugly
Welp you're right 
Hmm but with persistent views, the bot will keep storing that view, which it wouldn't if such an event existed
I think it'd just be a little bit more optimized, maybe I'm wrong.
Sometimes it's worth spending a tiny bit of memory for a useful layer of abstraction
If you want to be "optimized" you shouldn't be using python in the first place

Lemme introduce you to
using the same instance 
Or even better..
DynamicItem 
Knew I'd get hit with the dynamic item man
They're so good
Well in that case I'd have to manage the cache myself, not that it's such a disaster, but still
Orrrr I can pass all info to the custom id
You don't want persistentsy
(edge case: people can check the message data and cheat in games, but idrc)
Knowing whether a component was handled by a view would be nice yes
But it was denied hard https://discord.com/channels/336642139381301249/1296458798256488459
Oh God is it really that hacky -_-
😭 🙏🏻
They say right things but bruh atp remove regular callbacks as they're objectively bad for UX
If you really don't want to get in the way of views and not hardcode stuff, yes
Pycord is planning something like that 🙏
Good for them
I don't get the idea of having a feature where there's a certain problem that's unfixable, with the only "fix" being using a different feature
The advantage of the callback is that the library handles the interaction responses for me, inside a class, potentially - what I mean to say is that this is comfortable to use, quite more than dynamic items for some use cases
But then as I said it becomes useless if you don't make it persistent
Ya
Mhm, and I'm pretty convinced there'd even be more ways to implement this, but yeah
Probably but that's the simplest and it doesn't break any design choices
I was thinking initially about making a Git issue but now you showed me they dont want this
You could still try lol
That was all a year ago
Just pretend like not knowing about the above :)
Like I was thinking about checking if the interaction's message's view is still active
And that binds this concept to components rather than to interaction in general
views are confusing sometimes :blobpain:
Dpy doesn't store views per message though
It's per message id
Wait
Sorry for reply ping
there's a message_id kwarg for add_view
Is it always per message
Very primitive since I have no real way of checking if it was created internally
!d discord.Client.add_view
add_view(view, *, message_id=None)```
Registers a [`View`](https://discordpy.readthedocs.io/en/stable/interactions/api.html#discord.ui.View) for persistent listening.
This method should be used for when a view is comprised of components that last longer than the lifecycle of the program.
New in version 2.0.
By default they are attached to message ids
time to look at the srouce code
I wonder if dpy could expose that somehow
Message.view would be bad and misleading
hmmm
class BaseView:
...
def __init__(self, *, timeout: Optional[float] = 180.0, id: Optional[str] = None) -> None:
...
self.id: str = id or os.urandom(16).hex()
self.is_id_overridden: bool = id is not None```
One thing I thought of
Unless making this bound to view.id is not good
Then ig you could have a method that checks the view store to see if that view is there and whether it's managed by the library (condition: id is set)
but how would you get the view in the first place
You mean how to find the view corresponding to the interaction?
view = bot._connection._view_store._synced_message_views.get(interaction.message.id)
like not using private methods
Should the library not use its own internal things 🤔
I just think it can be "more accurate" if you do that, rather than checking if an error didn't occur
oh i missed that
but
views and view id is a dpy thing
you don't get that from the interaction afaik
unless you mean the method should take a message_id > search for view > check if id is set > return True : else False
That's if you choose to not use private methods
what would the flow for the library be?
class Interaction:
...
@property
def item_callback_available(self) -> bool:
if not self.type == InteractionType.component:
raise TypeError
if not self.message:
raise AttributeError
view = self._state._connection._view_store._synced_message_views.get(self.message.id)
return True if view and view.is_id_overriden else False
I'm not too familiar with the source code, but this is just a concept I had in mind
bot instance won't be used like that tho
Maybe you'd pass the instance
oh I was thinking something on the bot
so you could get it even without an interaction
what about interaction.client
Changed to use self.client 
i thought
The condition at the end was wrong, fixed it
self._state directly can be used no?
correct
What is the concrete use case for this?
I meant like a method on discord.Client/commands.Bot to get the view..
no
handle components without callback / persistent views
Personally I thought, for example:
A game, that you want to time out eventually, but you want to be able to tell the user indefinitely that it expired, and you don't want to make it persistent
The point is not making it persistent
Why not just edit the message to tell them that rather than making them interact
Just sounds annoying
Unexpected restarts is the only thing that I thought of
For me that'd be great
Maybe I'm the only one who may find this useful at all 
I mean if your bot goes down unexpectedly you have bigger issues
Or not unexpectedly. Restarts can be a normal thing
And even then if you wanted to be paranoid there's dynamic items
Why is this the a priori point
Like yes when you rule out the mechanism made to do the thing for no reason, there is no alternative
Which will force you to either pass data in the custom id, which I find less convenient (users can check message data and cheat if it's a game, for example, but that's an edge case), or manage cache yourself
How are you proposing you avoid managing cache on a restart
Maybe I'm wrong but to me it sounds like bad practice, both for whether it's a large bot (you will store many many view instances supposedly), and for the fact you only persist it for sending a basic message
What is the theoretical feature that magically intuits what data you need for you
Making persistent views isn't a bad practice
Sorry, I meant that in a view class, with callbacks, you can easily access view attributes. You kinda lose that ability with dynamic items
Because dynamic items presumes the data is baked into the custom id
That's the whole point
This could even just be an id you query for everything else
Indeed
I mean I actually know about someone who chose to use dicts because they didn't want certain things to be exposed in the custom id, but as I said that's probably considered an edge case
That's all I got to say
A lot of people assume everything is sensitive when most things aren't
I can give you id's all day and there's nothing you can do with them
Trivia with the correct answer being in the custom id; I get message data; I cheat
But yeah I don't think that should be the reason for adding a new feature
So I agree that this matters less
That case is just poor design
Not a case against the paradigm
If those things needed to persist between restarts, the secret data by definition needs to be put into a db
Well not if your best choice would be to use dynamic items. I don't see how it'd be a design fault of the user.
.
But that isn't your best choice
Because you aren't supposed to use dynamic items to embed secret data
Right that's where I'd want to use something non persistent, instead of implementing DB usage where it's not crucial at all if I use memory
And I'd want to be able to tell the user, that this non persistent thing, has expired

And now we're back to whether using persistent views for that is bad practice or not
Why are you asking a user to interact with something you don't want them interacting with
Just remove it and tell them that rather than making them do an unnecessary step
On restart you lose the ability to do that. Restarts are definitely not edge cases
If you care about restarts then make it persistent. That's what persistent means
You can't just say "I don't want to use the tool made to do the thing I want to do, so make another tool"
The library's assumed default is that most views are temporary, restarts are rare, and even if they do happen and one view goes bad it's not worth warping the library to accommodate it people can live
something like
class Client:
...
def get_view_from_message(self, message: Snowflake, /) -> Optional[BaseView]:
"""Retrieves a stored view sent with a message.
.. warning::
This is not the same as :meth:`discord.BaseView.from_message`. This method
only retrieves views that have been sent in the current session or have been
registered via :meth:`Client.add_view` using the ``message_id`` parameter.
.. versionadded:: 2.7
Parameters
-----------
message: :class:`~discord.Message`
The message that the view is attached to.
Returns
--------
Optional[Union[:class:`.View`, :class:`.LayoutView`]]
The view if found, else ``None``.
"""
return self._connection._view_store._synced_message_views.get(message.id)
Hmm that's good but I assume this is only for covering the part of getting the view
Still would need to implement the other checks
Like an internal method somewhere to check if that message's view is active
Or not internal 
it shouldn't be in the dict if it isn't active?
After a restart, _synced_message_views is wiped out
It populates when you send a message with a view
Ah wait I'm not sure that was a question xD
yes it is
O yea
oh wait this is dumb then

so we need something for the custom_id
Wdym
so that doesn't work after restart anyways
It does, that's its purpose
how so? _synced_message_views is empty after restart
Yeah
And then I do
if view and not ...
So if this condition is false, it means I can reply with "this x has expired", because the view is not active
all discord sends with the event is the component type, id and custom_id
yeah so the that'll always return false on restart.. unless you send a view on startup
If you need data you are inherently on the hook for getting it
Yeah it'll always be false if that view is inactive (in other words: if the message does not have a view attached to its id)
I check using the message id of the interaction
oh god I need to wake up
I thought you were sending a message IF the view was stored

Oh nah lol
that makes a lot of sense now
so
it would be
if (view := interaction.client.get_view_from_message(interaction.message)) and view.id in ...:
return
...
You can accomplish this with persistent views, it just doesn't do this by default because the library maintainers aren't as paranoid and anal about restarts
IMO honestly just a generic error when there's an interaction without a corresponding component would be fine
Catch the error, send a response
I imagine that PR wouldn't be controversial, an exception (or one you can optionally enable) isn't warping
raise_on_unknown_interaction=True
hm ig but then how would you handle that?
Client.on_error is not an event
whats the point of raise if it doesnt let u respond
you can respond while handling the error?
Or rather than an error let you implement a fallback
It should still be implemented as an event somehow
I doubt the maintainers would like to store a function like that
It doesn't need to be an event
so a method that takes a fallback method? that can work
It could just be a method on client with a default empty implementation
hm
So now back to how that's implemented xD
it's easy to implement
This is one option
not easy to get it past the maintainers
well shit
#1296458798256488459 message has very valid points
gotta get past teh hardest obstacle
sharding and multiple instances
indeed
Why would multiple processes matter though
I didn't exactly understand
Ah well in that case the interactions that are received and their responses may interfere with each other?
So how do respones in general not fail for multiple processes
whats the big difference
I guess because they're more dynamic
they're made per instance, the other instances doesn't know about the other ig
In comparison to this feature (that doesnt exist), that implements a generic response to "unknown" interactions
<@&831776746206265384>
Mods smite this guy
Then with a command interaction response, how does the code know which instance should be the one to respond?
Based on the guild so you know which shard covers that guild?
Since I don't know how it works, I just fail to understand how what he described is a real issue. But I have a reason to believe him Ig.
And still the interaction object is bound to a certain guild (or no guild at all), so you should still be able to choose the right process? 
But no idea how it works
you could ask em
Maybe it's about this.. Aiohttp uses that session for the request
Holy shit http.py breaks my brain
...
def __init__(self, *, timeout: Optional[float] = 180.0, id: Optional[str] = None) -> None:
...
self.id: str = id or os.urandom(16).hex()
self.is_id_overridden: bool = id is not None
class Client:
...
def get_view_from_message(self, message: Snowflake, /) -> Optional[BaseView]:
return self._connection._view_store._synced_message_views.get(message.id)
class Interaction:
...
def component_callback_available(self) -> bool:
if not self.type == InteractionType.component:
raise TypeError
if not self.message:
raise AttributeError
view = self.client.get_view_from_message(self.message)
return True if view and view.is_id_overriden else False
async def the_holy_internal_check(interaction: Interaction):
...
if not interaction.component_callback_available:
await the_function_to_handle_this_situation(interaction)
Anyway this is what I was able to come up with.
But I can't get any forward with this for now, would probably have to first prove that it can work
But at the end of the day you get all sorts of data of that interaction, including guild data, so Idk where problems come from

i'm doing Client.on_unknown_interaction rn
it'll function similar to Client.on_error
Thankfully I actually do have a sharded bot to test this on
Although its just a very few shards
If view.id ends up being a part of this whole thing, I suggest allowing to pass it in the instance
oh yeah
But it doesnt really have to be view.id. It can also be a check whether all view's items have custom id, or even if just the item that sent the interaction has..
At the end of the day you'd be checking for the view by message id
I forgot why I brought up view.id for this to begin with 😭
i don't even know why view has an id
yea it seems to not be used for mapping
lemme see where its found
{
1426127885659410462: {
(2,
'012ea8912709d5077beb5d0c03e74df2'): <Buttonstyle=<ButtonStyle.primary: 1>url=Nonedisabled=Falselabel='Coqui Frog'emoji=Nonerow=Nonesku_id=Noneid=None>,
(2,
'406511a3b0bd23a85cb7ad334be75de2'): <Buttonstyle=<ButtonStyle.primary: 1>url=Nonedisabled=Falselabel='Red-Eyed Tree Frog'emoji=Nonerow=Nonesku_id=Noneid=None>,
(2,
'd4cd9ce7a1a092a7c480633b041c88b1'): <Buttonstyle=<ButtonStyle.primary: 1>url=Nonedisabled=Falselabel='Australian Green Tree Frog'emoji=Nonerow=Nonesku_id=Noneid=None>
}
}
012ea8912709d5077beb5d0c03e74df2 is a view id for example
ah so it is used
{
message_id: {
(component_type, 'view_id'): component object
}
}```
yea
class Client:
...
def get_view_from_message(self, message: Snowflake, /) -> Optional[BaseView]:
return self._connection._view_store._synced_message_views.get(message.id)
class Interaction:
...
def component_callback_available(self) -> bool:
if not self.type == InteractionType.component:
raise TypeError
if not self.message:
raise AttributeError
view = self.client.get_view_from_message(self.message)
return True if view else False
async def the_holy_internal_check(interaction: Interaction):
... # Make sure to handle dynamic items before the following, or find a way to make them not contradict.
if not interaction.component_callback_available:
await the_function_to_handle_this_situation(interaction)```
⬆️ Yea it can work without view.id (probably), Idk why I got it involved
Removed the baseview, its useless now
nice
ig it works https://images.soheab.com/euOoRIV9jLw.png
class MyClient(discord.Client):
async def on_unknown_interaction(self, interaction: discord.Interaction):
print(f'Unknown interaction received: {interaction.id} from {interaction.user} with data {interaction.data}')
await interaction.response.send_message('Sorry, this interaction is not recognized.', ephemeral=True)
intents = discord.Intents.default()
client = MyClient(intents=intents)
@client.event
async def on_ready():
view = discord.ui.View()
btn = discord.ui.Button(label='Click Me', custom_id='my_button')
async def callback(interaction: discord.Interaction):
await interaction.response.send_message('Button clicked!', ephemeral=True)
btn.callback = callback
view.add_item(btn)
view.stop() # added after first run
await client.get_partial_messageable(679016927988940831).send(view=view)
What's the backend though 
Bruh I forget to turn off mention
its fine
it's just <state>.dispatch('unknown_interaction', interaction) in bunch of places where it exists if not found
also for app commands
what is the condition of not found? The one you have in: https://github.com/Rapptz/discord.py/compare/master...Soheab:discord.py:interaction-valid ?
Like if there was no dispatch, then dispatch the unknown interaction?
yes
Please react with ✅ to upload your file(s) to our paste bin, which is more accessible for some users.
bruh
😭
I wonder if the maintainers would like the idea of having it as a fallback rather than a more specific condition

Anyway you might see a similar response from them again, what do I know
most likely
Will see in a couple of hours
:kekw:
Give up fam
Why are you making stuff on_ready?
it's just a test function
If you guys are trying to reactivate the buttons after bot's restart best version is creating a proper sync that works after bot is ready.
Why is slash command information hard to come by. Everywhere I look for code information on python prefix are what everyone uses
Even tho slash ain't that hard
It depends where you're looking
if you're looking on google/youtube, that's just basement vibe coders that wait for someone else to copy
It's crazy how easy it was to register slash commands compared to js as well as cogs
i need help with hikari
i have a command that return's a string from a list if the name of the link given in the command is in the list
so if i was to do /links_list name:test it would return the link named test if it is in the list
the problem is that i want to show what are the links available when typing the command but i have no idea how and i cant find anything on the internet
like autofill?
if you pair lightbulb with Hikari I think this is the proper way to do it actuallyhttps://hikari-lightbulb.readthedocs.io/en/latest/by-examples/080_autocomplete.html
Autocomplete is a Discord feature that allows your bot to suggest values for an option dynamically based on the content already entered by the user within the option being autocompleted, as well as...
there's an example there
async def autocomplete_callback(ctx: lightbulb.AutocompleteContext[str]) -> None:
current_value: str = ctx.focused.value or ""
values_to_recommend = [
i for i in list_of_links if i.lower().startswith(current_value.lower())
]
await ctx.respond(values_to_recommend)```
I think the autocomplete for you might look like this
alr thank you i will try this
Hi I need help
You're gonna need to be specific
@narrow hazel where ?
with what?
im creating my first discord bot
Best of luck!
Yoo
Dmsa
Someone knows how to host a bot for free 24/7
Get a VPS
Its paid or free
Oh I Heard that theres a way to host it for free
off of your laptop
Wdym
If you have a laptop you can host it at home 24/7 for free presumably
@mild kiln Sadly, in this world, your best option is buy a VPS, to be able to host your application 24/7.
I recommend hetzner, you can get it for cheap a month.
thank you so much it work
i am using crescent so it took some adjusting but it finally works
!hosting
Using free hosting options like repl.it for continuous 24/7 bot hosting is strongly discouraged.
Instead, opt for a virtual private server (VPS) or use your own spare hardware if you'd rather not pay for hosting.
See our Discord Bot Hosting Guide on our website that compares many hosting providers, both free and paid.
You may also use #965291480992321536 to discuss different discord bot hosting options.
Oracle has a free tier, I have never used it to know if it is good
Hello, how can i put a stringselect menu in a modal?
!d discord.ui.Label
class discord.ui.Label(*, text, component, description=None, id=None)```
Represents a UI label within a modal.
This is a top-level layout component that can only be used on [`Modal`](https://discordpy.readthedocs.io/en/stable/interactions/api.html#discord.ui.Modal).
New in version 2.6.
the component being the string select
why has discord not made an easier way to get a threads content 😭 this is the first time I had to use an async for loop
I mean it's not something that a lot of bots will need to do
especially with slash commands
What about a loop isn't easy? That's one line with a built in keyword
How does that translate to that being hard or that discord/the library should do something differently
[m.content async for m in thread.history(...)] works too
But it's still just one endpoint with pagination
That just makes sense
can anyone make me a custom version of sapphire so I can change its pfp to my server logo. Pls.
I really don't think you understand the huge scale of Sapphire, no, nobody can just make a copy of it
also random people aren't just going to give you things for free, especially if you put 0 effort into at least trying yourself
making some random bot have a hee hee anime girl profile picture is not worth all that work
What's sapphire?
💀💀💀💀💀💀
Pay me and i make you 💀
not free
Generic "multi purpose" moderation bot #853744 from what I remember
Advertising features that are now native and better on their front page lol
Might want to check the #rules
ahhhh
it was a sarcastic joke...
👍
I have 27 commands and only synced 10
Code?
How can I use links without breaking them?
[*BoldName*#1234](https://www.op.gg/summoners/euw/BoldName-1234)```
[*BoldName*#1234](https://www.op.gg/summoners/euw/BoldName-1234)
could you elaborate on what you mean by breaking?
Without the \
Doesn't seem like masked links respect escape characters
When it comes to markdown in hyperlinks, one thing I noticed is you cannot do a double slash after "http/s:"
Reasonable lol
I'm running into an issue in Discord.py where I need to access the Cog's self inside @app_commands.choices() for a slash command. The problem is that self isn't available outside of functions, and it's also not accessible when the class is being created along with the decorators
choices aren't meant to be dynamic
They're for a discrete small set of options that doesn't change
I don't want the options to change during execution, but I want to automate something that can vary from one run to another
I'd suggest just making it a constant, then
idk how it is setup in discord.py but you could manually set the choices in the cogs init.
class MyCog(Cog):
def __init__(self):
self.my_command.options[2].choices = self.whatever
@app.command()
async def my_command():
You can probably do something like that but the syntax is most likely different.
AttributeError: 'Command' object has no attribute 'options'
That's a shame, but ok
What's a shame about using a constant for...something constant 
Perhaps you want to use autocomplete. 
Or a select menu. Dunno what your use case is.
Question: If I create a ui.LayoutView instance that is not going to have any components, what should the timeout be? Should I just leave as default?
whatever is probably fine
Probably that it is not a constant.
something that can vary from one run to another
Whats the difference between a for loop and an async for loop?
I had an idea to update my project but I wasn't sure which method to use for it
async for is for when you want to iterate over an iterator that supports async iteration.
ok so it's not used commonly when you need to loop stuff
yeah, not super common
Another W
It awaits the __anext__ method of every element of the iterable for you, producing the next element asynchronously
Imo anything with more than 3 layers of nesting is goofy ahh code, only god knows how many more layers of nesting are there 🙏🏿
so how would you do it to loop the message content and check if it equals the integer thats stored?
By not using jsons
the json has nothing to do with the nesting
The with block does add up a layer of nesting
if message.channel.id == 1380373033516007597:
try:
with open("JSON_storage/counting.json", "r", encoding="utf8") as f:
count = json.load(f)
for m in message.content:
if count["Count"] == int(m):
count["Count"] += 1
with open(
"JSON_storage/counting.json", "w", encoding="utf8"
) as f:
json.dump(
count,
f,
sort_keys=True,
indent=4,
ensure_ascii=False,
)``` I could remove the JSON storage and it would still nest
I genuinely cannot read this on my phone
count = 1
if message.channel.id == 1380373033516007597:
for m in message.content:
if count == int(m):
count+= 1```
exactly the same just without the JSOn
Idk what exactly you're doing, could be just a design issue
its a counting game
Im looping the message content to check if it contains the number for the count. I wanna allow people to talk in the counting game to add interaction
more fun than doing
1, 2, 3
Okay
Have you ever heard of regex
I have made a system that allows exactly that
Or even just "".join(n.strip() for n in message.content.strip() if n.isdigit()) if you want it really simple
Also wouldn't int(m) fail if m isn't a digit?
But yeah Regex is good for this case, I guess re.match
Yeah Soheab's version is safe, the one in Zizzle's message isn't
You are adding unnecessary file I/o operations, you can open a JSON file as write and read mode with the same statement
Also, may I ask why are you saving all the messages inside a JSON?
You could either just retrieve the whole channel message history (which is kind of inefficient) or just store the last valid number of the sequence in a global variable or cache
How come, he needs to check with Count first and then it's a conditional save
Anyway yeah I really see no reason to save all messages. Is this for the counting game? You could save just last one in that case
I'm just saying you can just use "r+" mode for example, and then dump and load according to your needs, no need for two separate with statements which adds unnecessary nesting
But it's conditional, he may not update the json
You dont necessarily need to write on the JSON file tho
Yeah pretty much
When opening a file with r+ permissions, it allows you to read and also write without having to open the file twice
For the counting game there's no reason to save more than the last message
I don't know if I'm explaining myself right
I think you are
Yeah, I think the easiest way is to just store the last valid number in cache (if the bot is 24/7)
I never depend on cache because I restart often xD
Better not use cache when self hosting
Actually it's less related to the environment u use
Better have persistency with a DB
Yeah true, even if you rely on persistent cache
If it's just a simple counting game you can just use Supabase
Yeah
Recomparing to the newly saved data each iteration can't be good
Just stack them up and save at the end
I would suggest code, but cba cause I'm on mobile lol
But wait, he opens the file before the iteration. Doesn't that mean that Count will stay the same?
Keep it simple, create a static class, with a counting variable and two static methods, increase and decrease counter, then every time someone passes a valid count increase
A class is not that necessary xD
It's simple operations unless you use a DB
Which he should ig
It's for keeping it somewhat organized, that way you don't have to hit the database everytime counter increases
You can just update the DB entry every 30 mins or so with the latest counter number
Yeah I think we are just going to confuse him
@narrow hazel
I assume you are still learning so I won't suggest using a DB
I don't think it's necessary to store it in a JSON, a plain TXT file will be much simpler to use
Json is used to store the count after restart
Yeah but you don't need a JSON, you can use a TXT file
As a JSON adds an unnecessary level of complexity for such an easy operation such as increasing count
Hmm tbh something I wanted to know, what's the issue with saving every time? With DBs
I just don't like losing data, and I don't think scheduling DB task is such a good thing
For small apps not much, but it's always better to avoid unnecessary transactions, because when you scale bigger, it affects performance
I'm not sure the difference between a txt and json
That's also reasonable, but in those cases I prefer to rely on cache, which is much faster and won't crash if the main application does
A JSON is basically a dictionary, you save values in a structured way (in key value pairs to be exact)
In a JSON it would be:
{
"Count": 1
}
Un that case you have to load the JSON, the access the "Count" key and retrieve the value
With a plain TXT file you can just store the count itself, so 1 per se
The shame is that it’s not a universal constant — it changes from run to run, and I could automate it if that wasn’t the case
I'm not sure I want to do that since I'll just lose data on crashes
But alright
This sounds like a bad idea, updating command choices??
No, only set once per run
Do you fetch them or something
Yes, I fetch them at the start of the Cog
Why not use a static variable. They don't update as long as you don't sync anyway
Yes, it's really no problem to do that, I just wanted to see if there was any solution for the automatic way
You won't, Redis for example is persistent, even if the main application crashes, it won't lose any data
Not that typa crash that I experience lul (: but yea thx
For now as my app is small ill save each time
Yeah that's fine, you can also split into microservices any time
ignore what i deleted if u saw it
Didn't haha
Parameter is read-only
Why assign choices like that instead of using app_commands.choices
That's what I use
Or u want to assign params like that, even more odd
I was thinking if there is a way to make a "emergency backup" for my discord bot. If my discord bot get offline, a backup bot like dino, carl or Gaius Cicereius bot will activate (those bot are not by me)
Quite a stupid question ngl
Or is there anyway to keep my server cool if my home server gets shutdown (like a blackout)
(Please ping me if you have an answer, i'm going to be eating dinner soon)
Then you shouldnt use choices? You said earlier that they didn't change, now you're saying it changes run to run
This is a perfectly valid use case for choices. It's weird that discord.py does not support this (or at least without a lot of monkey patching)
It can supports it when using a transformer
It's really not
Choices are designed specifically for things that don't change, as you have to eat into your syncing rate limit every time you want to change them
It's a max of 25 anyway, what's the worst that could happen if you just manually wrote them
It's simple if you ask me
Changing choices will not meaningfully eat into the syncing rate limit assuming you are updating
"Run to run" is pretty ambiguous
It might help to better understand the actual use case
Changing choices is bad UX
what?
bots don't send commands
i mean msgs * 😭
what format do you mean?
im tryna find a picture of what i mean wait
Build games, experiences, and integrations for millions of users on Discord.
embed?
EMBED yes ok thank u
no...
ty
create an instance of it and pass it to the embed kwarg in whatever method you're using to send the message
Might want to look into components if you are just getting back into it
componennts v2?
can u send
Depending on your goals they have more flexibility
Build games, experiences, and integrations for millions of users on Discord.
alr cheers
This is what I'd do, assuming this is the game he's making
And you can use sympy like this to support basic math expressions (:
@gritty inlet I like your solution, this is what i meant earlier this morning btw
class CounterManager:
# Stores the count for each channel by its ID, shared variable across all instances.
channels_count_storage: dict[int, int] = {}
def __init__(self, channel_id: int) -> None:
self.channel_id: int = channel_id
def increment(self, sent_number: int) -> bool:
current_count: int = CounterManager.channels_count_storage.get(self.channel_id, 0)
expected_next: int = current_count + 1
# Special case: Starting the game (nothing → 0)
if self.channel_id not in CounterManager.channels_count_storage and sent_number == 0:
CounterManager.channels_count_storage[self.channel_id] = 0
return True
# Validate sequence: sent number must be the next expected number
if sent_number < 0 or sent_number != expected_next:
return False
CounterManager.channels_count_storage[self.channel_id] = sent_number
return True
def reset_current_channel(self) -> None:
CounterManager.channels_count_storage.pop(self.channel_id, None) # pyright: ignore[reportUnusedCallResult]
@classmethod
def reset_all(cls) -> None:
cls.channels_count_storage.clear()
Then you can add checks to increment, so the logic lives inside the class and not inside the discord functionality layer
hello, everyone
You can also add helper methods (advantage of OOP :D):
class CounterManager:
# Stores the count for each channel by its ID, shared variable across all instances.
channels_count_storage: dict[int, int] = {}
def __init__(self, channel_id: int) -> None:
self.channel_id: int = channel_id
def increment(self, sent_number: int) -> bool:
current_count: int = CounterManager.channels_count_storage.get(self.channel_id, 0)
expected_next: int = current_count + 1
# Special case: Starting the game (nothing → 0)
if self.channel_id not in CounterManager.channels_count_storage and sent_number == 0:
CounterManager.channels_count_storage[self.channel_id] = 0
return True
# Validate sequence: sent number must be the next expected number
if sent_number < 0 or sent_number != expected_next:
return False
CounterManager.channels_count_storage[self.channel_id] = sent_number
return True
# Helper
def get_current(self) -> int | None:
return CounterManager.channels_count_storage.get(self.channel_id, None)
# Helper
def get_next_expected(self) -> int | None:
return (self.get_current() or 0) + 1
def reset_current_channel(self) -> None:
CounterManager.channels_count_storage.pop(self.channel_id, None) # pyright: ignore[reportUnusedCallResult]
@classmethod
def reset_all(cls) -> None:
cls.channels_count_storage.clear()
Hey!
Pretty clean implementation
Thanks 🫶
out of curiosity , with the new components can you send the view aswell as an file that’s not part of the video together?
I’m too lazy but I know there’s some common sense here
What do you mean by "not part"?
You can send attachments with a component v2 message afaik
You have to put the attachments in a media gallery for them to render tho
It doesn't change during one, but it changes from one to the next. I'll be direct, it's basically the bot commands that I want to automatically pick up
I'm translating this here, so I don't understand it properly anymore, but I've already resolved it, I'm not going to use a class, I'm going to create the commands globally within startup, I don't see many advantages in using a class
what actually causes the options to change though?
they're not just changing randomly
You really might want to consider autocomplete here
how do i get
get...?
speaking about audio files, same way you can send a audio file with a embed , can you do the same way the new component since they can’t be added in the media gallery
There is no way to get audio files to have a preview or player with components currently.
thanks
What version does v2 component support
Depends on what library you're using
i didnt even know you could send audio files with embeds
You can't
That's a separate message
At least, I tried it a week go and it didn't allow anything
Would be great if a file component could render if it's an audio file
i hate u
🥀
I just copied a real mp3 preview, no idea if Discord would make it that color and that size if they made them render
still good concept
Posted in https://discord.com/channels/267624335836053506/1427762436534177824 python help if anyone would mind looking it over. should be fairly basic for someone familiar with discord bots.
Actually, you can get quite close of creating something similiar 
Using the new components as v2 containers are definitely a improvement into style.
and labling of your messages
is a list an array but just named differently? I was looking for the differences but they look exactly the same?
am I just being dumb?
Lists and arrays are the same thing for the context of python.
List can contain heterogeneous elements while arrays contain homogeneous
There's a separate module in python called array
oo
does python have anyway to selfmake errors? Like in JS they have console.log for print and console.error for errors. Does python have anything similar?
You can check the logging module in python
oh yeah the logging module, I messed with that once but couldnt figure it out. I might check it out again, thanks
Discord.py prettifies and formats your logger to be better. All you need to do is import discord.utils.setup_logging and call it once in your entry point of your program
sounds good thanks
With logging you could do
logging.exception
logging.error
logging.warning
Etc
In python it's the same
How exactly? Audio files don't render in Components V2 in any way
What is this error from?
Did you recently upgrade Python or discord.py?
not that im aware of
Is this error from now or did you have that for a while
I just got home and logged on PC and saw it
nope I just got home and I logged on and imported an event I worked on at work
I just copied the code from the server onto VSC
I got it
I upgraded discord.py and it stopped showing the error

so weird
These things don't have timers built in that randomly break things
You did something
Are you using any feature audio-related
What? It's the recommended way by ruff and many other linters, also re raising the exception will halt the execution of the program or send it to higher layers which is bad because it adds complexity
And also logging.exception automatically adds the traceback to the message, critical doesn't and it's best suited for more extreme cases where an error would cause the whole operation or application to malfunction
If anyone is interested on the topic I highly recommend this article: https://realpython.com/python-raise-exception/
correct, but there are various designs u can create
Not with the voice message being in the same message, unfortunately
Audio file*
Voice messages will be the same in this context
You can literally make that same embed tho, but keeping file on the outside, and its mostly about creation, you just put a button and send the file so it doesnt look ugly
That's what I've actually done, yes
see! it's fun and easy :D
I eventually had to terminate that command because it required presence intent 💔
And no I'm not going to implement Spotify's Oauth just for one command
Does V2 have the same char limit as embeds?
Sheesh
Is there a way to get an array of my events like I can with my commands?
Or do i have to go through each event manually and add a print statment
what do u mean
Like with commands you use the .synced to get an array of commands im wondering if events have something similar to find out which ones are working
don't think so
Ah well
What do you mean by events "working"?
if they're properly formatted for event listener
What does that mean? Whether you listen to them with a @bot.event statement?
Or you wanna know when an event is received?
There's an event for raw socket receive, Idk more than that
But I don't see how this kind of debugging is useful
Yes get listeners
Thats it thanks
Not all listeners are in cogs
Can I use a timeout like this?
https://paste.pythondiscord.com/IQLQ
Why not just defer and try-except the method like normal?
Oh you're sending a modal
Why the wait for in the wait for callback though
Why limit the function's execution time like that
Plus the last try-except is unecessary
Because I want to limit the DB call the same way as the whole process to guarantee that errors are returned properly if that makes sense
Since we can't use defer when sending modals
Limiting execution time does not equal ensuring errors are returned properly?
It does if you only have 3 seconds to respond
Then make the modal openable from a button
I think it's bad practice to enforce limits like this
Why do you think that?
At least they will receive a proper error instead of "The application did not respond"
That is not what I want to do
I can tell lol
I dont see what is funny
The idea is to use the button for checking only. If that fails the user should receive an error embed
Shouldn't this except Exception as e: be except asyncio.TimeoutError as e to be more specific or at least try to catch that error before catching all errors with Exception
But you realize this failure pretty much comes from the fact you set a timeout to that function?
I would probably check if user has an account somewhere else, but Idk the context
that is a good point
The function not running in the set time could indicate a different kind of failure, but time-limiting instead of catching the actual error isn't good
Could do that too
Regardless, the very last try-except seems to be useless
discord.py
What makes bot.user.avatar or banner populate and not be None?
Works normally for me
Also, is there a way to get the bot's per-guild bio? Since you can edit it
Modify Current Member is new so that probably isn't implemented in the library yet, Idk
Not yet in dpy
I have a banner set in the developer portal, yet the following two are None
Hmmm
My banner gets auto cleared in the dev portal
I don't use banners
. But for normal users you have to fetch, the banner doesn't get cached
Yea, I assume bot's own also doesnt..
values is untyped.
should i just add # type: ignore or just access it from interaction.data...
ignore the variable name, its misleading
Ye right right but my type checker doesnt care
So just tell the type checker what .component is
The typechecker is correct otherwise
By doing what
assert isinstance(self.avatar.component, discord.ui.FileUpload) is what all of dpy's examples do
Can also use typing.cast
alrighty thanks
Or component: FileUpload = ...component # type: ignore
ill use assert
Nice
How can i pass conditional args to guild.me.edit?
For example "only pass" avatar if x
Because I'm pretty sure that if I pass avatar as None it'll clear it
make a dict and pass it as kwargs
me_kwargs = {}
if some_condition:
me_kwargs["param_name"] = value
await guild.me.edit(**me_kwargs)
hmm i can pass utils.MISSING
since the internal check is like this
whar are you trying to do?
Conditional update of member stuff
Works
Show code, I doubt using utils.MISSING would be better in any sense than passing in a dictionary of the keyword args
Don't pass in missing, that's an internal implementation detail
I'll pass None, didn't think about the fact that it clears just for that server which is fine
thats cool
how
which?
user tag
!d discord.User.primary_guild
property primary_guild```
Returns the user’s primary guild.
New in version 2.6.
Funny that it's duplicated in the API response, it's there both as "clan" and "primary_guild"
In avatar: You are changing your avatar too fast. Try again later. 🥀🥀🥀
Will have to implement cooldown
Is the exact rate limit of this known? Or even approximate
all rate limits except for the global one are dynamic
If you're hitting it then you're probably trying to do an improper use case
What would be good UX wise for this 🤔
I guess, I hit it because I was playing with it xd
True. If the process takes longer than 3 seconds, it should time out. The modal wouldn’t be sent after that point anyway since we can’t defer when sending modals.
Process
- Check for existing user in the database
- Submit Riot ID
- Verify Riot ID
Why am I getting Coroutine 'create_task' is not awaited?
I can't create a task and send the embed or modal without waiting?
you don't need to await it before sending stuff, but you do need to eventually await it
or at least store a reference to it
also wait, asyncio.create_task isn't a coroutine 
I want to create a task that removes the role and sends the modal without waiting for the task to finish
then what is going to store a reference to that task when your function returns?
Why do I need a reference?
because python has a garbage collector?
you could also just await it in that method but after you've done your other stuff
You are right
I just need that response within 3 seconds 
Clan was a different experiment that was discontinued
just a quick question, i've never actually used button IDs. Am I able to use the custom ID from discord.builders for a V2 button inside the @discord.ui.button(label="", style=, custom_id="") to control it's interaction?
it's just id iirc
you're right
!d discord.ui.Button
class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None, sku_id=None, id=None)```
Represents a UI button.
New in version 2.0.
Damn didn't know it had id as well
I doubt the usefulness of this for a button though
I haven't used id so far regardless, dunno what the use case is
It's for persistent views
So your views can work even after your bot restarts
Used internally?
Internally as in?
((((:
You're talking about id
Indeed
Yea no clue
All components have it and Idk how it's useful
Maybe the api returns a unique id for it idk
Maybe for dynamically rebuilding a view
Nah you set that id
Oh
Could make sense, say if you loop over view children if you get the view from a message; it's a reliable way to find a specific item
Also find_item and remove_item take it
I never needed to do that but maybe some people do
find yes, remove no
But that's pretty much it
custom_id is still required, but id isn’t
Both must be unique, and id assigned a unique integer by discord when not passed
What do you think of an implementation like this?
https://paste.pythondiscord.com/QHWQ
- Run task to remove role
- Send embed
- Wait for the task to complete
Would that be any improvement over simply sending the embed first and removing the role afterwards?
I wouldn't use tasks here
Why not?
wait nvm
Don’t get me wrong, I just want to see if I can learn something from the way you think
assert interaction.guild
assert isinstance(interaction.user, discord.Member)
if existing_account:
role = interaction.guild.get_role(UNVERIFIED_ROLE_ID)
if role and role in interaction.user.roles:
asyncio.create_task(interaction.user.remove_roles(role, reason="Riot account linked"))
embed = discord.Embed(
description="You already have a Riot ID linked to your Discord account.",
color=discord.Color.red()
)
await interaction.response.send_message(embed=embed, ephemeral=True)
else:
await interaction.response.send_modal(RiotModal())```
My implementation
You do not need to await tasks
Also don't do these assert lines if you don't use a type checker. Moreover, make sure the user is a guild member
You need the else. Otherwise if existing_account is True, it will run that block and then will attempt to send modal
I also recommend wrapping the role removal in try-except but being more specific with the exception, not Exception (or at least add that as the last except)
This really doesn't seem to need a task. If sending the response doesn't require the results then just do that thing after sending the response
You're talking a difference on the order of less than a second

Or just asyncio.gather if you want to run two coros together
Were there no other exceptions?
But you should've got NotFound
Unless you catch that exception
No, the author is none
if the lines they sent are relavant to the partial error they sent
What type of message is that where author is None
Ah well
Or

