#discord-bots
1 messages · Page 402 of 1
Have you tried logging the result you get back from the api? Also you should not be using the requests module in an asyncio application
what you mean logging?
anything that you can do to output information from your code to you
even a simple print statement works
this looks like chatgpt made it in the most respectful way possible
He has also made no progress since I got him to paste his code 2 days ago
oh thanks for telling me
Np
I upload the image to Discord and then copy the URL
im a bit confused....
i was able to do this... but how do i get it to be in the embed box?
Using the set_image() method of the Embed object, there are a few ways to do this but the easiest in my opinion is to upload the image to a Discord channel and copy the URL.
is there a video on that?
I don't know if there are videos in your language, I speak Spanish

See the following if you are using discord.py and want to add a local image to an embed:
https://discordpy.readthedocs.io/en/latest/faq.html#how-do-i-use-a-local-image-file-for-an-embed-image
me when people don't even read what is sent to them.
no wonder they will then code random stuff
literally code to copy paste but naah, let's ignore it and try random things out

trying to set up cogs and need help, can someone dm me?
You can post your question here
Helllooooo! im back
😉
Now ive setup a database with Plugins n that sets weather commands innside of the cog can be used or not, im new to databases atm the bot makes a new database per server would this be ineffecient is there a better way like to have server_Settings.db list all the servers and there settings or contuine with SERVERID_setting.db per sever
you should not be using new databases per server. It should just be a row in one table
"the bot makes a new database per server" 
unfortunately that’s what a lot of people first reach for
either new database per X or new table per X

