#discord-bots
1 messages · Page 417 of 1
You're already responding to the interaction
15 mins
But you've already responded so discord doesn't care anymore
What you should be doing here is moving the sending message to the task too and only allowing one per guild
And don't call it yourself
async def mass_give_roles(self, members: Sequence[discord.Member], role: discord.Role, inter: discord.Interaction) -> None:
if inter.guild.id in self.currently_roll_assigning:
await inter.channel.send("This guild already has a /roleall task running! Please wait for the previous task to complete before calling this command again."
return
self.currently_roll_assigning.append(inter.guild.id)
for member in members:
try:
await member.add_roles(role)
await asyncio.sleep(0.42) # this is probably good enough
except discord.Forbidden:
result = f"Error: Missing permissions to update roles for {member.name}"
await inter.channel.send(result + f"\n{interaction.user.mention}", silent=True)
except discord.HTTPException as e:
result = f"Error: Failed to update roles for {member.name}: {e}"
await inter.channel.send(result + f"\n{interaction.user.mention}", silent=True)
result = f"Success! {role.mention} added to {len(members)} member(s)."
await inter.channel.send(result + f"\n{interaction.user.mention}", silent=True)
self.currently_roll_assigning.remove(inter.guild.id)```
?
Wth is that
💀
Well it's fine outside of sending the result multiple times in the loop
thats for specific users
But I was thinking something like
# task
async def mass_roles(interaction):
... # add roles and send message etc
# command
...
if interaction.guild.id in self.tasks:
return ... # tell user to F off
task = asyncio.create_task(mass_roles(interaction))
self.tasks[interaction.guild.id] = task
task.add_done_callback(lambda: self.tasks.pop(interaction.guild.id, None))
...
Could send the message etc in a done callback too but eh you can decide that
will this fix the race condition if two admins from triggering the task at the same time
lock = asyncio.Lock()
async with lock:
if inter.guild.id in self.currently_roll_assigning:
await inter.channel.send(
"This guild already has a /roleall task running! Please wait before calling this command again.",
)
return
self.currently_roll_assigning.append(inter.guild.id) # yay fixed the race condition hopefully
for member in members:
...
What if you process them in chunks rather than sequentially
10 members > sleep 1 sec on repeat
1000 × 0.42 = 420 seconds
1000 ÷ 10 = 100 seconds
smart
What hosting service do yall use to keep bot Alive? (Also is it free or paid)
It would not be economically feasible for someone to provide you compute resources for free eternally
I use digital ocean, $4 a month.
Oracle also has a free tier
fly.io is a good paid one
I see. Thanks
!d discord.Guild.edit
await edit(*, reason=..., name=..., description=..., icon=..., banner=..., splash=..., discovery_splash=..., community=..., afk_channel=..., owner=..., afk_timeout=..., ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the guild.
You must have [`manage_guild`](https://discordpy.readthedocs.io/en/stable/api.html#discord.Permissions.manage_guild) to edit the guild...
Thanks
How are you identifying which messages you want to delete?
by an int
But i think i got it
I just did
async def clear(ctx, amount: int):
deleted = await ctx.channel.purge(limit=amount + 1)
yes am also working as solo on similer project
hi :3
i've made a pretty big discord bot. I'd like if someone could review it and give some insights. I have it on github :)
link?
Improved version of MusicBot.py, a feature-rich Discord music bot built from scratch. - japaneseTemmie/MusicBot.py-2.0
-
You didn't have to create a separate repo for v2, you could've just used your original repo. One of the biggest reason to use github is for version control itself and it becomes ironic if you don't use it for that. You can make use of tags and releases to mark (a snapshot) of different versions of your code base.
-
Personally I prefer keeping only the main file at the root of the project and the rest of the files inside a folder to make it clear where the entry point is supposed to be.
-
Usually you'd name your entry file name of your program as
main.pyor the name of your project, notrun.py -
Automatically installing and checking for dependancies in runtime is diabolical, don't do that. There's so many points of error and adds too much complexity for very little purpose.
-
Avoid using
from module_name import *whenever possible, it usually pollutes your namespace and type checkers cant infer what you're importing and also makes debugging slightly harder. -
Instead of manually attaching an error handler for every command individually to do the same thing, you can override
discord.app_commands.CommandTree.on_erroronce and it will apply to all app commands -
Use formatters, linters (like ruff which does both) and type checkers (like basedpyright)
-
Your filenames should follow
snake_case, yours is like a c style with no underscores lmao -
You can use docstrings within the command method to give it descriptions and stuff instead of having an unreadable
help.json -
In some places you have mutable data as default value in a function's parameter, specifically your this function in
iohelper.py:def ensure_paths(path: str, file: str | None=None, file_content_on_creation: str | dict={}) -> bool:
This is a very bad idea since if you don't overwrite it, the data in default dict will persist in every function call instead of clearing. Just google "why should you not have mutable data as default params in python functions" to learn more
- I just saw your
settings.pyfile realized that your import that shit into EVERY module... that's single handedly one of the most questionable things I've seen. ONLY and ONLY import the modules / packages you actively need in your working file DIRECTLY instead of having a separate file that loads shit ton of unnessescary files and then load that bloated file into your working one
I'm not even gonna question why you have time.sleep in that file..
there's probably a some more i can point out but these are some of the obvious ones
Even though you're making use of json as a database and you handled synchronizations and somewhat non blocking, json is still not suitable for databases because it can get really slow very fast (especially because of synchronizations)
its not even that hard to use an actual db lmao
For very small things it doesn't matter
Nah, in this case, the amount of efforts they put into syncs and non-blocking, they could've easily just used aiosqlite (which does that for you) for half the effort and better readability
👍🏿
thats exactly what i thought before using type checkers
now i cant go back
i js use vsc standard to point out the obvious mistakes i do and run basedpyright for the more detailed ones
the ... hits hard 
type shift
Should I just append all functions instead of allowing only one per event? 🤔
Not that serious
Well, i'm aware that's generally a great idea, but if i need a lot of stuff, the top of every file will be cluttered with imports instead of one. I'm actually trying to improve the codebase, it used to be much, much worse than this lol :3
Got it. But feature-wise how'd sum it up in a rating?
My review is that this violates TOS and this server's rules by extension
No. It's NOT a great idea even remotely, you're taking DRY to a next level which should be avoided. Even if it means to reusing the same import statements in many files, do that. Be explicit with what you're importing and actually using not implicit.
I haven't seen in detail what all features are there but code quality wise I'd give 5/10
Also if you want to automatically sort your imports you can use isort or ruff (with I rule extension as fixable) to do that for you
Bruh
Got it. Guess i'll take a look at the codebase with new eyes now. Thanks
Nah nothing wrong with that
with that
i like this quite less
Thing is, all 3 can be only two things, that's why they all just subclass the same thing and that's it
Always better to keep them separate for future proofing 
Oh btw i think you understood it wrong, i meant your approach is great
ohh i see lmao
how so? Please enlighten me
It is against YouTube tos to redistribute their content, and by extension against discord's.
It's also illegal to redistribute copyrighted content without permission from the copyright holder
Music bots in a nutshell
Well, It just streams it just like you'd do it with a browser
But yeah i guess so
I'd recommend just dropping the YouTube feature
Unless you want the chance of ending up like Rhythm
Don't redistribute copyrighted content or interact with services in unsupported ways
I'm not hosting it. it's just FOSS on github.
I won't get into this too much but as long as you're using a service that does that, you become a part of the problem too
Got it.. I just liked the idea of a personal bot and figured i'd put it on github if it could interest others too
Ima go now
I’m using pterodactyl panel but my bots code is python but I don’t know what happened
The error is self explanatory
async def security(self) -> discord.Embed:
g = self.guild
verif_map = {
discord.VerificationLevel.none: "None",
discord.VerificationLevel.low: "Low",
discord.VerificationLevel.medium: "Medium",
discord.VerificationLevel.high: "High",
discord.VerificationLevel.extreme: "Extreme"
}
nsfw_map = {None: "Not Set", True: "Yes", False: "No"}
afk = safe_attr(safe_attr(g, "afk_channel"), "mention", "None")
notifications = str(safe_attr(g, "default_notifications", "Unknown")).title()
explicit = str(safe_attr(g, "explicit_content_filter", "Unknown")).title()
partnered = "Yes" if "PARTNERED" in safe_attr(g, "features", []) else "No"
verified = "Yes" if "VERIFIED" in safe_attr(g, "features", []) else "No"
community = "Yes" if "COMMUNITY" in safe_attr(g, "features", []) else "No"
nsfw = nsfw_map.get(safe_attr(g, "nsfw", None))
embed = discord.Embed(
title="Title",
description=(
f"**Verification Level:** {verif_map.get(g.verification_level,'Unknown')}\n"
f"**Default Notifications:** {notifications}\n"
f"**Explicit Content Filter:** {explicit}\n"
f"**AFK Channel:** {afk}\n"
f"**AFK Timeout:** {getattr(g, 'afk_timeout', 0) // 60} min\n"
f"**NSFW Level:** {nsfw}\n"
f"**Partnered:** {partnered}\n"
f"**Verified:** {verified}\n"
f"**Community:** {community}\n"
),
color=discord.Color.gold()
)
return embed
is this code correct?
wdym is it correct dawg
run it yourself and see if it works, if there's any error show it and explain what you're trying to do
i wont ask if it tells me an error
you matafaka you better shut up if u gonna say run it myself
run it yourself
frick off you matafaka
Not that hard to just spin on the bot and use the command that send the embed
Better yet use jishaku extension
No need to be rude
You are asking for free help
No one can even run that command for him since there are variable and function names that only he knows how they are defined.
Really hope safe_attr is just getattr(obj, "attr", fallback)
But also, why is that even used there? Those attributes should always exist.
"Matafaka" 
i love abstraction over abstraction
i fixed it period
!mute 604560333063061505 1h If you want to remain in the server, you need to be more respectful towards its members.
:incoming_envelope: :ok_hand: applied timeout to @warm bramble until <t:1758968621:f> (1 hour).
no respectful for strangers , its for my parents
Are you saying you can't or won't be respectful to our server members?


I know this isnt a discord bot question but seemed like the best place to ask. when making a twich chat bot should i make a seperate twitch account for the bot or would using mine be okay?
I don't think you can use your own, don't you have to create a Twitch bot user with a token of some sort?
Doesn't even seem python related at all tbh
Might be good to start here: https://dev.twitch.tv/
i need help
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.event
async def on_ready():
print(f'Il bot è online come {bot.user}')
@bot.event
async def on_member_join(member):
channel = discord.utils.get(member.guild.text_channels, name='welcome') # nome canale
if channel:
await channel.send(f'Benvenuto/a {member.mention} nel server!')
bot.run('token') #token
what is wrong?
PING ME PLIS
and someone know a free hoster for discord bot?
It costs money to run servers. People aren't going to run your stuff for free
Also we can't tell you what's wrong if you don't describe the problem
Either pay for a good VPS or considering self hosting. Depends on your preferences/scale/budget of course.
when i run the py on cmd it say " TypeError: unhashable type: 'list' "
depending on the bot it might not even need a good vps
just... a vps
It's the discord.utils.get(... line
Actually I'm not sure

so what's the problem'
Is this the entire code
You should get a traceback, not just an error
can someone send me a code for welcome bot?
because i dont understand the problem of my code
Oracle has a free tier.
Also please use slash commands if you are new
They don't have any commands though 
Thx
If you have good Idea I am here for the implementation
Make a bot that tells people what kind of bot to make
Did I cook chat:
if message.content.startswith(“popsicle”):
c = message.channel.name
ch = c.split(“-“)
if “ticket” in ch:
await message.channel.delete()
Why not just make a slash command bruh
also you shouldn't be using channels for "tickets" when threads exist
Correct
Can we have 2 bots pls
yes...?
No like if they need any help from staff
Ppl can create a ticket and it’ll add only the person and staff in the channel
yes. That's what threads are for
Hi i need a bot for a chess server where i can (after the new member cites his lichess username) create a new role with that name and assign it to him with a bot comand. Is there a bot that does this?? Thank you
why would you wanna create a whole role just for one person
run it yourself
Also if you're looking for existing bots, rather than building one yourself, there are better places than a python server. Existing bots don't need to be in python
So that everyone can know the username of others. Or maybe a command that changes the server nickname into the lichess username
Yeah ik sorry about that its just that its the only place i can ask for if theres anyone here that is familiar with existing popular bots
Why can't people just change their own nickname?
Best option might be making your own bot and saving those Lichess names in a DB
there's an authentication workflow so you can get users to login to your bot through lichess
hi, I need help with making my own jarvis from scratch, I have the txt to speech done, I need help making the brain
Is it a discord bot?
run it yourself bro
Hello
ok but didnt ask
thats not very nice..
Did you not learn your lesson from the first mute
what? when did i get muted?
i never get muted in this server before
You did
Matafaka
hello
i need help regarding the hosting
my query is:
that when i use a command in my bot of ?help it does not send any responce
when when i host my bot with same files locally, they work
other all commands are also working on hosting too but only help command is not working
If anyone know please ping me
It's not yet
@celest pelican
!mute 604560333063061505 4h don't insult
:incoming_envelope: :ok_hand: applied timeout to @warm bramble until <t:1759177259:f> (4 hours).
Just ping the role please, not individuals
Ack ack will do, figured you had the context but will use the role going forward sorry!
Wdym
it's a new component that hasn't been announced publicly yet
For modals? 🤔

Is that a Roblox game?
yeah, a private server in the game
Do you know for a fact that it has an API?
Yes
Does it have documentation
yes
but i dont understand it and how to make it into a cmd
Do you have Python and/or Dbot developmenet experience?
So no experience with http stuff I assume
I mean maybe there's a wrapper for it somewhere, you can try to search
nah
There is a Python example to each endpoint
If you need further assistance, I'm here
how do u make it into a working cmd (e.g /erlc command :h test)
However, I definitely recommend using asynchronous methods when using an API
For example if you use httpx (the HTTP library I use), you'd do something like:
import httpx
client = httpx.AsyncClient(headers={"server-key":"YOUR_API_KEY"})
async def example():
response = await client.get("https://api.policeroleplay.community/v1/server/command", json={"command": ":h Hey everyone!"})
data = response.json()
I recommend going over the docs of the library you use to see how to setup your first slash command. There's plenty of examples online
im gonna be honest i js aied it and might see if i can get it from there
sorry if i wasted ur time
You didn't don't worry!
have a nice day
Hi everybody ! I'm sorry if this question has been asked many times before, I haven't been active in the server. I'm making a gacha discord bot, where it generates a random picture based on a discord command, and the user gets to keep that picture. So far, it works great. However, I don't know how to save the data. Everytime my bot goes offline (I can't host it 24/7 yet), data is lost (collected pictures in the binder disappear). I've read that I could use JSON files, but it doesn't seem to work (unless I am doing it wrongly), or I could use SQL. Do you have recommendations?
It's best if you use a Relational DB like postgresql, SQLite or whatever you're comfortable with. Or non relational like mongo.
You can use the db locally if you're self hosting on your machine but if you're hosting on a server or smt you'll have to install whichever db's driver on that too. But that's a lot of work so the recommended way is to use cloud databases, you can check out supabase which has a free tier with 500mb db and uses postgresql
I see. I had started checking out postgresql, but I might as well try the cloud databases, I didn't think of it. Thank you ^^
SQLite is a very good option to get started
My advice is to default to sqlite until you find you need features it doesn't have
tbf I went with postgresql because it seemed like the most popular and liked choice in general. I had tried sqlite3 at school, but I guess I need to see which one might be better, if I were to go with more traditional sql handling, rather than cloud db
Or you can make it database independent by using an orm
orm?
if you don't know sql at all, that's step 0
Object relational mapper, check out what SQL alchemy is.
I do know the queries and the management of tables, but I don't know all of the differences between the relational and non-relational databases
That's a good topic to get a handle on. It's extremely likely your data is relational but it's a good thing to know
I'll keep those info in mind, thanks
Today
What'd be a good DB that fits for very frequent changes (but also for normal paced changes)? Disk based
Maybe I can use aiosqlite, but I'd like to hear some recommendations since I have zero DB knowledge
sqlite is the format, aiosqlite is one option for libraries that interact with it
I personally recommend asqlite instead
Does it offer any specific benefits that you like having? Or is it rather you being used to it or maybe just syntax?
Thank you anyway!
how frequent
asqlite sets WAL mode for you (which you really should have when doing async) and gives you Row objects back by default
and provides a connection pool implementation
If I may know why only disk based
Does anyone have a discord bot templates with many features
Let's say for presence update changes, for example
Tbh one of my "archived" bots that I'm sometimes working on needs that and the others don't
in a server of what size?
I'd like to be able to maintain it for even large servers
Anyway I probably don't need it as I kinda gave that bot up
Hii
making a database query for each presence change can get unwieldy quickly for larger servers. you would need to do some sort of optimization like caching or batching
Yeah..
Because why would I need a DB for memory stuff. I'm not in a position where simply using dicts is not good
You generally do not need to store stuff in a db that's tracked by discord, you're just duplicating data and discord has a lot more money than you do
🥲
Anyway is there a downside of using a disk based DB? Necessarily not for very frequent changes (but edge cases always exist..)
.
...what is the alternative?
stone tablets? 
Comparing to stuff like Redis, unless Redis is called "disk based" too
Where would redis physically put data 
Well yeah you cannot completely avoid using disk
I don't think this distinction of disk-based is what you're trying to get at
Redis (and the like) are caching layers, not databases anyways. It's meant to be used in tandem with a db, not as a db replacement
As far as I know, most databases (SQL type), load "pages" (sections) of the disk data to memory and whenever you make any query, it does most of it in memory than disk I/O, which is why they're super fast.
But databases like redis loads the entire data to memory without needing to calculate which page it needs to load.
But in the end all the data is being saved in the disk
anyways, #databases is probably worth a poke

JSON is not database.
A quick suggestion i can give you, is learning how to use docker, you can easily setup a database running on docker, no need for extra installation on your pc, Amazingly to be able to work in development.
Consider in production you will need to connect to a proper database cluster or locally, i do recommend postgreSQL, I main it, and it's the best in my opinion for long term data storage, and works amazingly for discord bots.
It's a lot easier creating a configuration to connect using Dynaconf package, And to also facilitate your work, you could use ORMs, You define your models, they will migrate / upgrade / downgrade based on how you want.
Using them in your code it's also a lot easier than having RAW sql (or any)
Docker no, I'll consider the other things, thank you
I'm doing perfectly fine with my RPI and its venv
Speaking of virtual env, are you familiar with the tool poetry?
No
Are you aware that within just 1 command installation it will automatically create a venv, not using a basic "requirements.txt" to install each package.
I think most developer here that have a certain level of experience would prefer docker.
UV isn't a host?
Btw, RPI is mostly used for lightweight servers
I don't have such a hard time installing packages, Idk what ur specifying here
Which is exactly what I do (:
It's just to facilitate your work.
UV is eventually faster than pip or poetry.
cd bin
source activate
pip install
ez for me
poetry install works better for me....
But thanks for recommendations
Also a lot easier IMO
Yeah, but it depends a lot over what you're building.
for me, being able to use all these tools as docker, poetry, it's absolutely all i need.
That's great for you
Yeah, i just need something to run properly, not focusing on "speed"
But you're right, UV is ineed better, as far as i know it's rust based.
Gotta love user installs
It's very easy to implement and support, definitely recommend it
i need a free hosting website that auto update from my repo
You don't need it to be free
Is it that hard to just hop in or load jishaku to do git pull
whats that
Jishaku is an extension that provide you some neat owner only commands
Run shell command, run python snippet, test command as other user,...
You also don't need a host or any extension to do this for you. GitHub Actions exist, or you can make a like 5 line command that pulls and reloads things.
teach me
Me when CMD exists 
Maybe except for the last one
will discord slash command ids change or not?
Only if you remove a command and add it back it's id changes if I'm not wrong
what happens if i edit the code of a command?
does it change?
No
will the id stay permanent?
unless you change the name of the command, yes
You should probably test if yourself
it's not going to rotate them randomly, no
ok
I'm not sure if you change the parameters and sync again and the I'd will remain the same or not. But it most probably will change I think
It's the name that identifies the command
Oh alr
There is a version field that changes for other stuff afaik
"In conclusion", I recommend not using a static string for command mentions
But rather find a way to dynamically get it
vercel
Does select work yet in modals? I see on discord.py's website that they added it in 2.6. If I put a select in my modal in the code the bot will run, but when I run the command to open the modal the bot errors
Are you putting it in a label?
I'm not sure what you mean tbh. I was just trying it out with this. If I remove the select it works fine with the text input, but errors out with the select
class modalTest(discord.ui.Modal, title = "poopy stinky"):
testfield = discord.ui.TextInput(label = "input poopy", style = discord.TextStyle.short, placeholder = "not poopy enough", required = True, max_length=2)
select = discord.ui.Select(
placeholder = "Select something",
min_values = 1,
max_values = 1,
disabled = True,
options = [discord.SelectOption(label = "option 1", value=0)]
)
Selects have to be put in a label. You can't just directly add them to a modal
It worked, thanks for your help! I was having a lot of trouble finding recent examples that showed select working in a modal, so this helps a lot. Thank you!
i can use vercel for bot hosting?
nope but you didn't specify this before
we're in #discord-bots but whatever
just go with a vps

Does anyone have a really good template for discord bot. I wanna learn from scratch
How are you going to learn from looking at a template?
I wanna learn from example
Youtube tutorial is way too basic, not practical
youtube tutorials are also wrong and made up
Just looking at a template a) won't tell you the design choices they made to get that code b) help you understand the tradeoffs made or c) even necessarily be "correct"
Can u give me some advice where to start
I'd recommend starting with getting very, very strong fundamental python skills if you don't have them already
you should know things like OOP and async first
Oh thank you a lot!
are u viet
Yes
Im not
whats async?
i know oop is object oriented prorgamming
asynchronous
what is it?
Single threaded way of running a program concurrently
Usually used in networking where there's a lot of I/O and waiting
wow you guys know a lot of words and stuff
my school didnt teach me anything
i wasted like 5 years of my life learning bare minimum
self taught is way better
Schools usually teach you the bare minimum or scratch the surface of many topics, you gotta learn mostly on your own
also ur tag is the initials for my name lol
anyways what is i/o?
Lol it's my dev server
Input output
wait so
do you mean multiple programs?
its probably a simple concept youre telling me about its just i dont know any of the vocabulary us3d
By this i mean: when you send a request to a host, your program needs to wait for the response to be sent back by the server and this time wasted in waiting can be spent on doing something else, that's where async comes in
i feel ashamed to ask more questions
It's alright, I don't mind answering
whats a host
Host is a server somewhere on the internet that accepts requests to it and possibly sending request back too
can you give an example of a request and a request back?
Discord API
well
You send a request to the discord api's server
i mean like
And get some data back
whats api
Application interface
It's a kind of abstraction to simplify the internals of a programs for external use
so what would discord’s api be? could you give some examples?
https://discord.com/api
This is the base URI of the discord API
And over here you can see bunch of endpoints which you need to add to the end of the base url to get it's information https://discord.com/developers/docs/reference#image-formatting-cdn-endpoints
Build games, experiences, and integrations for millions of users on Discord.
ah i see now i looked what api was on google
sorry im bad at wording
i wanted like the definition of api and like what it does and stuff and like an example
Yea there's many different kinds of apis you're better off googling them
i mean
i just wanted the general concept of one
this was very straightforward
Sorry if I didn't explain it well
its okay
we’re all human
me and you
Alr
man i still dont get it
i dont fully grasp the concept of why to actually use one
i dont see why you should use one
Api?
yes
Api = application programming interface, you interact with the application programmatically
Discord API in particular allows you to control your discord bot
Through your code
this doesnt help me
Every api is different and serves a different purpose
Which part did you not understand about that
i dont know man i dont think through definitions i think through examples and reason and logic
You are interacting with discord thru a user interface
Specifically graphical user interface
But since bot dont have senses like you
If you want to understand better you should try working with some simpler APIs and learn about GET / POST requests and stuff
They interact with discord differently
Through python's requests library
i dont know man maybe im just stupid and cant learn normally
if it seems simple to you guys and explained simply then why dont i understand it
i dont know what to ask to help myself understand it more
Try experimenting with this API, it gives you cat facts
They dont understand how api work, not how to work with api
yeah
I still think you will understand a bit better if you actually work with the api
when im given a definition of how something works it doesnt let me understand why i should use it
its like not knowing anythinf at all about a lawnmower and its reduced to a word.
A, using scissors to cut grass: hey B, why should I use a lawnmower?
B: because it cuts grass
A: how does it cut the grass?
B: by using blades, here work with it.
A: i have no idea what im looking at, i dont even know how to work with it and how to know if its cutting grass or not, and i have no reasoning to use the lawnmower instead of the scissors.
If you want to understand how to make your own APIs and stuff you can check out FastAPI
B: here wanna make a lawnmower now?
A: but i have no idea what it even does or anything, its still just a word to me
If you make a lawnmower you get to see every internals, how it works and bit of critical thinking you'll figure out yourself why a lawnmower is better than scissors
yeah but you dont even know what the internals are and you still dont know how the lawnmower actually cuts the grass
you dont know why you should use it either
i cant visualize things in my head API right now is just a word to me
If we're talking about discord API internals or in general any APIs internals, we'll never know because most of them are proprietary code. In general APIs just allow you to access the host's database in a limited form
You won't understand at first why a lawnmower is better than scissors but unless you use both of them you won't know that lawnmower is easier to use. So just start using an API and see how it works right before your eyes
Im trying to deploy a new readthedocs site of my repo and saw that it has pelican as one of the configs. I dont know how to see what the pelican docs look like. Anyone know of any existing repo that points to their pelican type docs?
oh nvm. The actual docs site of Pelican is made with Pelican
gulp
It's like a user interface but for developers.
Let's say there's an API for cat images.
It exposes parts of its underlying system, that is a database of cat images, and enables using them in programs in a cohesive, abstract and (hopefully) safe way for the system.
It could provide a function to retrieve a cat image from its database or even many at once. These two functions may support specifying filters to get images of specific cats or other features like pose, accessories or environment.
This API would set a limit to the rate at which users can access it so it won't get overwhelmed with requests and go down for all users.
Now you get to use cat images in a simple way. You don't know the details and you can't abuse this system, but this is the tradeoff you make.
Alternatively, you would have to set up your own library of cat images and write your own functions that simplify extracting images from it in possibly complex ways.
APIs of online services let you work with systems you don't own (e.g. social media APIs, game APIs, Google Translate API) or can't possibly replicate on your own with limited resources (e.g. satellite APIs, database APIs).
If an API is locally available, it's basically the same as programming libraries or even operating system APIs and drivers.
You may not know how the random module in Python's standard library produces randomness for your intents and purposes, but you can use it nonetheless.
im so frustrated man
i cant understand it logically. i know its a way to get requests from the server/ send them and i know thats what the api is for but i want to know deeper than that and im not getting my answer wherever i go. youtube, AI, even here i cant fully grasp the concept of an API. it just feels like every explanation is vague and explains WHAT it is, but not HOW it works and WHY you should use it.
and if i see one more restaurant analogy i am going to lose it
what do you mean by "how" it works?
Fam it's clear you are more interested in getting frustrated and complaining than actually engaging with the information people are giving you
it is not our responsibility to keep trying random words until we find the combination that works for you. It is your responsibility to engage, think through it, and ask targeted questions on the specific things you don't get
that is absolutely not what im trying to do at all.
this is very insensitive
im just stressed out man
ive been trying to learn for hours i am engaging it just isnt clicking
it's insensitive for you to take that out on people helping for free
im not taking it out on anyone?
im not blaming anyone?
im not saying its anyones fault that i dont get it
im grateful theyre helping. its just im bad at learning
i appreciate the time people take to help others and that doesnt mean i cant express the frustration im feeling
I'm not going to argue with you. But you're not going to get anywhere if all you do is express frustration
not once have you asked a clarifying question that demonstrates you're even trying to engage
that isnt an argument, im not arguing dude
🤦♂️
scroll up
.
if youve actually read what im saying, im not solely just complaining
“all im doing” is not just expressing frustration im literally trying my hardest to grasp the concept of an API.
im not arguing dude
argues
my feelings are hurt and my day is ruined
you want to know how an API works?
i guess, i understand the concept of an API and what it does. but i dont have an intuitive understanding of it or anything
did you try experimenting with an API yet..
i tried the website you gave me and i got very confused on what it was doing
could you maybe show me what its doing so i can understand it better?
what was confusing you about it
let me go back to it rq and ill tell you
lemme pull out microsoft paint
curl is a CLI tool for making requests
you can use any library for making a request
i see
the second image, response body is the main data returned by the server (which is nothing here, idk what you did to do that), response header contains metadata returned by the server. What's metadata? metadata contains useful information about the host's properties like the type of encoding etc
i understood it now its because theres no facts that are 7 letters long, i put something like 70 and it worked
I see
so how does the api interract with the database?
dude this actually made me understand databases way better
they were so ambiguous
and vague
we don't know because the API is not open source, but it's most likey some SQL database
or mongo
well i mean like in general
so an API is a method right
you talk to the API and basically you give it arguments right
and then it uses those arguments on the database to give you what you want specifically
learn about SQL and python's SQLite library if you want to understand databases better
yes
so it would be like
give 3 cat facts
api: ok catfact(3)
api: hey database im going to select 3 random cat facts from you
database: ok
api: ok done
api: hey i got your 3 cat facts here you go
pretty much
basically my whole issue was i thouht it would be more convinent to just pull them out the database, but that can completely expose things that you werent meant to interract with
and also its much more complicated instead of just using an api which gets what you want for you
that's why it's called Application Interface (API), the API gives you an interface to work with it's database or of some sort
disambiguating what a database was solved 90% of my problem
databases itsef is a whole another topic of it's own
yes
i like understand it 75% now. i think if i want to know more then id have to experience an api more
This is the python equivalent of making the request
you'll have to pip install the requests library
cool
bruh
im sturggling tryna debug fucking python
so my main.py links in with my commands folder and all my commands
for some reason it's not working and i literally cant think of why
ive even tried asking another person and they dont know
maybe were both blind
or tired since it is late
We need more details than "it's not working"
In discord.py is there a way to make / commands only visible in one channel? I know I can make them just only work in one channel, but I want them to only appear on the tree at all in one channel on a guild
You can do that from the integrations menu in guild settings
(So not in code but in the UI itself)
Darn, that sucks. Thanks
Technically you can do it via OAuth but that is out of scope for discord.py
Well wouldn't that mean every server owner would have to change it manually? I just thought it'd be more user friendly if the bot did it itself
But not every server has the same channels
Nor would every server necessarily want that behavior
yes, but that's a topic unrelated to discord bots which is the focus of this channel.
you can do that with libraries such as selenium or playwright
sry in wrong channel
Does anyone know anything about JSON files? I'm making a basic counting game where users input a count and increase the count by 1 each new message. If they say anything or it doesnt equal the number it gets removed.
self.count_file = 'JSON_storage/counting.json'
os.makedirs('JSON_storage', exist_ok=True)
@commands.Cog.listener()
async def on_message(self, message: discord.Message):
if message.author.bot:
return
if message.channel.id == 1414445233814634679:
print("MEssage sent to channel")
try:
with open('JSON_storage/counting.json', 'r', encoding='utf8') as f:
count = json.load(f)
except FileNotFoundError:
count = {"Count": 1}
print(f"User sent: {message.content}, expecting: {count['Count']}")
if message.content.isdigit():
print(f"User sent: {message.content}, expecting: {count['Count']}")
if int(message.content) == count["Count"]:
print("It did check if matched the count")
count["Count"] += 1
await message.add_reaction("✅")
else:
print("Number mismatch!")
await message.add_reaction("❌")
d = await message.channel.send(
f"Hey {message.author.mention}, that's not the correct value. "
f"The value is ***{count['Count']}***"
)
await asyncio.sleep(5)
await d.delete()
else:
print(f"User sent NON-digit: {message.content}")
await message.delete()
with open('JSON_storage/counting.json', 'w', encoding='utf8') as f:
json.dump(count, f, sort_keys=True, indent=4, ensure_ascii=False)```
I've been doing some basic debugging but I can't figure out what I did wrong that it doesnt create the count in the file and doesnt add it
im still new to JSONs and im trying to learn
what print messages are triggered when you attempt to start the count?
only
if message.channel.id == 1414445233814634679:
print("MEssage sent to channel")
after that nothing happens
it does detect words that are not numbers and delete them as well
but it doesnt print anything
so nothing with the ```py
print(f"User sent: {message.content}, expecting: {count['Count']}")
but then it should chuck an error
wait could it be becuase im not checking if a count exists
like my other JSON
if user_id not in users:
users[user_id] = {"name": user_name,"level": 0, "exp": 0}```
or no?
my best guess is that opening the file is blocking the async function
you could try to put the loading of the json file in a seperate function and calling it with asyncio.to_thread()
can you try putting a print statement under the with open place
Just don't use jsons at all
I want to keep the count after the bot restarts so I got no choice
They are not a good databas for an async environment, just use a dedicated db like sqlite
You do have a choice
I dont need to use a DB if Im not looking to scale
What
It doesn't have to do anything with scaling, using jsons is just bad, use an async implementation of a database if you want to store data
JSON is pain in the butt, your program get stop for a second while json is being written, your json file get messed
There's very high chance of your json getting corrupted too
using a DB means Im reliant on paying for storage or I have to learn SQL which I dont wanna do
vibe code the db part
JSONs are simple and quick and I can see what goes on
You don't have to pay anyone
You can store it locally
you running the bot by writting run at the end right ?
can you send full script
im using cogs
Bro will do anything but write good code
what does that even mean
if you're gonna insult me for wanting to use what I know then I dont need you're help
stop the beef guys
Nah, I'm just giving you the recommended way to do stuff and you won't do it because you refuse to learn. It's upto you if you wanna do it or not. Just saying that if you continue using your method you'll end up facing even more problems down the road, it'd be in your best interest to fix it as soon as you can
maybe I will but I've tried DBs they're complicated I hated using mongoDB and JSONs have proven to be more simple and reliable
So for now im using JSONs
Try SQLite and aiosqlite if you want to use it in your bot
welp I cant figure it out right now so i'll move on, not a big deal since counting can work without the JSON
I'll just manually update the value if the bot restarts until then
Can you add a persistent button to an ephemeral message?
I heard it's only possible with non-ephemeral messages
My idea was to wrap the button response in a try except (since it expires after 15 minutes). Is there a better way to handle it?
I figured it out
Im so beyond dumb
So the
try:
except; was causing the data to be loaded without caring if it exists
I removed try and excepy and now it saved it
Can you add timeout to ephemerals?
Guys, i just made a simple discord bot. I made it for fun and now thinking if i can upgrade it even more.
https://kakashi-sensei.onrender.com/
Anyone have any idea ?
Wdym
I'm sending an interaction.followup.send with ephemeral=True and attaching a view (button). The issue is that the button in the view stop responding after 15 minutes
Did you set a timeout to have it stop working after 15 minutes
ephemeral (bool) – Indicates if the message should only be visible to the user who started the interaction. If a view is sent with an ephemeral message and it has no timeout set then the timeout is set to 15 minutes.
You cannot keep it running for longer than that
Just set the timeout = None
It still times out after 15 minutes
Yes that is what I did
yeah u can't do anything about that
How can I handle it?
The whole purpose of ephemerals is to be temporary. If you don't want something temporary, don't send it ephemerally
I want it to be private from others
Well that's just how ephemerals were designed, they go away quickly
is there a "discord.py" bot or "d.py" for docs?
Improved syntax for my webhook events wrapper 
Hopefully I'm using this type hint correctly lol (No I don't care that there's no "T" in the name, maybe I'll change it but meh)
Banana
Very secure 
recreate my punishment system I said, it'll be easy I said
json as a db 
my sever aint gonna be large so idc
It has nothing to do about size
thats literally the only complaint that comes with using JSONs
It's not
great argument
You're the one that made the lofty claim that size is the only problem with using json as a database
I didn't make an argument, I just corrected you
The lack of transactions and atomic reads/writes is a huge issue regardless of scale
Easily got into a race condition and then all your data gone
When writing a json file everything inside is cleared, and the whole new data is written into
If another activity that needs to use the json file happens when the last one is still writing, you are gonna have tough time
Better save every x amount of time instead of saving dynamically
But better just switch to a real db
again I dont have time or money to learn a whole new database
my server aint gonna be big and theres not enough activity worth doing all that
so no
I mean it's your choice, but if you're gonna talk about it in a public forum then be prepared for people to tell you how bad of an idea it is
If the afternoon to learn sqlite is more important to you than your data not randomly getting wiped out, that speaks volumes about how little you care about this project
I dont have time or money to learn SQL I barely know discord.py
How do you know how long it's going to take? You conveniently have enough time to do everything else here except the thing that keeps your data from randomly getting wiped out?
SQL is not that hard to learn https://sqlbolt.com/
SQLBolt provides a set of interactive lessons and exercises to help you learn SQL
18 exercises covers more than you will need to know for a discord bot (most likely you dont need joins)
and its free
This is for the best but you can also just learn the very basics from code examples
I don't completely agree with the idea of learning a course for every thing you use
I've looked everywhere online and it says to host your sql db you're gonna pay
from articles I found, microsoft, reddit
if im gonna do all that i'd rather just go back to mongodb cuz at least they're easier to learn
Sure they don't mean the simple fact that you need to have your db stored somewhere?
Huh? but the api worked?
no wonder their role wasn't getting added
been working on this for 2 hours

