#discord-bots
1 messages · Page 415 of 1
With some of the new laws popping up I think it could be very possible
i was talking about discord dev policy like infernum said just to be clear
how does shards work?
its like running multiple instances of the bot so that one instance of it isn't handling every single request, it's mainly good for large bots that get lots of traffic
so is the shards thing custom? like do i have to code that into my bot
It's only mandated by discord once your bot reaches 2500 guilds, but libraries such as discord.py support custom implementations. They also have built in solutions but I've never personlly used them
and the docs say that "It is recommended to use this client only if you have surpassed at least 1000 guilds."
In discord.py, your bot uses AutoShardedClient by default. So unless you want to get advanced, you don't really need to implement anything
AutoSharded is not a default, that is very much a conscious decision
Oh I thought it was default, my bad
So from reading the docs, if your robot is connected to +2500 guilds, it is commonly hard to handle all these events with one connected socket. So discord allows to shard, one shard is a gateway connection and kinda routes the events to guilds 1-5 and another shard is routes the events to guild 6-20 as an example. This is to scale your bot and make it more efficient. So to sum it up, sharding is like to have multiple gateway connection to handle the events from multiple guilds your robot is connected. Hopefully this is well explained, I am open to feedback and corrections
That's correct yeah
learning about the concept of "cog". Really nice implementation to write clean code and modularize code, Astonishing!
Cogs have nothing to do with files
Ye it's nice when you're beginner and you get to organising that 5k lines monstrosity you had (at least that's how it went for me 😅)
I made an event on_member_join(member) that takes the parameter member. https://docs.nextcord.dev/en/stable/api.html#nextcord.on_member_join
Really nice to read and learn
Personally I just import command funcs from other files to the main. What are the benefits of using cogs? (genuinely asking)
command grouping, cog level handlers like on load, disabling a whole group of commands by just removing that cog, error handler, checks, some group command/group cogs are also present now (basically it's the utilities that come with cogs thats invoked internally by the library is whats helpful)
It really depends what you're importing. You can utilize extensions without making a cog
I import the funcs that take discord.Interaction
I handle checks either manually or with decorator
I mean any function can take an interaction 🤔
Yea ur right, I'm talking about command functions in particular
You don't need to import to add commands to your command tree
That's one of the main points of extensions
Ik, I have them in different files to not have a big mess
Unless you meant something else
You don't need to directly import to use other files, either. That's what extensions are for

I have a small but Important question. Does enabling all intents influence performance on the bot, so always enabling intents that are needed and used?
idt they are using extensions, they are probably loading the commands/functions in manually?
are you using load_extension and have a setup function defined?
Yes, it influences performance. There's no reason to request intents you're not using
yes I do that now. I have a cog folder and there is a py file called events
was meant for serverit :p
sry
np
No, I just import the func and call it lol
@bot.tree.command(...)
async def whatever(x)
await importedfunc(x)```
I don't think they're using extensions, I'm suggesting that they should
Mhm
also a concept, advantages and disadvantages?
oh yeah you should use extensions/cogs
Idk it's what I've done since I started using dpy 
Perhaps when I make a new bot lmao
I'll check it out
Is there a helper function for Template in dynamic items or do I gotta memorize the basics of Regex xd
well i wouldn't say it as an advantage but in a sense this impl abstracts all command logic to different files and leaves only all the command interfaces/contracts in one main file so maybe easier to browse list of commands from code lol?
Yea I group my commands in files by category
you need to define the template by yourself
recursion

I dont understand this to be honest but maybe I am beginner in discord api
i dont either
mention is just a name i gave it
why do u need it tho
Idk so far I've used it here and there
!d discord.app_commands.AppCommand.mention
property mention```
Returns a string that allows you to mention the given AppCommand.
maybe cogs are the best way to handle all the code and modularize I dont know
take and use what is given and make something with it.
Easy to miss stuff with how big the api is
good to know that a group of many people contribute to the libraries and update it
I could not make it myself to be honest
Was also wondering, am I supposed to define on_message once and then call whatever funcs in it? or
dosent the interaction.command return app_commands.Command object? does that have mention too?
!d discord.app_commands.Command
class discord.app_commands.Command(*, name, description, callback, nsfw=False, parent=None, guild_ids=None, allowed_contexts=None, allowed_installs=None, auto_locale_strings=True, extras=...)```
A class that implements an application command.
These are usually not created manually, instead they are created using one of the following decorators...
To be correct, the gateway and the api are two separate things. I can use one and another to communicate with discord
Each one has a different purpose
got it
You can also make bots that don't use gateway
- gateway is how discord communicates with your bot
- the api is how your bot communicates or performs some action with discord
Two separate objects; Command is just a local representation with the callback whereas AppCommand is the metadata including what discord tracks (like the id)
You can fetch the commands from discord
Well I'd rather cache them on startup than sending request each time
!d discord.app_commands.CommandTree.fetch_commands
await fetch_commands(*, guild=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Fetches the application’s current commands.
If no guild is passed then global commands are fetched, otherwise the guild’s commands are fetched instead...
I'll just simplify my method to use command.mention I guess
I take the ids from tree sync
do the libraries cache some informations like channel id, role id, user id to not always send requests and slow down the performance?
This works but you don't need to sync constantly
Nah only on on_ready
That's the worst place you could be doing it
bot.loop isn't documented and you don't need it when asyncio.create_task exists
fair
So I may just put it at global level ig
just make a one time task
You should only be syncing when you need to, which is something you as a developer decide not the application
some stuff is cached but it may be unreliable or a cache hit may miss so you should always fallback and make a request if the cache returns None
Would hard disagree except in the case of sharding and referencing things between guilds
I have currently a cog folder and there is a py file called events. If someone can evaluate this: ```py
import nextcord
from nextcord.ext import commands
class Events(commands.Cog):
def init(self, bot: commands.Bot):
self.bot = bot
@commands.Cog.listener()
async def on_member_join(self, member: nextcord.Member):
await self.bot.get_channel(1405632225063600208).send(content=f"A new Member joined <@{member.id}>. Welcome to the server and have a nice stay!")
def setup(bot: commands.Bot):
bot.add_cog(Events(bot))
how would you know if some object is cached or not? you would still need to check the cache if its present?
I'd ask for what the case is when that object isn't cached and 99.9% of the time that's a development mistake and not an expected event
hence like
user = bot.get_user(...) or await bot.fetch_user(...) # fallback
Different use cases I'd say
Because fetch gives you more data doesn't it
Anyway I never experienced cache failing
There's I think one case where it gives you more (user banners)
like prior to the chunking and cache has been entirely populated?
From experience, everyone who's trying to access the cache prior to chunking is doing is accidentally and not by design
hmm fair enough ig i still prefer having the fallback just in case
hi
The main issue with the fallback is that in a vast majority of cases, it's due to a coding mistake and rather than fixing it people eat into their rate limits and performance (silently)
hmm i usually have these in my command bodies so for most part i should be good but yeah maybe log a warning statement next time
If people log when the fallback happens and commit to digging into it, sure, but I have yet to see someone do that
I might finally have usage for /applications/detectable lol
Was thinking about making a bot mainly for finding "teammates" for games you play, and caching games' app ids is something I might do
yeah lol usually the rate limit isn't a concern for smaller bots and idt the fallback is triggered unless someone messes with cache or does something weird which is rare too
But it depends
For game info, I might just use the external API that Discord themselves use
or I can get game description from applications/id/rpc
Not such a big deal
I have many ideas for that bot but might not do it because it'd be absolutely useless if not enough people use it 🫠 not the first time I abandon something for that reason lol
mhm
Is there a way to optimise how embeds look in mobile discord ? It’s different in pc and mobile
Not sure what you mean by "optimise"
Your options are fairly limited though, it's really just the fields on the Embed object that the libraries give you
All you can do is specify the parameters given to you. If discord renders them differently, that's discord's choice/fault
could send an image but that will be heavy and make no sense
True
Can someone explain to me difference between
for guilds in bot.guilds:
and
for guild in bot.guilds:
? literally no difference except the variable name
Oh wait it isn’t a keyword
Yeah mb.
I just @vagrant depot
All good 
This should be better
😄
Plus this
If I want to use variables from bot.py in an ext cog, would I import them normally or would I do bot.x = ... and then use the bot in the cog?
How are you using it in your extension?
You can use interaction.client to get the bot object. You don't need the cog to store it
But either works
I'd recommend the former
if you have a bot subclass then interaction.client requires a bit more typing
otherwise your type checker may not pick up extra stuff you've added onto it
Well that var will show as Any
ah wait
I do subclass the bot
So I shouldnt do bot.x but rather self.x inside the subclass?
how do you use bot.x if youre subclassing the bot itself 🤔
self.x is the current class' attribute x
bot.x is (whatever the bot instance is)'s attribute x
when youre subclassing Bot, you don't have access to the instance
so youre question doesnt make sense
Yea I mean at global level

self.x is not at global level
Actually nvm would be irrelevant wouldnt it
can help to prevent bugs
I know, bot.x is
so why are you asking if you should use bot.x or self.x
What should be in the extension file for it to work?
Just command def?
can be whatever you want. An extension is only a module that's given a reference to your bot object
So load extension takes whatever funcs or classes (that take bot object) that it finds there?
all load_extension does is import the file and run the setup function
Ah so I'll still need to have a single class that holds everything in the ext?
no
Im sorry if I ask stupid questions but I just wanna be sure
an extension can have 0 classes or 100 classes just fine
the only requirement is that it has a top level setup function that takes in the bot. Anything else is entirely up to you
await bot.tree.sync() returns app_commands.AppCommand, right?
Well then can I access children of that command?
There's AppCommand.mention but that's just mention of top level, and I need of all other levels too...
AppCommand is the API object and the api puts subcommands/groups in .options
So you'll need to parse it from there
it returns a list of appcommands
Yea meant that
Or you could use an implementation like the following that handles the caching for you and has a method called find_mention_for that can get all levels deep
https://gist.github.com/LeoCx1000/021dc52981299b95ea7790416e4f5ca4
Or I'll do this and pray that it works
xD
🤢
Why is the dict named like a constant
And why is that a private method like someone is not supposed to call it
thats an insane reaction 💀
yo 2.6.0 is out
with v2 components support
In the setup function is use, bot.add_application_command(callback_function)
im doing my best xD
^
A new version of discord.py just dropped
Bout time ✌🏻
any1 know if its against discord tos to store message data in a database? I would look it up but i dont want to
It can be if you don't follow the rules
You should read the tos you've agreed to. It's your responsibility if you're handling people's data
but like, im doing it for educational purposes or something
" including the European Union’s General Data Protection Regulation (GDPR) and the ePrivacy Directive, the UK General Data Protection Regulation, Brazil’s Lei Geral de Proteção de Dados (LGPD), the California Consumer Privacy Act (CCPA), and the California Privacy Rights Act (CPRA). You will provide and adhere to a privacy policy for your Application that is compliant with applicable privacy laws and clearly, accurately, and fully describes to users of your Application what data you collect, how you use and share such data with us and third parties, and how users can request deletion of such data. For the avoidance of doubt, how you use data includes how you access, collect, store, retain, transmit, share, and otherwise process it. You may only use API Data in accordance with your privacy policy, applicable laws and regulations, and the Terms. You agree that your privacy policy may not and will not supersede, modify, or be inconsistent with the Terms, which will supersede if there is any conflict or inconsistency with your privacy policy. You will maintain publicly available, up-to-date links to your privacy policy in the Developer Portal and make it easily accessible to users from your Application."
Is the tos I dont know what these countries laws are and im really not feeling spending a year to research it
GDPR is a practical act with various principles. Mainly you don't collect any more information from people than is necessary and lawful, and anything you do collect, people have the right to access and see that you have, and have the right to request that it be erased from your application, also obviously informing and consenting to having personal information collected too. I don't think just collecting messages on discord and saving them without peoples consent is very lawful, and there can be a lot of personal information in messages with what people share online, where they generally don't expect someones bot to be saving them. If you want to save messages for educational purposes then do it in a server with your friends and tell them you're doing it, or do it in your own server, or have people opt into it and be very clear about it.
Apply the golden rule and it's easy, don't do with other peoples data what you wouldn't want done with yours.
anybody willing to help me with making a bot?
i tried making one and it was going alright until i reached my message limit on chatgpt 🥀
I would sugggest you use chatpgt if you already know the library and the language itself. Chatgpt is not bad as always said for coding help, but you need to understand the code line by line otherwise it makes no sense to work with chatgpt
i just started about 2 days ago bc i got influenced, i dont really know anything about coding
interesting
i would use chatgpt consistently but it always finds one way to mess up like it did for me tonight and then the message limits dont help either, i have to wait until 2:51 or something tmr morning
to be able to send the next message in that chat that has all of the past questions and steps its given me
thats why i asked if someone could help me bc i know exactly what i want it to do i just dont have the brain power to put it in place
id love to learn tho
yes goood
but where is the question
https://fallendeity.github.io/discord.py-masterclass give this a read
A hands-on guide to Discord.py
i will thanks
hey asher, I am currently working on an approach myself
with regards to?
with regards to the gateway. I looked into discord.py github and they use a library called aiohttp
the library has a built in websocket
right
so far my console prints out this: {'t': None, 's': None, 'op': 10, 'd': {'heartbeat_interval': 41250, '_trace': ['["gateway-prd-arm-us-east1-b-qr22",{"micros":0.0}]']}}
do you know if pycharm would work? thats what ive been using so far idk if theres a difference between whats on that and pycharm
ide makes no difference
use pycharm I am using it too
ok thanks a lot
jetbrains makes good products
yea thats what ive heard
I'd recommend VSCode with Python extensions
vscode also good
yeah thats an event from the gateway in your case it is op: 10, which stands for HELLO
Internal stuff which you shouldn't care about xD
yes, but there is much more to do in order to remain a connection
Of course there is
sending an identify payload and maybe make a background process to send heartbeats to say discord I am alive
when you get the HELLO subsequently you are supposed to send a heartbeat every heatbeat interval, thats what tells discord ur bot is alive and online
indeed, my thought is to make a thread just for the heartbeat or is this not a good approach?
thanks, I am so hyped for this. But just a reminder, it is just an approach not to make a library
cool :)
You want to change the lib's logic 🤔
no
its just learning by implementing

good approach to have
as long as you dont keep reinventing the wheel, and work on ur own stuff too
the discord api so extreme, discord.py has +400 contributors
and the maintainer danny is a hobby programmer
so look what humans are capable of making
If you want you can have a look at the internal modules discord.gateway and discord.http
To see more of the gateway logics
thanks
Where can I find the changelog?
Thanks
hello there
i made a bot that checks messages for user IDs
and apparently it doesnt work for forwarded messages
Forwarded messages do not have any content, you should check in the message snapshots.
There are various other things that would not work if you only check the content. Such as embeds and components
wait so
they dont work like normal messages
ok lemme check smth
thanks
ah yeah i see now
No, forwards are a message that contains another message (but only some not all of the data is there)
👍
i see
so to fetch a part from a forwarded message (like an user ID for example), id have to utilize message.snapshots instead of the normal message.content right?
Yes
to the docs we go
uh so
im unable to get username from id
bot.get_user(user_id_input).display_name
i get this error
AttributeError: 'NoneType' object has no attribute 'display_name'
@shrewd apex so far I have this. I am not sure if this is a right approach. did I use create_task() correctly, is it that what you meant? ```py
async def sending_heartbeat(ws, interval):
await ws.send_json(HEARTBEAT_PAYLOAD)
await asyncio.sleep(interval/1000)
async def main():
session = aiohttp.ClientSession()
async with session.ws_connect(url="wss://gateway.discord.gg") as websocket:
hello_event = await websocket.receive_json()
interval = hello_event["d"]["heartbeat_interval"]
print(hello_event)
asyncio.create_task(sending_heartbeat(websocket, interval))
await websocket.send_json(IDENTIFY_PAYLOAD)
while True:
response = await websocket.receive_json()
print(response)
asyncio.run(main())
get_x methods will return None when that item wasn't found in cache. You're looking for a userid your bot can't see
Means user isn't cached
You'll need to use await bot.fetch_user(...) which is an API call
A vast majority of the time you should be fixing why it's not in the cache rather than trying to fetch
What would you need to do tho 🤔 I don't think this ever happened to me
The most common reasons for this are
- You're passing in something that's not a valid id (like a string), which you should fix
- You're not subscribed to the relevant intents, which you should fix
- You're trying to access the cache before it's populated (ex during startup), which you should fix
I'd assume there'd be a ValueError for 1st one
nope, it just returns None
TypeError*
Alright
can I say that discord has for every object user, channel, server, message ... an exact id?
Yes
Btw your id is more than just a number
further?
Timestamp, worker ID, process ID, increment
in one id?
Yes, the timestamp being how you know when a user created their account btw (: since it's not in the /users/id response
nice, I need to read about it, but also for me it is a little bit complicated. The id's are called snowflakes if I have it
right
Yes
How the snowflakes are generated is entirely an implementation detail as you will never be making one yourself. All that matters really is that they're globally unique
ah ok got it. so no double id everything on discord app is a unique id that refers to an object?
Yes
interesting
As a matter of fact discord.Object(id=...) uses this concept
Well obviously everything uses that concept, but yeah
well done discord!
You'll need to use Object when for example passing guild to, let's say, sync() (iirc)
but yeah that's unrelated to the api directly, just a dpy implementation
Quick question, what method in guild object uses this request?
In dpy
Oh... I don't actually even know how a user gets cached
okay thank you I'll try that tomorrow
the Object class is useful in methods that require you to pass objects that represent discord models, in some places instead of passing a whole object the library allows you to pass an Object instead, saving you from retrieving the full object from cache or from the API
that's the main reason why that class exist
this is "chunking" afaik, when you get all of the members in a server

why not fetch if it works?
So the cached guild.members is unrelated then, good
Because it's slower and you don't want to send requests too often
yes that's correct
ah haven't yet personally experienced slow being much of an issue
mosf of the ratelimits normal bots experience are coming from channels and messages related operations
(in the past i was testing like a dummy and was hitting PUT /commands (sync) too often)
((:
Never got another rate limit besides that
iirc that endpoint has 1d ratelimit
most likely you always sinced instead of doing it only when needed?
That's Guild.query_members
Nahh
No i was just turning the bot on and off fast 😭
And I have sync on startup
I mean by doing that you are sincing every time you start it up again
yea
There is a global rate limit of 200 application command creates per day, per guild
Is there a check decorator for @discord.ui.button(...) ?
Like @app_commands.check(...) but for ui items' callback
!d discord.ui.Button.interaction_check
await interaction_check(interaction, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A callback that is called when an interaction happens within this item that checks whether the callback should be processed.
This is useful to override if, for example, you want to ensure that the interaction author is a given user...
ig you could write a custom decorator
So this happens by default?
yes, unfortunately the ui decorator doesn't let you pass a function for the Interaction check
So I'll need to re-def it?
so you either subclass the Button class and override the Interaction_check method or make a custom decorator that lets you override the Interaction_check by just passing a function
like what, discord.ui.Button.interaction_check = custom ?
nuh uh
ah for that item specifically
yeah, I'd go for the custom decorator
How'd the custom decorator override that tho
I mean you could do that but that's monkey patching the lib at that point which I don't reccommend because if you forget that you are overriding the Interaction_check for every possible button in your code base you might think that there's a bug
it would look like
async def foo(inter):
...
@button(..., check=foo)
async def callback(...):
...
ideally
oh a whole new button decorator..
is it
Would rather make a separate decorator just for check, if possible
You could also just put that in the body of the callback
why?
Is it necessary if you use ephemeral?
I doubt it 
oh true
but it's ugly
interaction_check is not used only to check if the author of the Interaction is also the command executor yk
that's the most common usecase tho
I don't have a real good reason besides syntax. 
Ok I see now, I can make a decorator for the whole subclass
Then it can override interaction check
or you could just implement interaction_check?
you don't need a decorator to do that
Which would be doing item.interaction_check = custom within every item subclass?
no, implemented on the view class itself
then it will apply that check to all interactions on that view
So this but with view class?
How's that done, I just don't understand from this
class MyView(ui.View):
...
async def interaction_check(self, interaction):
return True #logic goes here
Ahh oops alright then
But nah I don't want to just put it there in every view xD
Anyway this isn't a big deal
So all of your views apply this check?
You can declare a parent view class and have these other views inherit it
Yup. You can implement interaction_check in the parent class, then all of the children classes will inherit it
I do this to do central error handling, for example
Alright, I'll need to find a similar thing for dynamic items as well
chat ts isnt making any sence to me after the 2nd page 🥀
If you don't know basics of Python then obviously it isn't
You shouldn't skip to making dbots, get the basics first
thats the one he sent and said read through that so i did
about to pay someone to make this bot fr
Currently I use check to send error if user isn't the right user, and if the bot misses required permissions
Planning to implement specific response if i toggle "maintenance mode"
every time i made a bot in python there is this problem with the intents and i have to spend 5 minuted to find the solution , and randomly the bot doesnt take input from users anymore smh
Intents aren't "random" 🤔
I mean that guide + discord.py docs should be enough to get you ready
did you read the views page, I wrote that shit 😭🙏
chatgpt helped me out more then that did
I think he should get into Python generally first, this is a rabbit hole
yeah
cant use chatgpt anymore tho bc i reached my message limit
chatgpt thinks 3 isn't a prime number sometimes. It's stupid
it's stupid but that's not a valid reason to say that it's stupid
it just can't do it right
.
where would i even get into that like are there guides you recommend
But maaaybe I can "help" making it, depends
anything of that sort
Do you have a way to host the bot?
chat what does that mean 😭
bro fr you gotta dumb it all the way down when talking to me about ts
Your bot has to be hosted on a server to work
Just like websites
Even if I made the bot's code for you: what's the point if you have no way of hosting it
ohhh yea im trying to make it work out of a server that i run
Oh you have one then
si si
its kind of a lot well for me at least
well im gonna have to if i want to get help
and its no secret really i dont mind
may want to review the #rules
Yep no promotions etc etc ✌🏻
Anyway count me out if it's multipurpose or music or moderation
non of that
i need it to store data basically
when someone runs a command like "/profile" i need it to come up with a list of what that person has in my case it would be awards, badges, rank, roblox name and a few others
I don't have good database knowledge
JSON is an option but not recommended for large scale
but it has to store everyones lists of things and i want there to be a website or something so i can manage and see what everyone has outside of discord
not thattt large, over 100
do you know anything about what im trying to do?
The core code would be pretty simple. Incorporating it into a website and hosting that is another step
well honestly idk if its a website bit or not
it might just be like an html thing in the program they use to edit if needed
I use it for small projects honestly
if that makes sense
Sure, so are you gonna build it?
i have no clue how to
Are you gonna learn how?
id like to
i dont know what id even search for thats why im asking you guys
guidance is what i need
the python tutorial is quite good, the official one
does it go over what im trying to do?
it's the basics of the language
ah i see
then you go again to read the guide that was linked a lot of messages ago
that link is discouraging 😭
You can also search code snippets instead of learning from scratch
Learning the entire logics of a library is useless, but there are some things I'd recommend going over
code snippets are??
just pieces of code?
Yes
i see do you know of a website?
ill probably just have to search around for a little to get what im looking for
just "SOF"?
And you can use ChatGPT for very basics, but don't rely on it
But don't "be shy" to do it if you need to
i gotta wait until 5:41 to type agian 🥀
StackOverFlow
Hard disagree
I mean that guide is mostly code snippets

chat so uh i need help agian

local_cache = {}
keys_available = []
async def id_to_global_name(user_id: int):
if user_id in keys_available:
username = local_cache[user_id]
log_message(f"Found {user_id} in cache")
return username
else:
fetch = await bot.fetch_user(user_id)
local_cache[user_id] = fetch.global_name
keys_available.append(user_id)
log_message(f"Couldn't find {user_id} in cache; appended in cache")
return fetch.global_name
this good?
i need to assume that the bot variable there is instance of discord.Client
you would want to not override assigned key values in local_cache by checking if the key already exists, but i am not sure what is intention in your case
i will be honest, i code a discord bot myself using python
yea it only appends new keys when they're not found in keys_available
I was told that using bot.fetch_id() too often isn't nice but since bot.get_id() mostly returns none so i made this method
tbh i havent seen something this before! well, fetch_user() is good approach there, you receive instance of discord.User, get user's global name and assign it to local_cache with user's id as the key, append the id to keys_available (this will affirm it is now in this list so the if statement will be invoked after the next invocation of this function), you receive the global name from local_cache, print the message it was found and return the global name. all you want is to append and receive the user from cache
i think you should be fine
without caching this will be just (await bot.fetch_user(user_id)).global_name
also i could tell, you can use alternatives for if statements that you wont need to use keys_available variable:
# 1
if local_cache.get(user_id, None) is not None: ...
if type(local_cache.get(user_id, None)) is int: ...
if isinstance(local_cache.get(user_id, None), int): ...
# 2
if user_id in local_cache: ... # in dicts, the 'in' keyword inspect dict keys, not their values
i personally prefer version with get() over one with in keyword
if you want to receive a list of keys, you can just do list(local_cache) or list(local_cache.keys())
Why do you use both a list and a dictionary?
also i could tell, you can use alternatives for if statements that you wont need to use keys_available variable:
# 1
if local_cache.get(user_id, None) is not None: ...
if type(local_cache.get(user_id, None)) is int: ...
if isinstance(local_cache.get(user_id, None), int): ...
# 2
if user_id in local_cache: ... # in dicts, the 'in' keyword inspect dict keys, not their values
i personally prefer version with get() over one with in keyword
if you want to receive a list of keys, you can just do list(local_cache) or list(local_cache.keys())
My version
local_cache = {}
async def id_to_global_name(user_id: int):
username = local_cache.get(user_id)
if username:
log_message(f"Found {user_id} in cache")
else:
try:
user = await bot.fetch_user(user_id)
username = local_cache[user_id] = user.global_name # Use user.name, or user.global_name or user.name if you must
log_message(f"Couldn't find {user_id} in cache; added to cache")
except Exception:
log_message(f"Error fetching user {user_id}. Retrying in 30 seconds.")
await asyncio.sleep(30)
return await id_to_global_name(user_id)
return username
why do u need a local cache once u fetch the user won't it be present in the library internal cache?
Also I would use user.name instead of user.global_name because it's not guaranteed to be set by the user
also for most part the user should exist in the library cache already you can just try get_user
Use user.name, or user.global_name or user.name if you must
True, I don't know what the code is being used for, but the optimal approach would be to use getch
user = guild.get_member(user_id) or await bot.fetch_user(user_id)
get_member not get_user it will only be cached if they are in a mutual server
but they both return different objects
Oh right nvm
how do i make a discord bot that will launch a tactical nuke at the user when they do/self-destruct
Tf?
You can use get_user across all guilds etc I forgot my bad confusion
No fetch doesn't add it to cache
hmm rip i thought it did
In that case, I would use
user = bot.get_user(user_id) or await bot.fetch_user(user_id)
Probably add a try/except
Realistically, you shouldn't need this as all users sharing a server with your bot should be cached as said above if the members intent is enabled
But if you do want a getch behaviour, you should try the lib cache first and then fetch. I'm not a fan of the local cache but I guess it's fine if you keep it updated (like via events). Here is my take on it: https://mystb.in/ad7ad079523fd5405f (not including events)
Rip indents
Check line 20
But otherwise I like it
Fixed
you just do it
hope that was clear
wrong message
you just do it
so helpfull thank you
you're welcome
thanks brother I think you are exaggerating a little bit
@astral jetty Wrong server
lebonbon
oh right I forgot I'll need to keep it updated
Just did whatever came to my mind first
Yea but most people have numbers and underscores in their name which can look ugly
anyways thanks yall
ive been trying to make a bot but its not going so well
How can i do 3 buttons in a embed in nextcord?
You can't put buttons in an embed. You are probably talking about containers.
anyone want to help me make a bot from scratch
It does not look like nextcord supports containers yet (which is part of components V2)
can bot.wait_for not detect messages at a high rate?
im trying to read every message sent in a thread, but bot.wait_for seems to be ignoring some messages when i type too fast
What's the code and what behavior are you trying to accomplish?
!paste your code
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
How would I set the row to be somewhere specific rather than top level?
I see that this is possible, but then where do I define callback? Assign button.callback = callback?
You can subclass Button and implement the callback there
You really should avoid stapling methods onto generic objects when possible
uhh alright
Or subclass ActionRow
I need help with the intents, because I dont understand the calculation. SO far I have subscribed the basic intents with the number 513
ok, they are in bits which can be converted to a number and then be added up?
Idk but they're all listed here https://discord.com/developers/docs/events/gateway#list-of-intents

You can send anything you want, just not cv2 + embeds/content
maybe im tripping holdup
ohhh i am thats why oops

Containers?
Containers are one of the new message components added a couple months back
Yeah i mein this type of components
"low level" 🤔
That's a next level low
xD
How can i install it
Should probably ask in their server
!d discord.MessageSnapshot
class discord.MessageSnapshot(state, data)```
Represents a message snapshot attached to a forwarded message.
New in version 2.5.
!d discord.MessageSnapshot.content
The actual contents of the forwarded message.
Can someone help? I used disutils.command.config in python 3.10 now i Switched to 3.12 and it is not supported anymore
Traceback (most recent call last):
File "/home/container/main.py", line 266, in <module>
bot.run(TOKEN)
File "/home/container/.local/lib/python3.12/site-packages/discord/client.py", line 929, in run
asyncio.run(runner())
File "/usr/local/lib/python3.12/asyncio/runners.py", line 195, in run
return runner.run(main)
^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.12/asyncio/runners.py", line 118, in run
return self._loop.run_until_complete(task)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/local/lib/python3.12/asyncio/base_events.py", line 691, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "/home/container/.local/lib/python3.12/site-packages/discord/client.py", line 918, in runner
await self.start(token, reconnect=reconnect)
File "/home/container/.local/lib/python3.12/site-packages/discord/client.py", line 847, in start
await self.connect(reconnect=reconnect)
File "/home/container/.local/lib/python3.12/site-packages/discord/client.py", line 727, in connect
await self.ws.poll_event()
File "/home/container/.local/lib/python3.12/site-packages/discord/gateway.py", line 658, in poll_event
raise ConnectionClosed(self.socket, shard_id=self.shard_id, code=code) from None
discord.errors.ConnectionClosed: Shard ID None WebSocket closed with 4004
this normal?
cant remember for sure, but i think 4004 means discord revoked your bot's token
is this running in replit? discord bots there tend to get ratelimited
I forgot I reset my bot token and after I put the new one in it works now
Yep, it was token invalid
I did reset my bot token and I forgot, after I put the new one in it works now
that link you sent didnt do me any justice
i think it was you idk it mightve been the other person
rip
im just tryna make a functional bot 🥀
and where are you struggling?
from the start really
i just cant figure out how to do it and something always ends up getting messed up by chatgpt
why using chatgpt?
bc idk how to code
i dont even really know the basics
so are you ask chatgpt to teach it or just using it?
im just trying to get a bot set up and thats all i need
just to show me what i need to do
what scripts i need to put and stuff like that
i mean it teaches me a little bit until something goes wrong and i have to reset
and that'll keep happening till the time you decide to learn from the proper sources
chatgpt is not a learning tool
ik its not im not really trying to learn im more of just trying to get the bot
i obviously have to learn hoe ti make it but im not planning on doing coding and programming consistently
Doesn't matter
If you want to make it yourself you'll have to learn how to do it properly
thats kinda why i joined this discord to see if anybody would be willing to help me make it
We help with learning how to make it so you make it yourself
Why is the "Done" button not working?
discord.errors.NotFound: 404 Not Found (error code: 10008): Unknown Message
https://paste.pythondiscord.com/PROQ
Don't use interaction.message basically ever
You can use interaction.response.edit_message
That + followup for my case?
Yup
I only ever use it for interaction metadata to know whether interaction.user is the original user
I just don't know of a better method. Is there?
"Original user"?
The one that ran the command
How would interaction.message give you that?
interaction.message.interaction_metadata.user.id
You could pass the user into the view to simplify that but that could work

My second question, is my code tied to each user’s button? I don’t want different users interfering with each other’s buttons
(still new to the buttons thing)
Even with ephemeral True?
No, that's different
Only you will see the message, so only you will be able to use the button
I still don’t want one user’s verification to disable the button for other users, as if they’re sharing the same instance
I'm a bit confused about this part
Do you want it to be so only the user who ran the command can use the button?
Yes it should create their own instance only for them
So just send ephemeral messages
Put instances outside of this lol, that's not really related
Anyway yeah you either make the message ephemeral, or add logic to check if the interaction.user is the one that's supposed to use the button
Oh right, it's only when you use a hardcoded custom_id it will share among users
I think there's a misunderstanding of how the view store works
When your bot receives a component interaction, it looks in your local view store. It first checks to see if there is a view object registered specifically to that message id. If there is, it looks for a component that has that custom id in that view object, then routes the interaction there
(this is for discord.py and other forks that follow the view model)
That is why you should never use hardcoded custom id for verification buttons? Or am I wrong?
no, it really doesn't matter if you do or don't
if you don't, the library generates a random one for you and they match up anyways
The first thing the library does when routing the interaction is look to see if there's a view stored mapped to that message specifically. It doesn't matter if there are other views that have components with the same custom id
The point of the custom id is for your side to know what to do with the component
Just an identifier
that applies to that view
stop()
Stops listening to interaction events from this view.This operation cannot be undone.
^ So for this case there is no two views created?
Because I submitted twice
The library internally uses that view, no matter how many times
So if you use stop() it will affect all buttons
The view store is basically
messageid_1 ---> [view object] : [button1, button2, button3]
messageid_2---> [view object] : [button1, button2, button3]
It is up to you what views you send and when
your code could easily be
view = MyView()
await channel.send(view=view)
await channel.send(view=view)
or
await channel.send(view=MyView())
await channel.send(view=MyView())
It would be the same result if it was from two different users?
The view is just an object that contains component callbacks. When you send a message and attach a view to it, you are saying you want that object to handle interactions on components sent in that message
That depends on your callback
this has no concept or notion of users
interaction on x message -> goes to y view object, and that is set at the time when you send that message
And what happens when the component is interacted with - that's for your callback function to handle
So for my case self.stop() basically cancels the view for all users that are running at that time
If they resubmit it works again
No, when you interact with that button, based on its custom id, the library knows what view object should handle it. So for as long as the view is 'stopped', no interactions with that button will work
At least I think so
You mean run the command again?
nvm
All good
None of this has anything to do with users
views are attached to messages. Not users
You stop the view, interactions on that message are no longer routed
So views with the same custom id would be considered as the same message?
No because you can have the same custom id in multiple messages
.
The view may be attached to multiple messages. In that case, using stop() will affect all those messages
In most cases, it is one view per message. You need to be going out of your way to specifically reuse a singleton view or if you're using a global persistent view
That is exactly what I meant. What does make the view be attached to multiple messages?
The fact that these messages used the same view instance
Which is based on?
.
Based on the instance you used when sending the message
If you could review my code and see:
https://paste.pythondiscord.com/VOCQ
I don't see a problem
.
view = VerifyButtonView()
await interaction.response.send_message(embed=embed, view=view, ephemeral=True)
You're creating a local instance here and sending it
Stopping this view instance will only impact this message
One of them is failing
User 1 > Submitted
User 2 > Submitted
User 1 > Press button OK
User 2 > Press buton failed
Same code as I provided
I'd have assumed that it's because the library no longer recognizes that view, but now I'm not sure after what Solstice said
Stopping this view instance will only impact this message

Why are you setting custom ids in the first place? Are you persisting a version of this view anywhere?
You said it doesn't matter
It doesn't, but it does matter if you have a global level view
So my theory was right?
So what are you saying?
Are you calling add_view anywhere in your code besides what you sent?
That is the full code
And why are you calling add_view in the first place
it's not the full code. This is clearly an extension
It's a cog for that particular verification. Try run the code yourself
It's used to keep the Submit button persistent
Me looking at this code doesn't tell me anything about what you do in the entirety of your code base
where any line anywhere else could be messing with this
If you want persistency, you need to set it for any view you use
Anyway I guess this is not the reason? I don't know enough about that
When you call add_view, all that does is manually adds a view to the view store for routing. If you don't specify a message_id, it means all interactions can be routed to it regardless of what message they came from
There is no other code, I'm running this cog solely
there is other code
Dude why don't you run the code yourself and see?
But just a quick note, you don't really need to stop the view if you make the button disabled nvm
You can't just "run" extensions. They don't do anything. They extend an existing bot
And you should do add_view for VerifyButtonView as well
Unless you don't want it to work after the bot restarts
No need for that really
I'm about 90% sure this will lead to a memory leak as nothing will remove the view from the view store
I assume this would only be relevant for non persistent views?
No, any view that doesn't have a timeout will by definition stay in the view store until you stop it
Actually come to think of it, not sure if editing it off the message entirely removes it from the store 
So using a persistent view just creates another internal instance every time?
I made a special case for you
https://paste.pythondiscord.com/QLEA
OR it stays there, but just a single instance. Sounds more likely
I think there's a confusion about what a persistent view is.
All add view does is just shove one view object into the view store. It doesn't make the class itself special or anything. The key here is that if you don't specify a message_id when you do that, that specific view object can be routed to for all interactions regardless of what message they came from
No because it's not per user
What I want to know is whether I'd need to use stop() in persistent views' callbacks to avoid a memory leak... I assume not because the library should store only one instance of that view, and I wouldn't call that a memory leak xd
Sorry if it sounds like bs but I got a liiittle confused there
You just had to word it right, it stops working for all messages that use that view. The word "users" isn't related
I think that's all
But you didn't use add_view for that Verification view. I guess because you specified a custom_id then the stop() acts like it'd act with a persistent view? (means it affects all messages)

Are These container or components v2?
containers are part of cv2, so yes
Stop only affects that view object. It doesn't look around and impact other views, regardless of the custom ids involved
im willing to learn the parts i need to make the bot
So if that view is persistent (so there's an instance of it internally)
And I create an instance to send in the message, the stop() will affect which?
That's like saying you're willing to learn the parts of basic engineering needed to make a nuclear reactor. There aren't shortcuts. You have to learn the basics
It affects the object you called stop on. It's a method
So how can i make this?
So ideally I'd want to use the same view instance that was used in bot.add_view, instead of doing view=MyView()? Memory-efficiency-wise
And I'm talking about cases where I don't use stop()
It really depends what behavior you want
and if your view objects have individual states
I only care about the callback pretty much
DynamicItems can also be a lot more memory efficient
I don't use any view methods really
Even for when the custom id never changes?
That's the idea behind them
I thought their purpose was for when the custom id is dynamic
Well, one use case. The "dynamic" part refers to the library dynamically making a component to handle the interaction when the interaction happens, rather than a view sitting in memory
Nope it handles the interaction and then is disposed
Might as well switch to using only dynamic items then ✌🏻😭 Unless it's not that serious
There's really no big difference between the two if there's no message-specific data being moved around though
Correct, but if you're doing one global view (because no message specific data), that memory footprint is negligible
What would be message specific data as an example?
Passing data to the view from for a message?
I send a view twice, one is supposed to send a response saying "A" when button is pushed, the other "B". And I want those views to persist between restarts without making two separate classes
Your options there are
- have a db, make one global persistent view that looks up the message id on the db
- have a db, call add_view N times passing in the message_id
- embed that data into the custom_id and make a DynamicItem
So basically any view that takes arguments (that are supposed to change) counts as one that uses message specific data
Okay thanks
I have one bot where I was too lazy to rewrite the views (wayy too many) so I just set timeouts for all of them lol
That'll do
A lot of time people think they need to make every button ever permanent but that doesn't actually match up with user behavior
Also for those curious about what stop does: https://github.com/Rapptz/discord.py/blob/master/discord/ui/view.py line 605
Well in that bot almost none of them is permanent since I didnt know shit when I made it
@fast osprey yo can you please help me on my question?
Only problem I have with buttons that just stop working, is the ugly 'interaction failed' frontend response
I don't have any experience with components v2 yet but I'm told the examples in the repo are quite extensive
I can try
Yeah the common approach is to implement on_timeout and remove/disable the items
I have my own wrapper but yesterday i tried dpy's CV2
So many classes 😭 ig it's formal but it bloats up the code
Not exactly, safe to say I'm not an expert with views
😄
I am just want to do this
Nextcord has no support for that yet
About that, I was actually trying to find the correct one in the docs 😭
Decided to grab one from the top of my head
wrap it in an actionrow
Ty for noting
but the user above is using Nextcord
Oopsie :D
which doesn't support cv2 at all yet
Sooo you can either wait or do what I did which is making a custom wrapper
Or switch libraries
Yeah that too 😭
Facst but thats not that easy and the same
Yeah up to you what the best use of your time and energy is
There is already a pr
Can i Download a pr ?
You can check out any commit on a public repo but you're doing so under your own risk
They could change anything and break any code you write now
you can install their cv2 PR by running the following command
python -m pip install "nextcord @ git+https://github.com/nextcord/nextcord.git@refs/pull/1254/head"
But you'll have to ask how to use it etc in their server as I don't think anyone here uses nextcord.
So i am on my own?
You have their server for support xD
have you tried asking?
Might as well click on Soheab's tag and find out
I forgot about that xD
When would you use persistent view vs DynamicItem?
In my case, if you want to keep a button that verifies users clickable after rebooting
Yes but help is very slow
In this case, your custom id stays static and you also don't pass arguments to the view. So persistent view
I will be pasting arguments
eh then it could depend
for the time being i'd say use persistent view
but its ur choice after all
ig your not understanding what im trying to say
its fine tho
the system i have now is good enough
DynamicItem is the newer and better versions of persistent views
like it doesn't take up memory to store the view etc, it just dispatches the item based on regex against the custom_id
so you should be using that where possible
"Better" is a bit disingenuous. There are meaningful cases where having a view is useful
true. but for most people it is
I'm not sure that I'm adding dynamic items to a view in the intended way:
...
self.add_item(TestItem().item)```
Only works when I add that .item, which is typed to Any so I wasn't sure I'm supposed to use it that way
You don't need the .item. What is TestItem?
class TestItem(discord.ui.DynamicItem[discord.ui.Button], ...)
Then you should be able to add the dynamicitem directly to the view
It raises an error, I'll check it when I can
DynamicItem is an Item so that should work just fine
Yeah double checked my code and you should be fine to just slot the dynamicitem itself into a view just fine
Is there some kind lib for discord bots?
For Python? Yeah there are a couple
Compares Discord libraries and their support of new API features
whats better discord.py or pycord
depends entirely on your preference
do yk how i can make my bot work after i close vs code?
so just having it run 24/7
you would need a seperate device to host the code
bc when i close vs studio the comand doesnt run anymore
how would i go about that?
conventionally a cloud hosting servicewould be used
do you use one?
you could also self host with an old computer or raspberry pi
I self host using an old laptop
I also have a free VPS from oracle free tier
itsgotenoughpower for multiple discord bots
im only using 1
for 1 single command 💀
i just need it to run 24/7
so i dont have to have my coding prog open
it is two years old but Idon't think there have been many large changes
ts looks confusing asf to install
you don't need to follow their bot guide
just the steps to create and access the cloud server
then you can ssh into the server in any way such as PuTTY and upload the bot files through sftp using something like FileZilla
and then just run the bot
so idk what ssh is, PuTTY, sftp, or fileZilla is
Putty and filezilla are apps
sftp is just a protocol like http but instead of sending websites it sends files
ssh is a way to access the cloud server's command line from your own device
PuTTY is a free implementation of SSH and Telnet for Windows. The program includes an xterm terminal emulator. PuTTY generates its own public and private SSH keys but can interoperate with OpenSSH keys.
Obtain an sFTP server and ensure that you're able to access it.
bro im so confused 😭
just follow the github tutorial until you reach the "Anything you wanna do" step
brings me to the same place
as this
np
i have to give them my home adress to sign up 🤨
you have to do that for all online payment things that use a card
im assuming the "free tier" isnt a free trial
and stays free
no the resources are permanently free
I've been using it for like 3 years now and havent been charged
so what was the point of the payment
to stop people from spamming accounts
ahh
that's for people to trial their premium resources
as the tutorial notes, make sure you pick stuff with the always free tag
it's the same thing
i got a virus warning trying to download https://puttygen.com/#gsc.tab=0
Download PuTTYgen for Windows, Linux and Mac operating system. Find step by step guide to downloading PuTTYgen, a key generator for free.
is that normal
guys can anyone help me
Exception has occurred: ClientConnectorCertificateError
Cannot connect to host discord.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1010)')]
ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1010)The above exception was the direct cause of the following exception:
File "D:!ExZhonya\Coding\Discord-Bot\Bot\main.py", line 37, in <module>
bot.run(TOKEN)
aiohttp.client_exceptions.ClientConnectorCertificateError: Cannot connect to host discord.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1010)')]
Update your windows
Are there people using render.com to run discord bots persistently? Are there alternatives?
Buy cheap VPS 5$ month and run your bot or whatever you like
You could also do local hosting if you're okay with that, cheaper and works
The reason why people are asking for host alternatives is because they can’t run them on their own machines
OT I don’t believe in any free alternatives
I'm doing fine with my Raspberry Pi
But everyone and their preferences/capabilities
And I actually recommend that for people who don't want to pay for a VPS. The Pi 4 is available for pretty good prices out there
These have a higher upfront cost, limited scalability and you still have to run them on your own
It depends on the scale of what you want to host on it. Yes it's not meant for huge projects or whatever.
And Idk what costs you mean, the only thing I'm paying for is a domain...
That’s why I recommend a cheap VPS, it has a low entry cost and you can always scale or switch later if you want
like hetzner?
i have this problem my bards are stucked, i am using pillow , how can i fix it?
I don't think this is the correct channel to ask that in
what is it?
#media-processing most likely
I don't know anything about that provider
yes
Webhook Events wrapper that I made for no good reason
-# "timestamp" and datetime.datetime doesn't really make sense but who cares
-# Just noticed it takes app id for no reason, removing that
And I figured that instead of using application.start(), it'd be much better to allow running multiple applications
Nice!
Nice
Nice
Nice
hi soheab I noticed you opened the nameplates PR on d.py, did you notice the weird ass endpoints of the cdn to get the assets 😭🙏
Oracle has a pretty good free tier, the complicated part is to get access because they release x amount of servers per week or something
Thx. I'll fwd this.
Yeah really weird
We just did .static and .animated
not even documented
Yeah it's not documented at all for some reason
huh, valid suffixes are only
asset.webm
static.png
and img.png (which returns an animated media lmao)
I swear at the start it was asset.png and asset.webm, then they changed it to be like it is today
maybe they just want to change it freely
Oh didn't know about the last one
The webm is technically animated as it's used for the hover effect
yes
The path is weird overal
it should actually return an apgn media
nameplates/nameplates/name...
Ya
yeah, it was even weirder at the start without the assets/collectibles prefix
Just discord things ig
Yup
discordn't
that got me too btw
Can anyone give me some tips to improve my code?
Set up a linter and formatter
Don't use prefix commands
Not sure what data you are iterating through here, but there's a good chance a member can leave or for any reason not be in cache upto the time member = guild.get_member(user_id) is called
There is a probability of member being None if they are not in cache or your server
You should consider error handling this as per your requirement, ie let's say you want to skip them, use continue to skip
Thanks for the suggestion
Why
Hmmm Idk I just think it looks better 