what do you mean by that? im trying to make it so that everyserver has a settings area inside the database, such as like there server id and then a list of pugins and if there enabled i will also need to add channel list to this adventurly and make it read there channel ids
if you want settings for servers, make a table that links guild ID to setting ID
you dont need an entirely new table
or an entirely new database
make your settings columns, each guild has its own row
don't make them columns
even more confused now
make them numbers: ```sql
CREATE TABLE settings (
guild_id INT NOT NULL,
setting INT NOT NULL
);
make them numbers
,, this is how it looks atm i thought it was good aha first time ever using a database
db_name = f"Discord Servers Settings/{server_id}_settings.db"
if not os.path.exists("Discord Servers Settings"):
os.makedirs("Discord Servers Settings")
if not os.path.exists(db_name):
conn = sqlite3.connect(db_name)
c = conn.cursor()
c.execute('''
CREATE TABLE IF NOT EXISTS plugins (
name TEXT PRIMARY KEY,
status TEXT
)
''')
# Populate the 'plugins' table with the available plugins and set the status to 'disabled'
# Replace 'plugin1', 'plugin2', 'plugin3' with your actual plugin names
plugins = ['Scramble_Game', 'Giveaway', 'plugin3'] # Add your plugin names here
for plugin in plugins:
c.execute("INSERT OR IGNORE INTO plugins (name, status) VALUES (?, ?)", (plugin, 'disabled'))
conn.commit()
conn.close()
print(f"Created database for server {server_id} and initialized plugins.")
@commands.Cog.listener()
async def on_guild_join(self, guild):
self.create_server_db(guild.id)```
| guild_id | setting |
|----------+---------|
| 123 | 1 |
| 123 | 3 |
| 456 | 1 |
here, the server ID 123 has features 1 and 3 enabled, but not 2. the server ID 456 only has feature 1 enabled. this is your settings
this is awful
you're also using a blocking library
!pip asqlite - use this instead
like i said first time ever using a database
dont make an entirely new database for something as small as this
dont do this
with the asqlite will it still work with my sqlite3 db?
well, now you shift the burden of settings validation from the database to your app but that could work too
Baso i just wanted to make a database that stores what plugins are enabled and disbaled n adventurly link it to a website n that can change it to either enabled or disabled
also be able to have channels in there under the serverid such as bot_commands_Channel n able to change that via the website
asqlite is an asynchronous version of sqlite
thats arguably better than needing to expand your database every time you have a new feature
so 😕
its way easier to add to some dict or enum or other method of config in your codebase than in your database
pervious i was using a json file structured like
SERVERID:
Plugins:
sramble_Games: enabled
giveaway: enabled
channels:
bot_commands: 47438292282
scramble_Channel: 34884884
I have no idea how to even go about the way ur suggesting
personal preference I guess. I like having my database at the core and be the single source of truth, and don’t mind adding migrations
how would i go about this then like say plugin Giveaway is number 1 and if its enabled its number 2 if its disabled its number 3?
im so confusd ngl
check bitwise flags
discord uses them for user badges for example
explained here quickly
how is this related to what im doing?
how would i go about this then like say plugin Giveaway is number 1 and if its enabled its number 2 if its disabled its number 3?
using bitwise flags, just like discord does for badges, permissions, etc.
permissions on discord isn't an array with true/false, it's a bitwise flag e.g. 2112
and 2112 can be used to determine if a permission is enabled
you can do the same for your commands
my brains fried ngl i spent 3 hours earlier codeing something to disable / enable cogs on a server basis to find out it isnt possible
mh it's possible
fr>?
im using pycord
or interaction check
Attributes description, qualified_name. Methods cls Cog.listener, def bot_check, def bot_check_once, async cog_after_invoke, async cog_before_invoke, def cog_check, async cog_command_error, def cog...
like honeslty earlier i spent 3 hours codeing it to update the database per server but the cogs were always enabled in all the servers.
probably add some simple caching there running a db check on every cog command is a bit eh
yeah I agree
besides the point though
that's why you should first check docs and gather info
my aim was to make a plugin /module style system like big bots such as dyno and mee6 use to enable/disable features hopeing to put them in cogs and be able to like ignore giveaway.py cog if its not enabled on the website /database
i did.
we know what your goal is, we’re giving you solutions
you don’t need to repeat what you want to do 😉
yeah bitsets would also be another option. forgot to mention thise
small example for you:
def is_plugin_enabled(server, plugin):
return (server & plugin) == plugin
giveaway = 1<<0
scramble_game = 1<<1
server1 = giveaway # only giveaway plugin
server2 = giveaway | scramble_game # both plugins
is_plugin_enabled(server2, giveaway) # True, because giveaway is enabled in server2
is_plugin_enabled(server1, scramble_game) # False, because scramble_game is disabled in server1
server1 |= scramble_game # enable scramble_game for server1
is_plugin_enabled(server1, scramble_game) # True, because scramble_game is now enabled in server1
server1 ^= scramble_game # disable scramble_game for server1
is_plugin_enabled(server1, scramble_game) # False, because scramble_game is now disabled again in server1
I would also be cognizant of backwards compatibility when implementing your enable/disable system
pretty sure this is to advanced for me just have to not bother i think
So your all giving me diffrent options what option would be the easierst n the least stress on the bot?
I’d say all of them are about the same level of difficulty, they’re all stored in the database
oh dear i do miss my json file ahah
maybe a steep learning curve, but worth it
is it viable to check a db every single time a command is run?
just query when needed, cache the data
# Skip the check for the test command (so we don't block it)
if ctx.command.name == "giveawaycogtest":
return True
# Database connection to check the Giveaway plugin status
db_name = f"Discord Servers Settings/{ctx.guild.id}_settings.db"
conn = sqlite3.connect(db_name)
c = conn.cursor()
c.execute("SELECT status FROM plugins WHERE name = 'Giveaway'")
result = c.fetchone()
conn.close()
if result and result[0] == 'disabled':
return False
plugin is enabled
return True
Like ive managed to do this thinking it was good
should be fine. Databases can handle a lot more than people might originally think
e.g. load the data when the bot starts, then when a server sets if a plugin is enabled/disabled, update the db and cache
yeah the enabled/disabled should be set via a website adventurly
tbh i thought a database was the same as a json file
json is an inefficient data exchange format, databases are heavily optimized to storage large amounts of data and query them
if you want to read from a json file, you need to load the entire thing into memory, parse it, and look for what you need. If you want to write to it, you need to load it into memory, modify it, and rewrite the entire file from top to bottom
meanwhile with a database, you just issue a query to read or write a specific value and the database handles the rest
Ik we all did that at the start 😭
Would i be creating a new entry in the db for a new server? insted of a new db
there's also to mention that all databases and db drivers use atomic operations, while for json files you need to do that yourself
yes
you usually don't create dynamic databases or database tables
oh im so dumb
databases are pretty much like excel spreadsheets, you have spreadsheets (tables) and every spreadsheet has columns and rows, where columns are the variables and the rows are entries that contains all the values
hmm
like this sir?
hello
hi
yes, this is better
pretty sure that's an excel sheet lol
oh yeah 
was wondering why the user IDs were separated
no its a database
show the full screen
and also thats probably an excel sheet
you have an extra column on the left
ew
its just the app i use to view the db
its goo enough for me
alls i need to do it check stuff is acc working on it
now ive wacked my brain on it for 7 hours might be time for some rest lmao tom need to try n start working on channel ids and then look a at makin a userdata db
how would u suggest i do userdata so i want it to track xp message count and lvl per user per server just do it as SERVERID USERID TYPE NUMBER? per line simular to above?
sounds like you want this then
i think so tryna eat right now i currently have one worlkking great wiht json just need to update it to db
thats yaml
no
it is yaml
i just typed that message from my head.... i was using a .json file i know what i was using
Finally getting back to working on my discord bot game
so i got this error message:
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
is there any way to check what privileges my bot needs? Like a function that just spits out all the permissions i need to give him in the developer portal?
These aren't permissions. Your bot is asking for intents, and you wrote that code asking for them
Intents are almost exclusively about what events/data you receive from discord. For example the GUILDS intent is for receiving things like guild_update and channel_create you can see the full list here: https://discord.com/developers/docs/events/gateway#gateway-intents
For privileged intents it is safe to assume that if you dont know why you need them then you either:
- dont need them
- should learn what they are and why you need them (you can learn more here)
Why not just receive all intents?
it will make your bot slow by default, why process data that you won't use/need anyways?
just a waste of cpu power
That makes sense, thanks. I was more thinking from a security perspective.
how yall feel about using supabase as a DB for my bot to acces info from and write into
What was said above and also the 3 privileged intents that you have to be approved for eventually
supabase uses postgres so u should be pretty good just make sure u keep an eye on the amount of data u are storing free tier has 512mb afaik
Hello guys, I finished my first project using discord.py, but now I don't know how to run it 24 hours a day for my discord. I want a server that is cheap and good to run it. Do have any advice?
!hosting
Using free hosting options like repl.it for continuous 24/7 bot hosting is strongly discouraged.
Instead, opt for a virtual private server (VPS) or use your own spare hardware if you'd rather not pay for hosting.
See our Discord Bot Hosting Guide on our website that compares many hosting providers, both free and paid.
You may also use #965291480992321536 to discuss different discord bot hosting options.
What is the best approach to use a list from one cog in another cog?
Cog #1
list = []
Cog #2
list.append
Do you actually have an answer to my question?
It's actually on the website
Cog #1
class LinkSpam(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.WHITELIST_FILE = [1, 2, 3]
Cog #2
class Checker(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.check = self.bot.get_cog('LinkSpam')
@app_commands.command(name="test")
async def test(self, interaction: discord.Interaction):
await interaction.response.send_message(f"{self.check.WHITELIST_FILE}")```
[2025-02-27 00:26:37] [ERROR] Unexpected error: Command 'linkspam' raised an exception: AttributeError: 'NoneType' object has no attribute 'WHITELIST_FILE'
I can't use self for self.check?
maybe the bot doesn't have a cog named that at the time you assign that
It works if I do it within the command:
check = self.bot.get_cog('LinkSpam')
await interaction.response.send_message(f"{check.WHITELISTED_DOMAINS}")
yes, because the other cog is loaded by then
it should be extracted as a module
How can we use the self.WHITELIST_FILE from the class?
Cannot find reference 'WHITELISTED_FILE' in 'link_spam.py'
Cog #1
class checker(commands.Cog):
def __init__(self, bot):
self.bot = bot
# Load test
self.test_list = []
Cog #2
from events.cog1 import test_list
I'm getting Cannot find reference
It's still an attribute of the checker Cog object
Is this a static attribute?
or is this something that multiple components are referencing/changing
Second one
This code is totally fine then, or you can make it an attribute on the bot itself
But why doesn't it work when extracted as a module?
what do you mean by that
Do I need to define it at the module level?
show the import line
yeah, it being all caps implies its a constant and constants are usually module scoped
Cog #2
from events.cog1 import test_list
should be module scoped if constant. otherwise if it's read and modified in a lot of places it should be an attribute on your bot
Thank you
Could I load the list from a json file on setup_hook?
you could do that yeah
Or would it be better to load them from a cog?
i don't know what the purpose of the whitelist file is so I couldn't tell you
import os
import discord
from dotenv import load_dotenv
from discord.ext import commands
def main():
intents = discord.Intents.default()
client = commands.Bot(command_prefix="?", intents=intents)
load_dotenv()
client.run(os.getenv("DISCORD_TOKEN"))
# this part wont load cogs
for folder in os.listdir("modules"):
print("loaded")
if os.path.exists(os.path.join("modules", folder, "cog.py")):
@client.event
async def on_ready():
await client.load_extension(f"modules.{folder}.cog")
print(f"{client.user.name} has connected to Discord.")
if __name__ == '__main__':
main()
the bot loads fine, but just skips over the part where i want it to load my cogs
cog loading is async in discord.py now assuming u are using that
can you help fix it
i can suggest you sources which show how to do it
please man, ive been looking for help for no joke 3 days
https://fallendeity.github.io/discord.py-masterclass/cogs/#how-to-load-extensions-from-a-folder you should check the cog load part
import pathlib
@bot.event
async def setup_hook():
for file in pathlib.Path("cogs").rglob("*.py"):
if file.stem.startswith("_"):
continue
await bot.load_extension(".".join(file.with_suffix("").parts))
A hands-on guide to Discord.py
the cogs folder holds all your cogs
man
u should also make sure ur cog has the async setup function
from discord.ext import commands
class SuperCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def super_command(self, ctx: commands.Context):
...
@commands.Cog.listener()
async def on_message(self, message: discord.Message):
...
@tasks.loop(...)
async def super_task(self):
...
async def setup(bot):
await bot.add_cog(SuperCog(bot))
async def teardown(bot):
print("Extension unloaded!")
here is an example of a cog
you're not starting the task 
That's partially wrong; setup_hook is not an event.
It works because the decorator simply sets the attribute; however, the recommended way to override is by subclassing.
yeah a pending change in our todo 😭
teardown?
yep triggered when u remove the cog
.cog_unload?
when you unload the extension
cogs vs extensions 
Not really related to dpy, but just to add more to your todo; you could do a little section on typing/annotations/generics because like no one seems to understand how that works.
i'll help write it 🙋🏽♂️
sure just send a pr
fair enough a typing guide would be cool, so far few we have currently planned are oauth, db, sharding, and deployments
Oo those are really good topics
Not to hammer this in, but the conflation a cog and an extension is a widely spread misconception. Especially if you're putting this into guides it would be good to get into the nuance.
yep will look into it
i think there is an initial section kind of setting apart the ideas behind what a cog is native to dpy and extension being more of a python module, would you suggest including some generic examples as well to give a clear idea between them
Providing an extension that doesn't have a cog, and a cog that isn't in an extension makes this more clear
As is newbies are almost always presented with the one pattern so they think these things are synonymous
idk how good "dynamic views / components / idk how they're called" are now in D.py but we could also consider to add that
Basically a disnake low level components similar solution but for d.py
mhm will do thx
https://github.com/DisnakeDev/disnake/blob/master/examples/interactions/low_level_components.py this?
Modals have "on_submit" but what if I just close it? Is there a response for that?
Nope, discord doesnt tell you they did that
Didnt think so
yeah but I've noticed D.py dynamic components are not the same as that, they are usuful to just store data in custom ids, you still need to use views, still we could cover that even tho it's an advanced topic so maybe it's not worth the hassle
or is the view state built from the custom ids making them persistent
Now with 45 flag questions ;D Do you know your flags?
What library are you using?
Py-cord, nextcord, disnake, and discord.py are the most popular (but there are more)
Meant to reply to this, read message above
they're using discord.py
i've worked with them before
They have asked for help in the Pycord server as well
Would not be surprised if they were linked the wrong docs at some point and have code in both
well thats certainly strange. they did say openly that they used dpy and the syntax reflected that (@client.tree.command)
mabye they joined pycord by accident ¯_(ツ)_/¯
Well now I feel ignored. Im using discordpy
did you have a question?
No. I shared my repo and he replied intending to reply to someone else and now I felt ignored lol
Just needy people things.
Also. No. I wont be adding a readme. At least not anytime soon. 🙃
Which method is recommended to use?
url_pattern = re.compile(r'https?://(?:www\.)?([a-zA-Z0-9.-]+)')
matches = url_pattern.findall(message.content)
-
if any(domain.lower() not in self.whitelisted_domains for domain in matches): await message.delete()``` -
for domain in matches: if domain.lower() not in self.whitelisted_domains: await message.delete() break```
Barely any difference for such a tiny operation
:D
What about the regex? Is there a better way to implement what I'm trying to do?
Its good imo
make sure it handles hyperlinks too
These will be handled differently, as they are 99% used by scammers to mask malicious links 🙂
Why handle them differently? Are you performing different actions if it's a hyperlink vs a normal link?
Exactly
why tho? it's the same thing?
why not just one regex
like I got ths one for handling url spam
URL_REGEX: re.Pattern[str] = re.compile(
r"""
(?P<url1>https?://[a-zA-Z0-9]+([-\.][a-zA-Z0-9]+)+(:[0-9]{1,5})?[^?#\s]*(\?[^#\s]*)?(\#[^\s]*)?)|
\[[^\]]+\]\((?P<url2>https?://[a-zA-Z0-9]+([-\.][a-zA-Z0-9]+)+(:[0-9]{1,5})?[^?#\s]*(\?[^#\s]*)?(\#[^\s]*)?)
(?:\s+\"[^\"]*\")?\)
""",
re.VERBOSE,
)
# URL_REGEX.search(message.content)
# group("url1") or group("url2")
-# "it works"
Because most of those who use hyperlinks have compromised accounts
i use them multiple times a day and im pretty sure my account isnt compromised. seems like a pretty vague argument
Well, it's because you are not running a gamer community with almost 30K members 😅
It's not like I'm gonna use the bot for an educational server
Is that like a thing? Gamers don't use hyperlinks?
Not common
your gaming server should be using the builtin automod tbh
deleting the message each time can ratelimit your bot
and considering that these compromised accounts that you're focusing on usually spam in muliple channels
We are quite efficient at removing these so the risk is quite small
I doubt it's gonna get ratelimited, the ratelimits are pretty generous iirc, but it's 100% better to use the builtin automod
That’s why we will handle them differently
but you do you ig
If you give me a good argument for why I shouldn't, I might consider it
For the record, Discords automod is terrible
how so
Just my opinion
What makes u think its bad
It's not always accurate and flags words that aren't that bad
Also, a much more reliable way to differentiate between links sent by comprised accounts vs by normal accounts is to check if a similar link is being sent across different channels in a short amount of time
No need for that, I will just add "no hyperlinks" in the server rules

Good point though
custom solutions for large communities usually work better than discord's canned one-fits-all automod
i still don't think it makes a difference if a link is a hyperlink vs just a regular link. in this server we just look for specific known bad links, regardless of where it is in a message
oh? does disocrd not account for big servers?
no, i'm just saying different communities have different needs and, if executed well, custom solutions are generally better
ah
for this server we have a fairly extensive filtering system: https://github.com/python-discord/bot/tree/main/bot/exts/filtering
I have analyzed 4 years of data from my server and 99% of the time, hyperlinks are used by compromised accounts
well if that's what the data shows then go for it
I'm not saying this applies to all servers
Agreed
holy hell
most readable regex
I think some of y'all are conflating automod with the specific automod rule of discord selected terms
Automod as a system does what it says on the tin and quite well
Regardless, Automod can't handle it the way I want to do it
Btw what is the point of using an underline before each function?
_check_bad_display_name why not just check_bad_display_name?
denotes a private/internal/utility function
^ they're generally not supposed to be used outside the parent class
In python it is a convention. In some other languages it is enforced. Like private in java
!eval ```py
class Test:
def _blah(self):
print("blahblah")
def __womp(self):
print("wompwomp")
t = Test()
t._blah() # yes
t._Test__womp() # yesyes
t.__womp() # nono
:x: Your 3.12 eval job has completed with return code 1.
001 | blahblah
002 | wompwomp
003 | Traceback (most recent call last):
004 | File "/home/main.py", line 11, in <module>
005 | t.__womp() # nono
006 | ^^^^^^^^
007 | AttributeError: 'Test' object has no attribute '__womp'
It can be somewhat enforced, but not fully like other languages
double underscore before just mangles the name
Once is just "you shouldn't" and twice "you really shouldn't" use that
Honestly a bit unfortunate that py doesn't have a notion of private
I don't usually use other langs, so maybe that's why but I don't see the appeal in private attrs
it's probably more valuable in libraries than applications like discord bots
I still like pythons "you shouldnt" rather than "you cant"
Not sure if python has a convention for private vs protected though
whats the difference between those two?
I won't be able to explain it better then google, I only use public/private XD
I'm just going to yeet my 2 yeets worth of thought in regards to compromised accounts and links.
Don't allow links in general if your community is prone to having their accounts compromised.
A compromised account will usually spam, send the same message, so you can tell it's compromised that way.
Most accounts these days DM users, so you have to rely on your members informing you.
From experience I've seen these compromised accounts primarily DM users.
And no matter how many times you remind your member base what to look out for, they aren't reading your warnings and will still get "hacked"
generally private is only accessible from within the class, but protected can be accessed by subclasses
Hiya, I’ve noticed a issue with my bot in codeing it I have multiple on message events tracking such as sever xp global xp and for a few games, I’ve noticed this breaks the bot slightly when typing any command the bot suddenly responds 3 times
You should send your code
Male sure you aren't processing commands in a listener
You need validation.
And you might want to set your commands to be slash commands and not text commands
ive fixed it now
and I'd consider merging all your "on_message" listeners
that message was supposed to send last night
Appreciate you letting us know. We almost offered help for an issue we believed needed assistance with
and i cant merg them there for diffrent games.
is there a better way of doing this? it looks ugly and I hate it
import re
...
def Parse_Message_Link(url: str, type: str):
match = re.search("https://discord.com/channels/(\d+)/(\d+)/(\d+)", url)
if not match:
print("bad")
return None
# Convert the ids to ints aswell as return them
guild_id = int(guild_id)
channel_id = int(channel_id)
message_id = int(message_id)
if type == "g":
return message_id
elif type =="c":
return channel_id
elif type == "m":
return guild_id
...
if you change the regex to r"https://discord.com/channels/(?P<g>\d+)/(?P<c>\d+)/(?P<m>\d+)"
you can just return int(match[type])
probably cleaner to return all channel id, message id, and guild ID as a tuple and let the caller unpack and discard what they don't want
also, Parse_Message_Link should be parse_message_link, and I would recommend not using match as a variable name since it's a soft keyword, and not using type as a variable since it shadows the built in type
What's the use case where someone is sending you a message link? A message context menu will probably be way better in most cases
This was legacy code. I used the function to have my bot send the message from the url into an different channel (pre forwarding). Saved an extra step or 2 and also was put into a pretty embed
is it ok if, I myself as an open source library developer, offer the open source software to use endpoints or other features that aren't document by discord? I'm genuinely asking because you can see tons of libraries which had or have PRs or even offer in their public APIs "voice recording" and other undocumented discord features
and this in the dev ToS seems related
2B) You will not (and will not attempt to or permit or enable others to): [...] (c) access or use the APIs in any way that (i) is not in accordance with the applicable Documentation [...]
Im making a dashboard, and I see guilds.members.read
and im needing to some how see what bots are in the guild, to see if my bots are in it..? I have multiple bots on this dashboard, and im trying to make a feature which would need to check if my bot is in their discord servers. Is there a way to do that?
But they are not authorizing with that discord bot, they are authorizing with only 1 bot, which is a bot in the support server, making it to where they don't need to authorize with each bot.
you'd need to get that information from your bot. so get the guild ID from the user, then check if your bot is in that guild
Discord themselves has a system for lib devs to get early access to features, that are not documented yet. I think "not in accordance with the applicable Documentation" could have multiple meanings
I'm not in that list tho. Even then I have never seen discord take any action against developers that offer access to undocumented features
I will provide support for documented features only
hi i have a problem
with
│── bot.py
│── config.py
│── /cogs
│ │── example.py
│ │── admin.py```
my project
structure
and splash commands its not work
bot.py file ```
import discord
from discord.ext import commands
import config
intents = discord.Intents.default()
intents.message_content = True
class MyBot(commands.Bot):
def init(self):
super().init(command_prefix="!", intents=intents, application_id=123456789012345678)
async def setup_hook(self):
await self.load_extension("cogs.example")
await self.load_extension("cogs.admin")
await bot.tree.sync(guild=discord.Object(id=config.GUILD_ID))
print("Bot gotowy!")
bot = MyBot()
@bot.event
async def on_ready():
print(f"Zalogowano jako {bot.user}")
bot.run(config.TOKEN)
my cog
import discord
from discord.ext import commands
from discord import app_commands
class Example(commands.Cog):
def __init__(self, bot):
self.bot = bot
@app_commands.command(name="ping", description="Sprawdza ping bota")
async def ping(self, interaction: discord.Interaction):
await interaction.response.send_message(f"Pong! 🏓 {round(self.bot.latency * 1000)}ms")
async def setup(bot):
await bot.add_cog(Example(bot))
They are syncing. But they're syncing to a guild despite having a global command.
Also I would not recommend you sync every time your bot starts, it's unneeded
Oh yeah, you can use a command to sync
async def on_app_command_error(self, interaction: discord.Interaction, error: discord.app_commands.errors):```
Hi, i had an issue with bot error handling. Why doesnt my bot catch the error? it fails to recognise the error
That isn't an event and I don't know what led you to believe it was
💀 um
Or are we just guessing events that might exist lol
damn mb i gen thought it did
do u know how i can fix it
i meant what the correct event is
There isn't one
Reading through the docs is a good first step, or you're just guessing events and hoping they exist with the parameters you want.
App command errors are dispatched to your CommandTree's on_error method. They don't fire an event
on_command_error
this is an event
i assumed thered be one for app commands
ohhh
omgg alr tysmmm

No worries, it happens 🙂
🙂 seems adversarial for any channel
there is no way to get a discord bot into a groupchat vc correct
nope
No, but you can have user bots
?
This is against tos, and it's against server rules to suggest or help things that are against tos
can i ask for python-telegram-bot here? or is it only discord bots?
can they?
latter
what do you mean ?
only discord
nope cause thats naughty
I need help with this error https://paste.pythondiscord.com/7AVQ
The slash command is not popping up in the discord bot
Nothing in here syncs your commands.
Also don't use the requests module in async code, use aiohttp instead
nope
this seems pretty good: https://fallendeity.github.io/discord.py-masterclass/
okie thank you 😁😁
hi bot
Hi
edit : omg nvm tysm i fixed it!
sry for the ping btw
Is anybody using hikari and crescent? have an idea why is not updating in discord when i add a new command?
Whenever you add/edit/delete a command the first thing you should do is refresh discord with ctrl+r
What even is a user bot?
Pretty much anything that uses a user token except the official discord client
That is confusing but if it's against TOS might as well stay away from it anyways
can someone help me rq
ive made a script for my bot but there is a command that is not going away and idk how to fix it
elaborate
dm
what is confusing about what i said
okay so
i want to get rid of the /rig command
did you sync
and its not getting rid
and did you refresh your client
yes
did you sync your command tree?
ive done everything but it still appears
is it there if you go to another guild?
ill try now holdon
yes
Did you remove it from the code?
yeah
atleast i think, thats why i joined here for help
!paste - lets see some code then
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.
I'm not good at python by any means but try deleting these
@bot.command(name="righeads")
@bot.command(name="rigtails")
isnt this for the '! command
Those would be apart of the Rig command and if you don't want that command anymore you wouldn't need those.
What do you mean
!rig tails !rig heads
that works, but i only want to get rid of the / one
Oh, okay. Yeah I've never dealt with ! Commands, I prefer / commands. I'll take a look at the code again and see if I can remotely help at all.
You're clearing the global commands
Are you the commands you're trying to remove aren't guild specific?
.
Multiple guilds? Idk lol
worth a try though
Clear the commands for the guilds with the id they have and see the result
@slate swan You could try this, I've had a similar issue before and this fixed it
@bot.event
async def on_ready():
print(f'Logged in as {bot.user}')
bot.tree.clear_commands()
await bot.tree.sync()
print("Slash commands cleared and re-synced.")
guild=None means all global commands
it's an optional kwarg
Oh, for me it never gave me an error. I think anyways, I just noticed my issue went away when I did it
No it's not an optional kwarg
So I apparently somehow solved an issue for myself while creating a new one. Neat!
docs are weird then
why'd have to be inconsistent with the rest
all others are optional and have none as default lmfao
So that users are aware of what it does 
well, get_commands() is optional
users may not be aware it gets the global commands if not giving a guild
same for sync()
They can read the docs :)
yeah, well then they can make it consistent
But I agree, it's dumb
ah, well tried yesterday
Oh i know what you mean
gotta see
That got fixed
the state thingy for interactions
nice nice
ah yeah no pings for smaller updates i guess
Nope
I have done create a bot tunneled via cloudflare.com. Can I write python code for processing messages received by my bot. Where should I start.
I'm new to this bot staffs.
I'm RPI++. Hi everyone.
can you give us more details
I need to process messages coming from remote ESP32Sx. I'd like to use python. And processed messages will be send back to the said device.
Is that possiable ?
It is some kind of IOT staffs.
are you effectively talking about discord bots?
doesn't seem like it has anything to do with discord bots
Ah Yah for discord bots.
then i'm not sure what exactly you'd like to do
You can just use a library like discord.py for this?
client = discord.Client(intents=discord.Intents(messages=True, guilds=True, message_content=True))
@client.event
async def on_message(message: discord.Message):
print(f"{message.author} sent a message: {message.content}")
client.run("token")
loool
what does an esp32 an iots have to do with the whole thing x)
import discord
intents = discord.Intents.default()
intents.message_content = True
client = discord.Client(intents=intents)
@client.event
async def on_ready():
print(f'We have logged in as {client.user}')
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('$hello'):
await message.channel.send('Hello!')
client.run('your token here')
note that there are also other python discord api wrappers like hikari, pycord, discord.http, disnake and nextcord
Yes. Thanks for your info.
before anyone jumps in
cursed af that the modal definition is inside the command
and client: commands.Bot 👍
Wait
Why is he importing app_commands separately and then using @discord.app_commands.
😭
💀
✨style✨
we need inport
anyone need my help?
I can develop a discord bot
You need to find them, they won't simply just find you
Can u tell me where I can learn discord bot making
what do you really want to build?
Like disc0rd b0ts like t0k3n joiner, ev creator, b00st bot oauth and many more
I purchased many tools like t0k3n ev creator tempmail and yopmail also I have b00st b0t but I don't want to waste money for purchasing this that's why I want to learn discord b0t coding so that's why I can make my own b0ts
that sounds like ton of gray areas
Um i only want to know where u learn coding to make b0ts
But they are selling at a huge price
dm me
you wont find any help for those particular use cases in this server, but we can provide resources on how to get started with building discord bots
Yea I don't want these bots help i only want to learn
https://github.com/Rapptz/discord.py/ check examples folder
https://discordpy.readthedocs.io/en/stable/
https://fallendeity.github.io/discord.py-masterclass/
An API wrapper for Discord written in Python. Contribute to Rapptz/discord.py development by creating an account on GitHub.
A hands-on guide to Discord.py
Ok it has tutorial also
Any more resources u know
Thank you very much bro
its an unofficial guide but yeah you can use it to get started
Any more u know
not many that are up to date, if you have doubts you can ask here or https://discord.gg/dpy
Everyone always asks if you're from India, but no one ever asks where India is from or how India is doing 
You're in the wrong subreddit..

oh hey
That sure is a lot of nondescript, randomly censored buzzwords
Gotta hack that mainframe
Yes
Yes but they are also common terms for what scammers/resellers use to violate TOS
Yea but some you cannot say that all are scammers some people are good and help people
Unlikely
Even if you think they are good if they break TOS they are probably hurting someone
Yea bcuZ all know it is developing country and for earning money some people do these bad things for earning but in some cases the person which is doing scam like in india but the money goes to china bcuZ 90% scam call centers are operated by China but many of us didn't know the reality.
Yes
That has nothing to do with what i am talking about
Many of people see that indian are scamming but the operator or boss is china
I am talking about discord scammers not call centers. Also I don't care who operates it it is still scamming
And either way, for the purposes of this server it doesn't matter if something is right or wrong, if it violates TOS we can't help with it
Discord finally decided to eventually add katex support 
did it?
$5^2$
its still in experimental stage, plus it won't work like that lol it'll be inside a codeblock afaik
experiments, so not live
also yeah, code blocks
```katex
\sqrt{2}
```
\sqrt{2}

not live
i read infertile's message first
then read yours after sending
I also said it's in experimental stage 
what? what kind of weird bots are those? 🤨
also why are your O's zeroes
t3h 1337 h4xx0rz xD
B00st bot = b00st the server with N1tro t0k3n
Ev creator = make disc0rd t0k3n with selenium automatically
T0k3n joiner --> Can join disc0rd t0k3n ( like offline members and many more)
what's the purpose of those 0 and 3 and whatever
those don't sound kosher ngl
Is there a way to create a slash command hyperlink? For example if someone clicks on #add, it brings up the /add command?
Yes you can mention a slash command: </full name:id>
i didn't even know that
yeah saw that in the docs
i wonder how they got to that emoji for the standard unicode stuff
also whats guild navigation
<267624335836053506:browse>


yeah.. discord...
though it's in the "example"
and only all uppercase should be changed
but yeah, don't necessarily read all that instantly to be fair..
ah i see
Hey if anyone here needs any discord bot i can make one for free I am new to this discord library I jus need a good topic to work on kindly dm me if interested
@astral wolfhey bro i want a dc bot
Yea sure man dm me
Scammers scam the scammer lol
scammer scams the scammer scamming the scam scammed by the scammer
Java's Scanner?
Anyone wanna collaborate on a discord game bot? I'll explain the design in Dms tho
Yo I'm up for it
Can someone explain what's going on? i'm confused on why its being passed as an integer when going into my function?
I have an app command
@app_commands.command(name="create", description="Create a giveaway")
async def create_giveaway(self, interaction: discord.Interaction, prize: str, description: str, amount: int, end_time: str, role: discord.Role = None, invite: str = None):
await interaction.response.defer()
print(type(end_time))
# will parste into database later also make it more pretty
if tt.string_to_seconds(end_time) is False:
await interaction.followup.send(
"Incorrect format used for the end date of the give\n"
"Examples of proper use"
"`1 month(s)`"
"`4 day(s)`"
"'1 hour'"
"'30 minutes'"
""
)
return
end_time = tt.seconds_to_discord_timestamp(tt.string_to_seconds(end_time))
...
and im passing through the strings_to_seconds function, its imported from an different .py file. I've been getting integer errors and when checking the type its an string within the app command but the function has it as an integer.
Examples of arguments passed through "1 day", "24232", and "2 months"
This is the start of the function haven't modified the variable or anything when passing it through
def string_to_seconds(time_str: str):
if time_str.isdigit():
return int(time_str)
time_str = time_str.lower()
total_seconds = 0
...
Fixed it by changing the object type into a string but still very confused
def string_to_seconds(time_str: str):
print(type(time_str)) # debugg
time_str = str(time_str)
print(type(time_str)) # debugg
if time_str.isdigit():
return int(time_str)
time_str = time_str.lower()
total_seconds = 0
# time_str is an string instead of integer now
before changing the type I would be getting this in console while checking the type
<class 'str'>
<class 'str'>
<class 'str'>
<class 'int'>
[2025-03-07 01:07:35] [ERROR ] discord.app_commands.tree: Ignoring exception in command 'create'
Traceback (most recent call last):
File "C:\Users\wizar\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\app_commands\commands.py", line 857, in _do_call
return await self._callback(self.binding, interaction, **params) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\wizar\Desktop\Giveaway bot\cogs\Giveaways\handle_giveaways.py", line 104, in create_giveaway
end_time = tt.seconds_to_discord_timestamp(tt.string_to_seconds(end_time))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\wizar\Desktop\Giveaway bot\utils\time_stuff.py", line 27, in seconds_to_discord_timestamp
seconds = string_to_seconds(seconds)
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\wizar\Desktop\Giveaway bot\utils\time_stuff.py", line 46, in string_to_seconds
if time_str.isdigit():
^^^^^^^^^^^^^^^^
AttributeError: 'int' object has no attribute 'isdigit'```
not sure if how i import matters but here it is
```py
import utils.time_stuff as tt
What wrong is probably in another function seconds&to_discord_timestanp
No I'm just a bad programmer and didn't add error handling, tt.seconds_to_discord_timestamp gets called because my code only checks if something is returned or not (which the error was returned)
Look at the traceback
It tells you seconds_to_discord_timestamp called string_to_seconds
string_to_seconds is what sends the attribute error
This is the entire function and I just realize that yeah I don't need to call the function again (its only called once at least and the argument is string_to_seconds) that's still the problem. the function itself. string_to_seconds returns an integer
also current_time_in_unix is just int(datetime.datetime.timestamp(datetime.datetime.now()))
def seconds_to_discord_timestamp(seconds: float):
current = current_time_in_unix()
seconds = string_to_seconds(seconds)
total = current + seconds
return f"<t:{total}:f>"
no way is anything visibly turning whatever my argument into an integer
See? You put a float inside the string_to_seconds, which it only accept string
Why took so long to respond...
Are you saying that because string_to_seconds is in tt.seconds_to_discord_timestamp and it only takes in an float that tt.string_to_seconds(end_time) is sending end_time as an float (and defaults to integer because it has no decimal) and that's why within string_to_seconds time_str is an integer rather than a string?
? Python type annotation only to remind the developer what type it should be, it's not enforced and not auto converted
(unless you are some library that read the type annotation and do some complex handling like discord.py) which you are not
And you put an integer there, so it's a integer
dangg
it all makes sense now
I was wrapping my head around about what you said and also did some testing myself and yeah you were right, really misunderstood and the simple fix was to just remove it all together
no clue what I was talking about here but after testing what I got from your help got me to the issue even if I was confused
Thanks 👍
Me thinking it's normal for beginner to not think this way as they only learn type annotation really late
But this is a special case as the discord.py have special usage of type annotation that might be confusing
Well, no, I am pretty sure discord.py taught you to put like description: str for command arguments to get a string
But this make you thought this apply to entire python, when discord.py doing the specific heavy lifting to make it beginner friendly
Not sure if this is a good reason or not but I just put it there so I would know what to put in when I call it
Well, I think you are required to put it due to discord.py
gotcha
At least, now I learnt that this can confused beginner who start from discord.py
Because usually, people learnt type annotation when they forget what type is everything and causing error
Yeah they force type annotation for slash commands
Because they need to know what you want and handle for you, specifically
Hello I recently took a Raspberry Pi 5 to put a Discord bot in python the problem is that I struggle to use it. for example when I put the bot on my user (not root) I create my venv, I install the modules in the requirements but as soon as I launch the bot it gives me a python error that I do not have the necessary permissions etc ...
Nothing to do but even when I do sudo su I still can not access the root folder
Show the error
Wait
to be fair it would likely fit better in e.g. #unix as it's not related to discord bots (even if you run a bot on that rpi, it doesn't make it a discord bot issue)
it's either a wrong rpi or python installation/setup
It depends on the error
Maybe they wrote something that cause it in the bot
on a VPS or my pc it works very well
An error message would be more helpful
Yes wait i reinstall the os
🗿
10 min max
at least changing some settings when reinstalling? compared to the first time
Honestly, I don't see what could be wrong.
so you're reinstalling just like before?
@slate swan@tender bobcat
Traceback (most recent call last):
File "/home/axrzz/discord/bots/bot.py", line 1, in <module>
from dotenv import load_dotenv
ModuleNotFoundError: No module named 'dotenv'
(myenv) root@raspberrypi:/home/axrzz/discord/bots# pip install dotenv
Looking in indexes: https://pypi.org/simple, https://www.piwheels.org/simple
Collecting dotenv
Downloading dotenv-0.9.9-py2.py3-none-any.whl (1.9 kB)
Collecting python-dotenv
Using cached https://www.piwheels.org/simple/python-dotenv/python_dotenv-1.0.1-py3-none-any.whl (19 kB)
Installing collected packages: python-dotenv, dotenv
Successfully installed dotenv-0.9.9 python-dotenv-1.0.1
(myenv) root@raspberrypi:/home/axrzz/discord/bots# python3 bot.py
Traceback (most recent call last):
File "/home/axrzz/discord/bots/bot.py", line 4, in <module>
import discord
ModuleNotFoundError: No module named 'discord'
(myenv) root@raspberrypi:/home/axrzz/discord/bots#
i already do pip install -r requirements.txt why...
why i am bad
!dashm
When trying to install a package via pip, it's recommended to invoke pip as a module: python -m pip install your_package.
Why would we use python -m pip instead of pip?
Invoking pip as a module ensures you know which pip you're using. This is helpful if you have multiple Python versions. You always know which Python version you're installing packages to.
Note
The exact python command you invoke can vary. It may be python3 or py, ensure it's correct for your system.
I think I am confused because I connect as axrzz 'and not root'
same...
Traceback (most recent call last):
File "/home/axrzz/discord/bots/bot.py", line 1, in <module>
from dotenv import load_dotenv
ModuleNotFoundError: No module named 'dotenv'
did you pip install it?
I tried to install it manualy without reading the requirements and it works .... I don't understand
define "install it manually"
(myenv) axrzz@raspberrypi:~/discord/bots $ pip show python-dotenv
WARNING: Package(s) not found: python-dotenv
(myenv) axrzz@raspberrypi:~/discord/bots $ pip install python-dotenv
Looking in indexes: https://pypi.org/simple, https://www.piwheels.org/simple
Collecting python-dotenv
Using cached https://www.piwheels.org/simple/python-dotenv/python_dotenv-1.0.1-py3-none-any.whl (19 kB)
Installing collected packages: python-dotenv
Successfully installed python-dotenv-1.0.1
(myenv) axrzz@raspberrypi:~/discord/bots $ pip show python-dotenv
Name: python-dotenv
Version: 1.0.1
Summary: Read key-value pairs from a .env file and set them as environment variables
Home-page: https://github.com/theskumar/python-dotenv
Author: Saurabh Kumar
Author-email: me+github@saurabh-kumar.com
License: BSD-3-Clause
Location: /home/axrzz/discord/bots/myenv/lib/python3.11/site-packages
Requires:
Required-by:
(myenv) axrzz@raspberrypi:~/discord/bots $ python3 bot.py
Traceback (most recent call last):
File "/home/axrzz/discord/bots/bot.py", line 4, in <module>
import discord
ModuleNotFoundError: No module named 'discord'
(myenv) axrzz@raspberrypi:~/discord/bots $
well you havent installed discord.py
I know but the problem and that I would like to install all the modules by doing to pip install -r requirements.txt and not with pip install <modulename>
so make a requirements.txt file and put all the modules you need
!venv i also recommend using these
Virtual environments are isolated Python environments, which make it easier to keep your system clean and manage dependencies. By default, when activated, only libraries and scripts installed in the virtual environment are accessible, preventing cross-project dependency conflicts, and allowing easy isolation of requirements.
To create a new virtual environment, you can use the standard library venv module: python3 -m venv .venv (replace python3 with python or py on Windows)
Then, to activate the new virtual environment:
Windows (PowerShell): .venv\Scripts\Activate.ps1
or (Command Prompt): .venv\Scripts\activate.bat
MacOS / Linux (Bash): source .venv/bin/activate
Packages can then be installed to the virtual environment using pip, as normal.
For more information, take a read of the documentation. If you run code through your editor, check its documentation on how to make it use your virtual environment. For example, see the VSCode or PyCharm docs.
Tools such as poetry and pipenv can manage the creation of virtual environments as well as project dependencies, making packaging and installing your project easier.
Note: When using PowerShell in Windows, you may need to change the execution policy first. This is only required once per user:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
I already have it but when I make the order he installs but nothing ...
define "nothing"
When i do pip install -r resuirements.txt
Please react with ✅ to upload your file(s) to our paste bin, which is more accessible for some users.
put it on the pastebin
He install all modules but when i run bot.py he tell i dont installed the module like dotenv, discord etc...
https://paste.pythondiscord.com/C72A
It isn't installing anything. There's an error
yeah thats a build error
any idea to fix that because i am lost 🥲
it literally says there "this error occurred from a subprocess and is likely not a problem with pip"
gonna have to look online. it's a C issue so 
want to die 🥲
#python-discussion and #c-extensions might help
Sounds like a threat
where
^ /s
the solution to avoid error (thx chat gpt)
sudo apt update && sudo apt install python3-dev
it work love on you and for ur time@viscid hornet@timber dragon
Does anyone know if there is any way to delete sending stickers in channel? I've checked permissions and server settings but it seems you can only disable external stickers & not all.
Not really related to discord.py specifically, but I don't know where else to ask. I've got a discord channel which is used for a specific slash command, users can obviously also DM the bot but a lot of them say it's easier to just use this channel. AutoMod currently blocks ANY message sent, so if you accidentally send a message instead of using the slash command, it never gets sent. Users have however figured out that stickers can bypass this, I now have the bot watch on_message and deletes any messages that are somehow sent however I'd rather block them entirely.
Do you need the user to read the message history?
Making a channel you don't want people to send messages in doesnt make too much sense. Why can't they just use this in a normal channel?
Long time since I did a discord bot, where were you able to check the submission of the Modal?
there's the on submit but cant find the actual data
it's in the .value attribute of the textinput
thanks
it says this but i have it in my requirements.txt
anyone know hwy
does anyone know hwy
bro?
helpers?
stop spamming everywhere
You have asked in 5 different channels with 2 accounts
!rule tos also
5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
context? What's tos related here?
🤨 weird
Bro is installing asyncio 💀
pip install io
pip install pip
pip install builtins
pip install python
pip install c
pip install std
pip install windows
if message.stickers:
await message.delete()
i just delete all messages by default
thought there might be a way to fully disable sending stickers discord-side that i was missing
but i dont think there is
Apparently not
Discord™️
You can disable embeds, files and reactions but not stickers for some reason
Just amazing
discord™️

Ayo?
msg.edit(f'{player1.id}\'s battle with {player2.id} has begun')```
I have the above line of code which gives the following error: `Message.edit() takes 1 positional argument but 2 were given`
I do not see another argument so if anyone could explain why this is happening that would be great!
How are you defining msg?
msg = await ctx.send(...)
Ah, yeah
!d discord.Message.edit
await edit(*, content=..., embed=..., embeds=..., attachments=..., suppress=False, delete_after=None, allowed_mentions=..., view=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the message.
The content must be able to be transformed into a string via `str(content)`...
The method is keyword only, so you gotta do content=f''
I see thanks!
Any idea why sendall command isnt showing?
...
class Shop(commands.Cog):
def __init__(self, bot: commands.Bot) -> None:
self.bot = bot
@commands.command(name="reload")
async def reload(self, ctx: commands.Context) -> None:
await ctx.bot.reload_extension("cogs.shop")
await ctx.reply("Reloaded!")
@app_commands.command(name="tienda")
async def tienda(self, interaction: discord.Interaction):
try:
await send_store(interaction)
except ValueError:
embed = discord.Embed(
title="Código de verificación expirado",
description=f"Para generar un nuevo código de verificación accede [aquí]({AUTH_URL})"
f", una vez iniciada sesión (no aparecerá ninguna web) copia el enlace "
f"y dale al botón de introducir código",
color=0xFF00FF
)
await interaction.response.send_message(embed=embed, view=NoAccessTokenView())
@app_commands.command(name="sendall")
async def sendall(self, interaction: discord.Interaction) -> None:
for member in self.bot.db.get_all_members():
await send_store(interaction)
await interaction.response.defer()
async def setup(bot: commands.Bot) -> None:
await bot.add_cog(Shop(bot))
the other command "tienda" is showing
sync ur commands and hit ctrl + r if on discord desktop
done that still not registering
when u sync the commands u get a list of returned commands which were synced is that command present in the list?
class Bot(commands.Bot):
def __init__(self) -> None:
super().__init__(intents=discord.Intents.all(), command_prefix="..")
self.db = DB()
async def setup_hook(self) -> None:
await self.load_extension("cogs.shop")
await self.tree.sync(guild=discord.Object(931192437949485116))
print([c.name for c in self.tree.get_commands()])
the print shows tienda and sendall
no the sync call returns a list of synced commands
!d discord.app_commands.CommandTree.sync
Returns
The application’s commands that got synced.
Return type
List[AppCommand]
await sync(*, guild=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Syncs the application commands to Discord.
This also runs the translator to get the translated strings necessary for feeding back into Discord...
are u sure the guild id is correct and when bot was added it was added with application commands scope?
thats wierd but it's likely that after the first command sync even tienda probably didn't get re synced
do you get any errors?
You declare a global command but you sync guild
Shouldn't be a problem, I don't think
fuck it was that
Yeah that only syncs the commands for that specific server
@calm vector can you mute/deafen/move/disconnect @ lemon in exemple?
i mean in vocals
- probably dont ping mods
- no. thats literally how roles work
yes i ping mods
lmao get ready for a swift timeout

lmao which part
what it is they want
hi, i cant seem to be able to give a simple role to a on_member_join event. am i missing something, i feel like it should be easy...
currently missing the whole code
Code? And what's the goal of giving everyone a role?
@self.event
async def on_member_join(member):
print(f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}----------{member} has joined the server----------")
# drifters role
has_drifter_role = self.DRIFTERS_ROLE_ID in member.roles
if not has_drifter_role:
await member.add_roles(member.guild.get_role(self.DRIFTERS_ROLE_ID))
print(f"{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}----------Added Drifters role to {member}----------")
- Does the bot have permissions to manage roles?
- Does it print anything?
- yes
- yes
the bot already manages roles and random stuff, its working fine for everything else. it throws an error
2025-03-08 16:20:13 ERROR discord.client Ignoring exception in on_member_join
Traceback (most recent call last):
File "/home/zed/.local/lib/python3.10/site-packages/discord/client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "/home/zed/Projects/ZeddyBot/zeddybot.py", line 336, in on_member_join
await member.add_roles(member.guild.get_role(self.DRIFTERS_ROLE_ID))
File "/home/zed/.local/lib/python3.10/site-packages/discord/member.py", line 1051, in add_roles
await req(guild_id, user_id, role.id, reason=reason)
AttributeError: 'NoneType' object has no attribute 'id'
it also prints that the user joined, with proper formatting and all
2025-03-08 16:20:13----------testy_test_mctest has joined the server----------
[<Role id=428788808754921472 name='@everyone'>]
False
1347960879500755066
it can't find the role in that server
Does the role exist?
i grabbed the role id from the developer option when you right click on the role in discord
make sure it's int
self.DRIFTERS_ROLE_ID in member.roles isn't valid either, member.roles is a list of Role objs. Use member.get_role(ROLEID).
also, you don't need to get the full Role obj just add it; use discord.Object(ROLEID)
alright, ill try those changes
Can you show where you placed it?
dang, i wrapped the self.drifter_role_id in int() and it worked.... ive been trying to debug for 3 hours
thanks @timber dragon and @young dagger
it's cause im loading all the stuff from a config.json .. it's a string inside of it, makes sense
You don’t need to wrap it in int(), though it’s not bad practice. Just using drifter_role_id = 123456789 is fine. If you add quotation marks, it will turn into a string
json is a pretty crap config format anyways compared to things like toml and yaml. It was designed for data exchange, not configuration
Oh right, json is always string by default afaik
ill have to refactor at some point, but at least its working now. ill do a couple more tests just to make sure
What would be the best way to get the user_id out of a username?
could you explain a bit more? There aren't many cases where you'd wanna do that, usually it's the other way around
So I am coding a Ticket system for my small server, but I dont want to save the users data in a db or smth, so the channels name is called "ticket-emn4tor". So I coded a cap with max tickets based on their id but to change it I need that ID
I hope you get what I mean
there are a couple things to note here
- Ticket systems that use channels are not recommended, it's best to use private threads
- using names for something like this is not recommended, ids are better since they're unchangeable and unique
Guild.get_member_namedwill take a namestrand return adiscord.Memberif possible
usernames in channel names is far more convenient, it's how @novel apex works
you can put the user ID in the channel topic though
IMO still use a small database, it prevents issues where the channel name/topic is changed
(and also don't use channels for this to begin with)
can you not also name threads?
.env file exists: True
TOKEN: None
OWNER_ID: None
Error: DISCORD_TOKEN environment variable not found.
can anyone help me about this problem pls dm
you already made a help post
env files and vars are more of a hassle than it is worth. I recommend creating a simple config.py and importing config values normally instead
i got it
The on_message listener never seems to work for me. I have given my bot every single permission there is, made sure there are absolutely no errors, made sure that the cog is loaded and nothing else is interfering. NONE of the code executes in the on_message listener
class GeneralCommands(commands.Cog):
def __init__(self, bot, config):
self.bot = bot
self.db = MainDatabase()
self.config = config
print("GeneralCommands Cog Initialized")
@nextcord.slash_command(name="test_general", description="Hello")
async def test_general(self, ctx):
await ctx.send("The general cog is loaded.")
@commands.Cog.listener()
async def on_message(self, message: nextcord.Message):
await self.bot.process_commands(message)
print("Listener triggered!")
if message.author.bot:
return
print(message.content)
The slash command works, but whenever I send messages, the program doesnt print anything
slash commands aren't messages. simple as that
also you don't need to process commands because it's a listener, not the main event handler
yes I was just trying out any code snippets I could
What does this mean?
wait fuck
Is there an example of working on_message listener functionallity? I tried making a bot a few months ago with a listener and it also didnt work then. I've tried every code snippet stack overflow has given
Yes I was just using the slash command as verification that the cog was loaded
Anyone know how see all members the bot can see? I wanna just len it, but i don't chunck the guilds on startup, meaning i can't just call self.bot.users is there another way?
no i doubt it
But how do I just get the message content to print as verification that the listener is working
Do you strictly need it in the startup?
Wdym?
You could wait until the bot is fully ready before doing that
If it's for a presence, that'd work
i dont see why it wouldnt work
Doing guild chucks causes rate limits, I want to avoid that.
That's why I'm writing here, because it is structured exactly the same as the existing code online
I can't have my bot just sit rate limited for 10+ minutes
That's the main issue, that's why I don't load the chunks on startup
command prefix as a raw slash? lmao

Yea, it cries if I put nothing, we don't actually have slash cmds.
Mb, I meant, we don't actually have prefix cmds
iirc you can put an empty tuple in there
I missed them 😔
They were alr
Hybrid were on top
Actually, fuck hybrid, I fucking hate those things, they were a mix of bs, if u got the prefix working, u would have to remember to make it work for slash too 😭
To much work
total_counts = [guild.approximate_member_count async for guild in self.bot.fetch_guilds(limit=None)]
total_users = sum(total_counts)
Well, this is my fix to my question, thanks to my glorious king @finite salmon
on god
❤️
how to go about making a command like this w/o api
What do you mean "without api"? And this screenshot doesn't really say anything about what this command actually does or what logic it uses
I know it's possible, I just don't remember how. How was it to make a button copy to clipboard something?
I'd guess make a URL button and redirect to a page that then adds the stuff to your clipboard
Don't know if it's possible any other way though
Ye ye!
I just read about it in StackOverflow
Thanks!
Link to post? 👀
okay thank you
Can masked links in messages be detected without using regex?
Why do you not want to use the tool specifically designed for detecting patterns in text
What kind of tool?
Regex
Asking how you find specific patterns in text without regex is like asking how you eat soup without a spoon
Just wondering if Discord had something builtin for this
It does, and it uses regex
To answer your question, discord does not send what links are in a message, so no
guys, is there a way to automatically send my robinhood trade positions to a discord channel?
for context, Robinhood is an investing platform that can also be used for daytrading
You can post whatever message you want to a webhook
how you create that message is entirely up to you
i mean, how can it be integrated into a python code?
Webhooks are just api endpoints with a specific payload. It's up to you to write the code that gets the info you need and crafts the message you want
Libraries like discord.py simplify sending to that webhook, but as far as it's concerned it's entirely on you the developer to figure out what message you want to send
do webhooks work if the bot is offline?
Webhooks aren't bound to a bot
If you have the webook url you can always send messages to it
My ephemeral isn't working, but there are zero errors.
I've also created a post if someone would like to help me out.
Are you deferring and then following up?
Uhh, not really. Just trying to fix it atp.
What's your code?
.bm - i'll take good note of it
Virtual environments are isolated Python environments, which make it easier to keep your system clean and manage dependencies. By default, when activated, only libraries and scripts installed in the virtual environment are accessible, preventing cross-project dependency conflicts, and allowing easy isolation of requirements.
To create a new virtual environment, you can use the standard library venv module: python3 -m venv .venv (replace python3 with python or py on Windows)
Then, to activate the new virtual environment:
Windows (PowerShell): .venv\Scripts\Activate.ps1
or (Command Prompt): .venv\Scripts\activate.bat
MacOS / Linux (Bash): source .venv/bin/activate
Packages can then be installed to the virtual environment using pip, as normal.
For more information, take a read of the documentation. If you run code through your editor, check its documentation on how to make it use your virtual environment. For example, see the VSCode or PyCharm docs.
Tools such as poetry and pipenv can manage the creation of virtual environments as well as project dependencies, making packaging and installing your project easier.
Note: When using PowerShell in Windows, you may need to change the execution policy first. This is only required once per user:
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
Nah
Just ask for help with whatever you need, here
Or do you mean with a bot? In which case you can
aaaaand guilds/clans are now gone
To clarify my reaction above, dont care about the clans feature itself, it does not effect me. But the many of the people who used them in scummy ways... im glad wont be able to do that
what scummy ways? what happened?
Abusing the fact that it was an experiment and only some people had access
ohh so people were selling clan tags?
among other things yes
@stark ingot how does externally setting a discord RPC work?
"externally setting"?
setting an RPC outside of discord
hence externally setting
You mean like set a presence from another app?
IPC connection
wtf man this channel has been quiet for 10 hours why is there slowmode
elaborate 
then it's just about sending the right commands
you connect to the IPC socket using its path
then send data to that connection, the data is the set presence command with the information
hm alright
also for websockets, what's the difference between that and a webserver
and what modules do you use for setting up websockets as opposed to a webserver
Websockets is more about sending/getting real time data, a web server can host a websocket endpoint for example
Depends the language/framework, some are very simple as you just need to "upgrade" the request to use websocket
Windows path is \\.\pipe\discord-ipc-0 iirc - Linux/macOS have another path
python first, but i might port this to JS to link it to my vscode
wait so what do i do with this
Then I guess websockets is probably the most common library for that
so a websocket can also be a webserver? or the other way around
Create a socket connection to it and send the commands, there's probably some simple code on GitHub/Gist for the most basic use
Most of the time it's a server and a client, the client creates a ws connection to the server so that they can send relevant data in realtime together
Instead of, for example, doing a request to a REST endpoint every 5 seconds to have the updated information
i feel so stupid rn
i dont get any of this
can i at least see some example code?
ehm wait
for Python there's https://github.com/qwertyquerty/pypresence
most of the code is not relevant, but the xlient/utils part to get the path and connect to it should at least get the rough idea of how it works
(with
websocket-client)
from websocket import create_connection
ws = create_connection(r"\\.\pipe\discord-ipc-0")
ValueError: url is invalid
am i just 
yeah because it's not the same
a socket connection to an ipc pipe isn't the same as connecting to and using a websocket
you just need the stdlib with socket module
you can look at how it works internally to make your own "alternative"
axo isn't slowing loosing it anymore, she lost it.
i am gonna punch my monitor in a moment
i dont get literally anything in this
it's cuz i dont know the structure of it so i have no fucking clue what goes where
yeha probably better to use libs then, they're made for that after all
i wanna know the whole process tho. thats my issue
then looking at the presence code is best
can anybody tell me how to lock a thread using bot command i'm using dpy
I only found delete in the documentation
Thread.edit(locked=True)
Forums hold threads lol
a post in forum channel is a thread
and a thread is just a channel type
Wym? There's a hybrid class that takes care of that. I converted to hybrid simply by changing the decorator to @hybrid... and it just worked 💀
hybrid_command didn't handle that all..? but okay.
Wym? could you rephrase
hybrid cmds were different than regular slash cmds
and certain arguments you had to treat differently
It's been a while since I used regular slash commands. But how different are the arguments? (not arguing btw just need a refresher)
First off, slash cmds require you to have typehints in arguments, and Hybrid does not.
Secondly, you would have to use keyword-only marker in hybrids, vs in slash cmds you do not.
Making it in my opinion, slash cmds betters.
@commands.hybrid_command(aliases=["j", "J"], description="Searches for Japanese words")
async def jisho(self, ctx: commands.context, *, arg: str) -> None:
page_view = PageView(ctx=ctx, arg=arg, data=self.word_search(arg))
await page_view.send()
This is my hybrid_command that was originally a prefix command. What did you mean by keyword-only markers? I really forgot how app_commands work (this is what you call slash cmds right?)
*, arg: str
* is the keyword only marker.
you would never need that in an actual slash cmd
wait hold up. gimme a sec to check something
What does it do to prefix commands I wonder
Nope that's wrong, I just checked. That's not why that's there. I wasn't forced to put that. It serves another purpose
I just ran the command without it
to understand what it does, you first have to understand what happens when you don't use it
you would need it for the prefix cmd?
not the slash cmd
Also wrong. I'm explaining the purpose of it rn
Normally, if you don't use the *, args syntax then what happens is, for every space you enter will be passed as an argument. For example
@bot.command()
async def calculate(num1, op, num2):
...
# on discord: !calculate 4 + 6
this is equivalent to saying calculate("4", "+", "6"). So it's just spaced arugments. If you add another space and do !calculate 4 + 4 + 6 then you'll get the parameter error (not enough parameters blah blah)
but if you could just do **kwargs to filter out extra arguments. But there's a catch. It might even be a bug idfk but you can't do it for large amounts of text for whatever reason and you also don't get quotations from text. what the *, arg does is treat every space as part of the argument including all special charactors and quotations. It's NOT NEEDED for prefix commands. It just depends on what you wanna do. I originally used it for a google translate api because having all you text in one string with all quotation is pretty handy for translating
Idk why it took me so long to type that @vapid parcel@naive briar
Yes, but most arguments will need *, not saying you NEED it in every cmd, but if you are making a cmd with a default value like reason= or another thing, you will be using *, and I had a lot of cmds like that, and thats why I just don't like hybrid cmds. I understand what you are saying, but a majority of hybrid cmds will be using *.
I thought the argument here was it is absolutely required to use the *