im not even sure why it was produced my content and embed combined only add up to 1400
probably just gonna go back to embeds cuz this api has caused more issues than it's worth
yeah
The content length is a problem on your side mate
im using a discord POST message API and a JSON to create it
This is the only content i have
So maybe either of these variables was too long (shouldn't be), you should debug (or just print) to see the exact string when the problem happens
🙃
status code of the api
Guys what’s wrong with it?
Show me the payload
I did do everything right
It tells you..
payload?
The json youre sending to the api
ah
body = {
"flags": 32768,
"components":[
{
"type": 17,
"accent_color": None,
"spoiler": False,
"components": [
{
"type": 9,
"accessory": {
"type": 11,
"media": {
"url": member.avatar.url
},
"description": None,
"spoiler": False
},
"components": [
{
"type": 10,
"content": f"Hey {member.mention} welcome to {member.guild.name}"
}
]
},
{
"type": 14,
"divider": True,
"spacing": 1
},
{
"type": 10,
"content": f"We are at **{member.guild.member_count}** members"
},
{
"type": 1,
"components": [
{
"type": 2,
"style": 2,
"label": f"{member.guild.member_count}th Server Member",
"emoji": None,
"disabled": True,
}
]
}
]
}
]
}```
Instead of printing just the status code, you can print the response text. The API tells you what the problem is
oh can I?
Yes
didnt know that was a thing
What http library are you using
Zizzlewizard is a poop 💩
Bruh
tf is wrong now
Also metal is pooopp
You can probably click the button on the right to see full error
not sure I imported requests
You shouldn't use requests, it's not asynchronous
All of u ar poop
Chill bro back to ur cave
Hush
And back to ur toilet
Bro don’t make me racist we are here to learn
Lol no
Btw Golf sea is arabic
K
im going back to embeds, im just gonna store V2 until python supports it
Are you using discord.py
yeah
Tf is the best app for coding in iphone
a PC
w
It supports components v2
You can refer to https://discordpy.readthedocs.io/en/stable/interactions/api.html?highlight=layoutview#discord.ui.LayoutView
But they probably have code examples somewhere
I swear this thing is better than iphone
iphone? probably
www
everytime I use the discord.py docs it crashes my computer
literally only the discord.py docs it's so weird
everything else works fine
Are you talking about something like this?
Cuz I tried the discord.ui.LayoutView a couple months ago and it said it wasn't supported
Get android
Will 🔄
Is this discord.builders? yeah you can use that
yeah
LayoutView hasn't even existed for 2 months yet 
thats my point
it wasn't supported
yeah that's right, it was added a month ago iirc
ah okay i'll try again
like d.js docs bot but python
what version of discord.py are you on
I think 3.11
discord.py not python
I need this tool but for instagram this’s insane
never used instagram
ez money actually
components cv2 support is on 2.6
instagram + telegram u can make ez money from them
yknow what that might do it
They sell Usernames checker for a 100$ monthly
No one needs a job anymore vro
If u make a 400$ in 4h I don’t need anything
then buy a PC
I need to pay for other things bro im living alone
sounds like you need a ||job||
Great
Put my name
put your name where
In the empty space
yall think I should actually learn python?
I learned .py without actually learning the language
If you want to
We can see
Man oh man is there a wrapper of sqlite that does not use string for actions 🥲 I feel like it makes it harder to learn and use
Check out orms like sqlalchemy
Thought of asking that here since at this moment I'm migrating to it in my bot
Define orm
I don't like this whole "IF X IS Y THEN DO THIS" concept
Object relation mapper, it maps SQL syntax to programmitical (pythonic) objects and functions
So I'm gonna assume there's one for sqlite as well?
Are you looking for non SQL databases?
I don't know what I'm looking for. This is my first time using these things
I mean to say I'd rather implement such thing using Python syntax and not a string instruction
ORMs make it so that it becomes database independent, it's compatible with many types of SQL dbs including SQLite and you don't need to change your code even if you change your db type
Alright, guess I'll search on Pypi then, unless you know of a good one, I just wanted to use sqlite because of recommendations
Sqlalchemy
I'll check it out, thanks
User frogs
Indeed
Looks pretty much like how I do it aside from the mapping whatever that means
So the problem is that the interaction token is only valid for 15 minutes. The timeout starts counting from the moment you click the button. After 15 minutes, when the timeout is triggered, it’s no longer possible to edit the button and it gives me this error Error during timeout: 401 Unauthorized (error code: 50027): Invalid Webhook Token
Indeed
But you can fetch the full message and edit that
Unless it's an ephemeral message
It is an ephemeral message indeed
So there is no good way to use timeout for ephemeral messages?
My original idea was to disable the button when it hits timeout, but that’s not possible if the token has already expired
But if they click on it in between (example after 10 minutes) the timeout resets and it will be 10 + 14.3 minutes, which will overlap the token expiration
^ This is the actual issue
If possible
But also, that'll be a new interaction
How would you do that?
See https://github.com/Rapptz/discord.py/issues/9646#issuecomment-1806813704
Or I've also got a base view class where it's an option: https://gist.github.com/Soheab/cfd769870b7b6eaf00a7aebf5293a622
Will using interaction.response.edit_message not work?
Not if the token expires
Ah so it's like that in ephemeral messages huh

You could also track the time yourself and check that and edit when exceeded
Well no, all interactions expire after 15 mins
Sir I know sir
I said interaction.response.edit_message and he said it wouldn't work
But if it’s ephemeral, then you can't do anything with it without an interaction.
Otherwise, you could've fetched it and done whatever.
I mean from the button interaction
Never understood "sir" lol
Sir me too sir
Same thing for non component interactions 
sir
iOS autocorrects "sir" to "die" 💀
Damn
Anyway I meant to say if he plans to edit using the button, he can definitely use response.edit_message
But now I understand that he wants to edit the message in another way
I just want to disable the button
Might wanna just change this UX
You can't edit it after 15 minutes
Why not? Are you sure you know what the function I mentioned does?
It's different than edit_original_response
And as I said, this would only work with the button interaction,
so that's why I concluded this isn't what you need
^^^
Both use the same interaction token
Yep
Sorry. This is all i have to do?
class VerifyButtonView(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
# Absolute timeout to 10 minutes
self._absolute_timeout_task = asyncio.create_task(self._absolute_timeout())
async def _absolute_timeout(self):
await asyncio.sleep(600) # 10 minutes
await self.on_timeout()
self.stop()
async def on_timeout(self):
....
we love tasks
Oh so it's better to use wait for in my case?
Not sure
Wait makes it wait x seconds and then executing the callback to stuff
Your impl executes the callback and then waits to do stuff
Your way of doing it?
class VerifyButtonView(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
# Absolute timeout of 10 minutes
loop = asyncio.get_event_loop()
def timeout_callback():
self.stop()
loop.create_task(self.on_timeout())
loop.call_later(600, timeout_callback)
async def on_timeout(self):
....
Yeah
I guess I will stick to that
self.stop() doesn’t stop the scheduled timeout. After verifying, it still times out the button
Should I use something like self._absolute_timeout.cancel() to cancel the timeout?
your custom timeout? yeah
the view doesn't know about that one so ofc it doesn't do anything to it
Also prevent from flicker (double edit)
Hmh
I need help with my discord bot pls dm me
Just ask your question here
Ah yes the feeling of sitting down to think and write some corny ahh phrases (:
At least they're corny on purpose
I would just ask ai to come with 20 or so lol
I thought of that but holy how corny it was
xD meh, it wasn't so painful to think of them myself
Lmaoo
sigma
@timber dragon Thanks. Here is the result
I think the second embed has some unnecessary text. Personally I'd use a container and add accessory link button to each step
Also "in about" is just odd, why not tell the exact time?
Do you have a check to make sure that the icon that they have to change it to is not the current icon of the user?
Of course
You need a production key for that
Just a different type of application
Ah so it's not that much of an issue (:
Do you think this version is better?
I'd remove the last field. It's obvious
And I would put the "the session..." as footer
I'd wager that getting a production key once and doing an oauth is less work than making your users do this convoluted old school profile juggling
It's more reliable as well
"Hey change your icon to match mine for this game"
How does your embed looks like this? Do you use vencord or any type of that sh1?
components v2
https://github.com/Rapptz/discord.py/blob/master/examples/views/layout.py
https://github.com/Rapptz/discord.py/blob/master/examples/views/embed_like.py
You can check these examples
Thank you sir
components v2 persistent view is possible?
How can i do that?
It works the exact same way as a regular view. LayoutView inherits from View
It’s actually still a good way to keep spam accounts out
Now we need a tutorial for the new modals
There is not really much different about them. There are a few new components but they are quite simple. Is there anything in specific that you dont understand?
...
to keep it related to discord bots im working on this new command
Beside inconsistent formatting for more readability, why is the bot dming people
wdym inconsistent theres no other way to write this
wdym then
The formatting
I think it's fine 👉 👈
2 spaces mixed with 4
No new line separating things - everything is jammed
Class name should not be in all lowercase
The code you sent is hard to read
I dont like camal case
and discord.py is super picky about spaces and uppcase for commands so I just write in all lower case
I used to do camal case for discord.JS
tho honestly its fine I can read whats going on
kid named linter
I use functions and class names to determine where stuff is
Its readable for you because you wrote it
But what if you come back after like a week
Will you remember whats going on
Pascal casing for classes and snake case for variable and function names
That's the python standard
You can read PEP8 to know the complete style guide of python
And use a formatter tool like ruff to autoformat everything for you
Will look into it
python should be more like JS and just stop being picky about indents
its not, the code you shared is just inconsistent
make it easier to make a mistake because you don't know if you are using 2 spaces or 4 spaces this time
it is, it wont work if you dont indent it correctly
JS you can have inconsistent indents and it wouldnt matter
I would still reject a JS pull request with inconsistent indents
let me see if I have any of my old JS discord bots
It wasn't as bad as I thought actualy
?
this is consistent
everything is indented nicely with 2 spaces
actually your js code is pretty nicely formatted
why don't you apply it to py
I worked with other people to make it + thet sent me sections
I can't imagine how much worser your code would be if it let you be even more inconsistent than you already are
Even then python is still lenient with how much spaces per tab it allows, as long as you use the same amount of spaces/tab under each code block. It considers it valid. This allows you to have different number of spaces in different code blocks (which is what you're doing)
its just how interpreted language works, same indent level = same block of code
Thats not related to it being interpeted
hello im new to python
Hello
why chatgpt doesnt want to learn me how to steal discord tokens with python?
im kinda sad
i got hacked like this once and im curious
because its against tos
i just wanna know how it works not to use it
i want to know how to do a crime to not do a crime
btw can i use python for in hacking
You can use any language for anything including hacking
what if i wanna make some to hack ingames
thats cheating
Read the server rules, we don't help with illegal stuff
you wont get much help then, due to in most case cheating is illegal
i just wanna know how it works so in future i can help with anticheats or something
Google is your best friend because we still can't help you
oh okay
same excuse
every cheater had to cheat to know how anticheats work


