#discord-bots
1 messages · Page 387 of 1
If this is user message content, are you implementing the privacy protections you have agreed to in the TOS? Unlikely you have a robust system for looking through these files if someone invokes their right to be forgotten
Frankly; not too sure how all that works; but it's a transcript thing, for the ticket. For support.
That does not waive you of the responsibilities you have agreed to
Alternatively you could just let people use discord and not try to handle this yourself
As I mentioned; it's just a transcript tool; for my discord ticket bot, for support? It's not interferring with discord's thing directly?
It is. You are interfering with privacy features, namely people's ability to request their messages be removed
just leave the messages in discord. People can read them there
Sure, and if I get a message from discord; saying that a user has requested their data to be deleted; I have no issue doing so, within my panel; however for the likeliness, and integrity of my server; I'd prefer to keep tickets logged.
And it can be logged. In discord
what mechanism do you have for a user to request you for their data to be deleted? How are you going to do so? This is not discord asking you, you have agreed to grant this directly to users
Is this data encrypted at rest?
It'd be only me and the person who created the ticket; who have permission to view the transcript?
that doesn't impact the responsibilities you have agreed to.
Don't most or popular tickets bots have transcript system though?
Someone doing something doesn't mean it is okay or legal to do
That doesn't matter
Someone breaking a law doesn't mean you get to
Like why the bot ain't banned or something
The TOS are clearly outlined. And this server's rules say you are not allowed to ask for help in breaking TOS. Someone else breaking the TOS and getting away with it don't factor into either of those 
At the end of the day, you can view "tickets" just fine in discord. If you want to pull those things out of discord, you have a whole slew of things you are responsible for. It isn't worth the headache, you can just use what already exists and users' privacy rights will be automatically maintained. Given you don't know what those responsibilities even are, you certainly have not implemented them. It's up to you if it's worth it, but that's not something you can just skip and worry about later
Homie you are just yapping 😭
Apologies; but this guy.. is just yapping LOL
Again. People doing something is irrelevant
Unless you are implementing user privacy protections you have agreed to, which you have made clear you are not, this is against TOS. Other people also violating TOS does not change that
That's js?
yes
This is the python server 😂
how do i know if is it js or no im just saying thats js
node index.js
so what do i do
You should probably learn the basics of programming before trying to create a bot
There's a discord.js server (assuming that's what you're using) that will give you better help
Hi. We don't appreciate the use of ableist language here, or personal attacks. Please don't do that again. Thanks.
Hey there, yeah my apologies; but that guy is just 😡
You can just use thread bud which will save u alot of headache all will be saved in your channel as well ,u can look into private threads which is more efficient
I personally just use them as ticket and with ticket(threads) i don't even have to save anything in my db all are saved in discord itself which saves my db resources as well
Guys, will you guys help program a bot?
I need help
import discord
from discord.ext import commands
intents = discord.Intents.default()
bot = commands.Bot(command_prefix='=', intents=intents)
intents = discord.Intents.default()
intents.message_content = True
@bot.command(name='H')
async def hello(ctx):
await ctx.send(f'Hi!')
This ain't wokring
working
What is happening, and what do you want to happen?
You define intents twice and you don't turn on message content until the second one, after you already pass it to bot
(That should also result in a library log saying as much)
If I want to select emoji with context menu does discord.Emoji will work as method parameter of context menu ?
context menus only accept messages or users
Oh so I need to check the message type then tnx for the info
hey so, i have this py for server in client.guilds: print(server.name) and i want to make it so that it assigns the servers name to a value so that i can use a function specifically for that server (like getting information about the guild) from the command prompt
i just cant comprehend how to do that right now,, 
I have another bot for testing new features, and if everything works well, I push it to the remote repository and pull it on the server where the main bot is.
this is how we test @unkempt canyon
Thanks bro i was actually checking that repo earlier and I noticed they were only linting or testing functions but not actual bot commands, still I haven't checked this directory yet. I'll check it out!
but do you test it manually?
I have 2 ways, manually and automatically
it's generally a good idea to have multiple methods of testing yeah
Yeah
it may be valuable to have a mix of unit tests and E2E tests for instance
how do you do it automatically
On discord bots can not run app commands so you would have to make fake data that you could feed the command callback
yeah thats what im currently doing
You can input the guild's id in the command line and use bot.get_guild to get the guild's object
!docs discord.ext.commands.Bot.get_guild
get_guild(id, /)```
Returns a guild with the given ID.
Changed in version 2\.0: `id` parameter is now positional\-only.
I do suppose that does work, but I was hoping It could be something where you just type like 1 and it selects the first server. Actually couldn’t I do that using a json file? 😅
well, bot.guilds returns an array object which you can index, so if you want the first server you can do client.guilds[0], and for second server client.guilds[1], and so on
something where it writes ”1”: “servername here” in a json file on every start and read/writes ig
oh!! Okay!!
not the best practice to store servers' names as they are changeable variables, a server's id is constant tho
Yeah makes sense, I just meant that in general it could work lol
also I don't think you'd memorize the order of your bot's servers
Hey, how can I make a bot run with a server? Like hosting you know, any free plans available?
however, if you want to get the server by name you could loop through the bot's guilds and use an if statement inside the loop to check whether it's the server you're looking for and if so return its data
it'd be something like this
names = ["zika", "seif"]
for name in names:
if name == "zika":
print("hello world")
hm, i reckon I could do
num = 0
for server in client.guilds:
print(f”server {num}: “+client.guilds[int(num)])
num = int(num) + 1
serverchoice(“Server to operate on:”)
do.stuff(client.guilds[int(serverchoice)])```
!d discord.ext.commands.Bot.get_guild
get_guild(id, /)```
Returns a guild with the given ID.
Changed in version 2\.0: `id` parameter is now positional\-only.
Sorry aha I was typing that on mobile 😅
you may just use that to get it
So it would simply be something like inputting a number choice
oh nvm, sorry
All good, I’m a bit bad at putting my thoughts into words and asking for help in general so if there’s a misunderstanding it’s 100% my fault lol
Nope, I just didn't read the whole thing so that is mb
So according to this, you want to get information on a guild based on your input
why do u want to know the order of the server
you could just get_guild if you have the id
.
Well like for servers that it’s in lol
Yep, so what type of input will it be?
Like if you put the name of the server, you could just use the example given above
using a for loop
well if my code works, it should just be like inputting 1 or 2 yk ?
server 1 or server 2?
hm
Well you could store the server number in a data base for example
Server number | Server ID
1 | 42394839438294832
and basically you fetch the server ID based on the server number that you searched for
you would also have to account for when the bot leaves a server, what number that should be etc
well yeah I just don’t need to store them lol i just suggested json as opposed to typing out or copy and pasting the ID
Don't use a json as a db
But the last line applies, that’s basically what I’m going for
If I stored IDs and stuff it would bloat overtime and eventually get too big, all I wanna do is be able to do is fetch some info by typing a number, so this should work
Thanks! :3
how can i remove someone from thread? when i do remove user it doesnt fully remove the member from the thread rather on its name slash is there
i want that person to completely remove from thread
you could create a list of guilds and then select it
guilds = [guild.id for guild in bot.guilds()]
selected_guild = guilds[YOUR_INPUT+1]
guild = bot.fetch_guild(select_guild)
This is so you don't have to create a database
guilds is to create a list of all guild ideas, then selected_guilds is to get the guild you want from that list and guild is to fetch that guild based on the selected_guild id
!d discord.Thread.remove_user
await remove_user(user, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Removes a user from this thread.
You must have [`manage_threads`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_threads) or be the creator of the thread to remove a user.
i am doing this only
but there is slash coming on that name
when i remove them
Do you mind sending a screenshot?
one sec let me see if i have those
see the person
he is not in thread
thats why slash is on its name
dont know why this happening
Can I see your code please?
sure let me open vsc
if check_clan_player.clan:
clan_data = await self.bot.db.fetch_clan(
clan_tag=check_clan_player.clan.tag
)
if clan_data:
mem_channel = await interaction.guild.fetch_channel(
clan_data["channel_id"]
)
stat_channel = await interaction.guild.fetch_channel(
clan_data["clan_stat_thread_id"]
)
clan_chat_channel = await interaction.guild.fetch_channel(
clan_data["clan_chat_thread_id"]
)
if user in mem_channel.members:
await mem_channel.set_permissions(
target=user,
overwrite=None,
reason=f"{user} have been removed from {mem_channel.name} channel. ",
)
if user in stat_channel.members:
await stat_channel.remove_user(user.id)
if user in clan_chat_channel.members:
await clan_chat_channel.remove_user(user.id)
player_leader_role = discord.utils.get(
interaction.guild.roles, id=RoleIds.LEADER
)
if player_leader_role in user.roles:
embed.add_field(
name="Position role unlinked",
value=player_leader_role.mention,
)
await user.remove_roles(
player_leader_role,
reason=f"remove {str(check_clan_player.role)} from {user.display_name} which is of {check_clan_player.clan.name}({check_clan_player.clan.tag})",
)
await interaction.client.get_channel(Logs.PLAYER_LOG).send(embed=embed)
mainly i am doing on this part removing the person
its not very optimised but it works
Okay!! Thank you! :333
just the slash thingi is there it doesnt cause much problem but leaves the user with slash in thread
np!
@vocal laurel anything wrong in my code : ( or its just a discord bug or something?
Im not sure tbh
oki : (
the code doesnt seem like the problem
is it possible to make commands for user installed bots in py? cause i made a command which works on my server but doesnt show in dms
and every example i have managed to find is in js
!d discord.app_commands.allowed_install
No documentation found for the requested symbol.
!d discord.app_commands.allowed_installs
@discord.app_commands.allowed_installs(guilds=..., users=...)```
A decorator that indicates this command should be installed in certain contexts. Valid contexts are guilds and users.
This is **not** implemented as a [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check), and is instead verified by Discord server side.
Due to a Discord limitation, this decorator does nothing in subcommands and is ignored.
New in version 2\.4\.
Examples...
^
thank you
Hello, I want to create a bot that is similar to @unkempt canyon
Specifically made for a certain server i own
Good luck and enjoy coding it
how to do it
i know a lil py
but not discord.py
couldn't you fork the bot and run your own instance?
@unkempt canyon's source code is available in https://github.com/python-discord/bot under a MIT license
i wanna add some adjustments to it
also i want something specific from this bot
!rule 3
this one
you are free to take what you want from that code and modify it how you please
how to do it
!source rule
Provides a link to all rules or, if specified, displays specific rule(s).
omg thanks!
is commands.bot_has_permissions and app_commands.checks.bot_has_permissions the same?
No
If you're not able to disable it you should contact Discord support, that shouldn't be happening and there's not much anyone here can do about it
First is for prefix commands, second for app/slash commands
Likely because you have set public link, which isn't allowed for private bots, so remove that and then should be good
Yeah, jus removed them.
thanks!
👍
I stand corrected, I need to un-rusty myself with the current status of bot dev apparently
Guys.
Do i need __init__.py for my bot
have no idea what it does
but seen it @unkempt canyon in repo
That really depends on the context, __init__.py is essentially how you create a module, so if you had a folder called abc with an __init__.py in it, and that file contained - for example - a setup() function for a Cog, you could import that folder as simply abc rather than abc.something if the file was called something.py. It basically lets you organise your code if you need multiple files grouped together. Python Discord's bot is a large bot with a ton of code so that sort of structure is necessary to keep track of it, but if you have a small bot you can get away without those files for now (though familiarising yourself with them and what they do is great for your learning journey, and I'd highly recommnd looking into the structure of Python projects more)
also what should I add to my bot? like features, cogs etc
im new and this is my first bot
i want my bot to be like @unkempt canyon and lil bit of @lament depot
Thanks, I understand!
So i dont need init for now ig
Just think of a couple of things to start with, a couple features you know you want, and go from there. Rushing in with a ton of stuff will burn you out quickly - try and pick the things you're really excited about as the features you make first
Noted!
IMO there are two distinct things here
- if you're trying to learn the library, hello world + very simple api interactions. Have a hypothesis for what you want to learn
- if you're trying to make something useful, actually observe a problem and design a novel solution to it. Rewriting the 10 features every bot has just makes you 97538th in line
Noted! thanks
there's a song I can't remember the name of with a lyric to the effect of "if I hear one more love song I'll be sick" and I think we need a adaptation for the bot community that goes "if I see one more generic multipurpose bot I'll be sick"
not doing anything rn but should i create commands with prefix first and convert them to slash?
If I were starting out now I'd ignore prefix commands, they're not liked by Discord and are gradually losing support in favour of slash commands. Unless you find something that you really can't find a way to make with interactions-based stuff (i.e. slash commands, buttons, menus, etc.) I wouldn't bother touching them
noted
Give me some i can code with python on my discord bot, can't be to hard.
Replay if you got some,.

😂
could someone give me an example on how to use userinstalled bots in discord.py? ive been trying for hours now and it works in my server but doesnt show in dms
you need to set allowed contexts and allowed installs on your commands
this sets where you can have the slash command: ```py
@app_commands.allowed_installs(guilds = ..., users = ...)
and this sets where you can use the slash command: ```py
@app_commands.allowed_contexts(guilds = ..., dms = ..., private_messages = ...)
dms is messages with the bot, private_messages is messages with other users
should it go under the command?
nevermind i figured it out
tysm
its a decorator
How do i make an embed?
Make a discord.Embed object -> call methods on it to set fields and whatever you want -> send it on a message with the embed= arg
Hope this is the appropriate channel for this. I have a discord.py bot that posts a message with some reactions. Users react to this message to have roles assigned and removed. It all works great but breaks whenever the bot restarts. Tried using a few different datasources to store the info of the reactions, channel_id and message_id and they all seem to work ito storing and retrieving but whenever the bot restarts, the functionality of the "Reaction Message" is lost. I have a workaround but it's less than ideal. It involves recreating the reaction message whenever the bot starts.
Any ideas? Is there some limitation in the API to prevent this functionality or perhaps a setting or two I missed in the Developer portal?
Consider using a persistent view with a selective menu to assign roles to users.
Or consider using the built in onboarding channels & roles dialogue, then you don't need a bot running at all
I'm giving this a go, thanks
Hmmm thanks for the suggestion, I like that. However, this won't work here as existing users will assign and unassign one role ceaselessly. I might look at using this for new users tho! 👍
@fast osprey
import os, shutil, aiohttp, aiosqlite
from discord.ext import commands, tasks
class Tasks(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self) -> None:
self.backup_database.start()
print(f'Cog {self.__class__.__name__} is ready')
@tasks.loop(hours=168)
async def backup_database(self):
if os.path.exists('src/database/backup.db'):
os.remove('src/database/backup.db')
shutil.copy2('src/database/bot.db', 'src/database/backup.db')
async def setup(bot):
await bot.add_cog(Tasks(bot))```
## How could I improve it or what aspects were wrong?
You really should not be using on_ready to drive functionality. This happens repeatedly and randomly
There's also really not much of a point in having a cog that has a single thing in it, it's just unnecessary boilerplate imo
So where in async does the task start? I can't think of any other way than on_ready
You can just make a normal ass task and start it in the setup
don't need a cog or on_ready at all
@tasks.loop()
async def whatever():
...
async def setup(bot):
whatever.start()
in my bot.py?
alr
or in an extension, wherever you want
What is the difference between saying cog and extension?
Entirely different concepts, the docs have pages on both
Do you still need it? @slim bloom
yeah
I can't find docs for it but afaik, extensions are files that you load into your main file and cogs are groups of command put into an extention that you then load into your main file
async def setup(bot):
await bot.add_cog(Tasks(bot))
cog = Tasks(bot)
cog.backup_database.start()```?
if its within a cog just start it in cog_load
!d discord.ext.commands.Cog.cog_load
await cog_load()```
This function *could be a* [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A special method that is called when the cog gets loaded.
Subclasses must replace this if they want special asynchronous loading behaviour. Note that the `__init__` special method does not allow asynchronous code to run inside it, thus this is helpful for setting up code that needs to be asynchronous.
New in version 2\.0\.
Oh no, I'm running into the exact same problem. I tried to implement your suggestion and again, it works a treat, but the functionality breaks when the bot restarts. Choosing another option results in this error I'm not sure how to troubleshoot. Thanks for the suggestion, back to the drawing board.
Oh really? Okay will check that out next thanks.
how can i make my bot work like this that i can specify the argument in a prefix command?
!ban user=@someone reason="rule 1"
see flag converter
set delimiter='='
where do i put that?
in the class def of the flag class, the doc shows an example of it
im getting
discord.ext.commands.errors.MissingFlagArgument: Flag 'user' does not have an argument
this was my code
class BanFlags(commands.FlagConverter):
user: discord.User | discord.Member
reason: Optional[str] = None
@commands.command()
async def ban(ctx: commands.Context, flags: BanFlags):
await ctx.reply(flags.user.mention)
you need *
!intents
lol
anybody knows how to code the new Group Chat update for bots?
Defines an async function
What discord library are you using?
Can someone tell me what a discord bot is
a bot user that uses code to interface with the discord api
Thanks.
How to fix this it won't response just trying to make a simple Bot
I'm just a beginner
!message-content-intent
The Discord gateway only dispatches events you subscribe to, which you can configure by using "intents."
The message content intent is what determines if an app will receive the actual content of newly created messages. Without this intent, discord.py won't be able to detect prefix commands, so prefix commands won't respond.
Privileged intents, such as message content, have to be explicitly enabled from the Discord Developer Portal in addition to being enabled in the code:
intents = discord.Intents.default() # create a default Intents instance
intents.message_content = True # enable message content intents
bot = commands.Bot(command_prefix="!", intents=intents) # actually pass it into the constructor
For more information on intents, see /tag intents. If prefix commands are still not working, see /tag on-message-event.
couple things:
- post your code as text next time, images of a phone screen are hard to read
- reset your token
I am having a problem with my help command. With the code sent below, the bot sends an embed but creates 2 fields within the embeds for the commands (basically creating it for each category/cog). However I want it to send all the commands in 1 field regardless if it has a category or not, how would I go about doing this?
async def send_bot_help(self, mapping):
em = discord.Embed(title = "Help Command")
em.color = discord.Color.from_rgb(93, 211, 251)
for cog, commands in mapping.items():
filtered = await self.filter_commands(commands, sort=True)
command_signatures = [self.get_command_signature(c) for c in filtered]
if command_signatures:
em.add_field(name="Commands", value="\n".join(command_signatures), inline=False)
await self.get_destination().send(embed=em)
just this? ```py
all_commands = []
for ... in mapping.items():
...
all_commands.extend(command_signatures)
all_sig = '\n'.join(all_commands)
it works, tysm
What's the discordpy thing to have loops etc?
NVM. Figured it out :D https://discordpy.readthedocs.io/en/stable/ext/tasks/index.html?highlight=tasks#discord.ext.tasks.loop
Thanks chat
Is there a discordpy thing to make a task run at a specific time every week? say monday 12pm?
yes
https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html
https://fallendeity.github.io/discord.py-masterclass/tasks/
A hands-on guide to Discord.py
u can enter the time but for checking the day u can use the tzinfo and something like calendar module to check if it's that particular day in like before_loop
What is the main language and libraries for discord bot???
there is no "main" language/library
Python and discord.py is one choice
Ok thanks
guys
i need a funcition who let only to users who has 'admin' role to use mod commands like 'ban',mute ecc. with my bot
for slash commands:
@app_commands.checks.has_permissions(administrator=True)
for text commands:
@commands.has_permissions(administrator=True)
You should really not be overriding mod actions that already exist in the client, you are actively reducing their security.
If you want to restrict app commands, you should use the default_permissions decorator rather than a local check
if you are looking for permissions, then use the deco suggested above, however if you are looking for roles, then you would use
@app_commands.checks.has_role() #checking for 1 role
@app_commands.checks.has_any_role() #checking for multiple roles
^ for app commands (aka slash commands)
@commands.has_role() #checking for 1 role
@commands.has_any_role() #checking for multiple roles
^ prefix/text commands
App command role limiting should be done from the integrations menu, not a local check
@bot.tree.command(name="add_role", description="add a role to a member")
@commands.has_role('Mod')
@app_commands.describe(member="The member to ban", role = "the role to add")
async def addrole(interaction:discord.Interaction,member: discord.Member, role: discord.Role):
emb = discord.Embed(title='addrole',description=f'the role {role} as been added to {member}')
await member.add_roles(role)
await interaction.response.send_message(embed=emb)
this is the command add_role
but everyone in my server is able to use it
what's wrong in this script?
youre using the text command decorator instead of the slash command decorator
it should be @app_commands.checks.has_role('Mod') instead of @commands.has_role('Mod')
Or this
And there are several reasons why you should use the integrations menu instead
This code also lets people grant others roles they shouldn't be allowed to. You can already grant roles from the client
hi guys, just wondering why instead of image, the code is giving me base64 text
sometimes images are b64 encoded
@bot.command()
async def imagine(ctx):
api = Text2ImageAPI('https://api-key.fusionbrain.ai/', '7D62CC5E605', '974CDBCAA8EE6910F74')
model_id = api.get_model()
uuid = api.generate("Sun in sky", model_id)
images = api.check_generation(uuid)
print(images)
heres the code
there is some bots that has a premiuem subscreption
and every premuim subscriber has its own bot with name and photo changable
the bot has same commands of the original bot but with more commands and featuers
how is that possible?
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: string indices must be integers
no wonder why im getting this error
You can spin up multiple bots and just run multiple processes with different tokens. That said, it is against TOS to share creds/tokens with someone who is not a service provider outlined by the TOS
Where exactly is the check for invite links? Because I cannot find it
Can you resume the interaction after restarting the bot?
show the code
it runs automaticlly
could you give me example for how to run that automaticcly pls?
so you want to make a public bot
that everyone can puts in their servers
and they could get more commands
by subscribing
?
probot if you know it
has premuim suscreption that you can by automaticlly that gives you ur own bot
if mean that making new app no
maybe they store some bot tokens and when someone by it runs a new bot by taking a token from database
There is not an automatic way to make bots, period
not without violating tos
Sure you could make a bunch of them in bulk, but there's still a limit. There's no functional need to do this. People can live without putting their dumb anime profile pic on a bot, just use the one bot
Is it possible for the delete_message_seconds parameter to not selectively delete messages from a specific channel upon a ban?
There is nothing about excluding a channel
discord doesn't provide that afaik
What are you trying to accomplish?
I want to delete all the user's messages from the past 24 hours upon a ban, except those from a specific channel
doesnt discord already do that?
No, you cannot exclude a channel from keeping messages
It will delete all messages
This example for using app commands in discord py is 2 years old, is that ok or have things changed? I'm new and I just want to make sure I'm not learning from an outdated example
https://github.com/Rapptz/discord.py/blob/v2.4.0/examples/app_commands/basic.py
2.4.0
That is the example published with 2.4.0, which is currently the most recent stable version
I see, thank you
In general, it's not too terribly unlikely for some core things to not change at all within a major version (2.x.x). Any additions will be backwards compatible anywho, so in theory any example written in 2.0.0 will work for any 2.x.x
First of all, you leaked your token
Second of all, you’re not passing any arguments
Third of all, are you using the correct prefix?
Fourth of all, you don’t need to set a name for a command if it’s going to be the same as your function name anyways
Fifth of all, is your command tree set up properly?
bro I want to familiarize with this who wants to make a project or just do something
Best way to convince people that you're serious and good to work with is to put forth the effort to learn on your own and have examples of your work that you can show IMO
Almost all projects start as a solo dev that makes the base of the code than showcase their project in the relevant community. Sometimes people will see it than want to help.
It also helps if you have a unique idea, as more people will be interested
Did you just leaked your API key?
made it shorter
so the api key is longer than short one
anyone can help me about automation script already ended working but something wrong cuz one script won't working but no error i can't understand why don't working
idk where to post
Is it about discord bots?
anyone can give me proxy scraper?
I'm working on a new verification system for my Discord server using captcha
can u edit a webhook in py
Uhm how to make command invisible for user that has no specific role?
For app commands, the integrations menu on the guild
Why do I sometimes get interaction failed when clicking a button, but it works again after restarting Discord?
I don't need to restart the bot, just my own Discord client
You have to sometimes restart your discord client to get the latest changes from your bot
Why?
Thats just how discord is
sometimes it doesn't instantly refresh on your discord client
So there is no need to use await interaction.response.defer() if the issue is solved by restarting my Discord client?
yep
My final server captcha verification
Generally that would only be for app commands not buttons
I don't know why, and I can't reproduce the error
@stark ingot Do you have any solution?
No, I have no idea why a button gets fixed when you restart discord
I assume you mean there is red text on discord that says interaction failed?
Correct
Maybe I should use something else instead of timeout=None on the view?
Well if the view needs to be persistent than you have to use timeout=None
I need some fresh set of eyes on this..
Why is that line grayed out? it should work..
🤔
What'd I do wrong chat?
Definitely not an indentation issue..
because you did "if not steamid or steamurl"
i think you meant "if not steamid or not steamurl"
right now if a steamurl is given, it satisfies the first if and will send the "please enter id or url" msg
discord.py doesn't allow setting required options?
Yeah I asked in general chat and they helped me find it lol. I didnt notice it before
It does.
I made a mistake with my code.
so my solution would work?
Here's the full corrected finished code now.
@app_commands.command(name="connect", description="Connects your steam account to your discord account to claim rewards")
@guild_only()
async def connect(self, interaction:Interaction, steamid:str=None, steamurl:str=None):
await interaction.response.defer(ephemeral=self.config['ephemeral_response'])
if not steamid and not steamurl:
await interaction.followup.send("Please enter either a steam ID or steam URL.", ephemeral=True)
return
if steamurl:
steamid = await self.functions.steam_profile_using_url(url=steamurl)
response = await self.functions.update_discordid(steamid=steamid, discordid=interaction.user.id)
if response:
await interaction.followup.send("Successfully linked your discord account to the steamid!", ephemeral=self.config['ephemeral_responses'])
else:
await interaction.followup.send("That steamid is already linked to a discordid. Consult the staff to resolve this issue.", ephemeral=self.config['ephemeral_responses'])
``` works no issues
yay
Wait. it should be and not steam url
@scarlet tiger - You can set a paramater to "None" or a preset value and it becomes optional. If you don't define a value it becomes mandatory.
You can also do things like set a parameter to discord.file or i believe it's discord.member or int or a boolean
I cant remember all of them but that's some of them
oh and discord.channel
by setting it to these specific paramaters you remove the possibility for your members to mess up the command, for example setting it to discord.channel creates a menu where the user can find the desired channel. similarly for discord.member
I do it another way and I didn't remember that it could be done that way too

I always opt to create everything in such a way that the end user, no matter how dumb or intellect they are, cannot mess it up.
I hold their hand as much as possible.
;-; Great new issue, error. Finally decided to run my code..
AttributeError: module 'discord.ext' has no attribute 'tasks'
My imports:
import json
from datetime import datetime, timedelta
from discord.ext.commands import Bot, Cog
import discord.ext
from discord import app_commands
from discord.interactions import Interaction
from discord.app_commands import guild_only
from plugins.seeders.supportfiles.embeds import seeders_embeds
from plugins.seeders.supportfiles.functions import seeders_functions
My code:
@discord.ext.tasks.loop(minutes=1)
async def check_seeders(self):
reset_points = await self.check_start_of_week() #Checks if it's the start of the week.
#The rest is not needed
🤔 is it an import issue? i think it is
Alright. it was. had to do from discord.ext import tasks
How do I send multiple embeds? I tried await interaction.followup.send(embeds=[steam_embed,base_embed], view=the_buttons) but it breaks lol
What does "it breaks" mean?
discord.app_commands.errors.CommandInvokeError: Command 'stats' raised an exception: AttributeError: 'NoneType' object has no attribute 'to_dict'
C:\Users\decla\OneDrive\Desktop\discordbots\developerbot>
Traceback (most recent call last):
File "C:\Users\decla\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\discord\app_commands\commands.py", line 827, in _do_call
return await self._callback(self.binding, interaction, **params) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\decla\OneDrive\Desktop\discordbots\developerbot\plugins\stats\stats.py", line 50, in stats
await interaction.followup.send(embeds=[steam_embed,base_embed], view=the_buttons)
File "C:\Users\decla\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\discord\webhook\async_.py", line 1785, in send
with handle_message_parameters(
^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\decla\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\discord\http.py", line 172, in handle_message_parameters
payload['embeds'] = [e.to_dict() for e in embeds]
One of those things is None
like my variables?
my embed variables? impossible. if it's getting to the point where it's sending the messed it means the embeds generated as intended
nope. nevermind. was possible. lol
i forgot to return 1 of the embeds xD
Ty @fast osprey
What is a good way to clean old entries in a dictionary when users interact with buttons?
Do it in a background task, cleanup in existing code or use something like caching library?
That's pretty vague, as is it's not clear how these buttons relate to this dictionary
It's for the captcha verification I told you about
What's the problem you're trying to solve?
Clean old entries from the dictionary
With only 10min you might be able to get away with an asyncio sleep
Why?
Because that is the point of a cool down?
Because the list is going to grow over time
And there is no need to keep track of these users
You could also start an ext.task for 10 min and only runs once but that might be unnecessary
Do you have reason to believe that it will grow enough to matter?
This really seems like optimizing before you actually have a problem
This is on the order of a handful of bytes
If you're already using the members intent, for example, that's already orders of magnitude more memory imprint
Anyway, what would be the best solution for implementing some kind of cleanup in this case?
You could make a task run every 30min to an hour that loops through the dict and removes old entries
this looks similar to dpy cooldowns, in their case they just clean up keys anytime a cooldown check is done
https://github.com/Rapptz/discord.py/blob/v2.4.0/discord/ext/commands/cooldowns.py#L119-L126
discord/ext/commands/cooldowns.py lines 119 to 126
def _verify_cache_integrity(self, current: Optional[float] = None) -> None:
# we want to delete all cache objects that haven't been used
# in a cooldown window. e.g. if we have a command that has a
# cooldown of 60s and it has not been used in 60s then that key should be deleted
current = current or time.time()
dead_keys = [k for k, v in self._cache.items() if current > v._last + v.per]
for k in dead_keys:
del self._cache[k]```
So cleaning on interaction is the best way to go about this?
I was considering that once every 24 hours should be enough too
the "best" way? i suspect both approaches have negligible differences for this workload
perhaps in heavy traffic (say, 100/s) you might experience slightly excessive cpu usage from checking each time, but at that point you'll likely have bigger bottlenecks
Why not less than 15 min?
If your cool down is 10 min it does not make much sense to check more often. And just a 5 min buffer. Not a fact but just my intuition that says you shouldn't :)
I could implement it as you suggested during interactions https://paste.pythondiscord.com/53TQ
Or I could run a task periodically to handle it
How would you personally implement this?
Oh, yes, of course, there is no need for that. I just don’t see why it should grow over a longer period of time
You can't make a good assessment on caching strategies when you don't even know how you're scaling. You're just assuming this will be a problem without proving it
you can't solve the problem until you quantify it, and I can guarantee from here that it's not a problem to begin with
So hypothetically, keeping track of thousands of users over a three month period is better than cleaning up users you no longer need to track?
I'm interested in why you see cleaning up old entries as an issue
The same reason why crawling through your code base and minimizing every variable name is an issue. This doesn't matter in the grand scheme of things, and if you can't quantify it you're just picking random things to optimize
You cannot make an informed decision without information. If you don't know what is taking up memory and how much memory it's taking up, this is just guess work looking at code and theorizing it's something that needs fixing without having a way of proving that it got fixed. If your optimizations are not rooted in empirical evidence and just whatever you happen to notice, your code and your sanity are going to suffer.
How do i install the discord.py library?
Put pip install discord.py on your CMD or Terminal
where do i run that
in terminal?
yep
and then i can use it in vsc?
Indeed
okay ty
:)
how do i put it on path?
sorry for all the q's
You could do it manually or just uninstall Python and install it again by clicking on the "Add to PATH" option in the installer, and it will do it for you.
i don't really wanna uninstall python again 😭
ok ty
it says this
You need to select the py launcher option when installing python
reinstall python
and on the first "screen"
like the first thing that appears
there should be "add to path"
to put python code in vsc you need to install the python extension
add python.exe to PATH?
done
then should be good
alr thanks
btw anyone got a way to lock an entire server with multiple role ?
like i mean when i lock a server i can only unallow a role to send messages
while there are other roles like helpers staff etc that i need to unallow aswell
but im getting rate limited because of the amount of role
now i gotta learn how to make discord bot
goodluck
Allows supercede denies. Just deny send message on @everyone and allow on the roles you want
Is this still valid?
Did you install Python correctly?
I think so
It didnt really tell me to do much so
Run this in your terminal python --version
I will when I get home
Ok 
It says 3.12.5
Try python your_file.py
Are you in the correct directory for your bot?
i have no idea
Do you use VSC?
yeh
Make sure to open the folder where the bot is
you mean the bot code?
It's not code, the error says that the file directory is not correct
i don't understand
Can you send me a screenshot of your VSC?
I want to see the files tab
this part?
Save your bot file in a folder and then open that folder
bot file?
the .py file bruh
Now let me see your terminal
in vsc?
Ye
Ok now run python your_file.py
how is invalid syntax
You need to put your token lol
Let me see the rest of the code
You need to enable privileged intents from the Discord developer portal
i looked around for that but i couldn't find it
!message-content-intent
The Discord gateway only dispatches events you subscribe to, which you can configure by using "intents."
The message content intent is what determines if an app will receive the actual content of newly created messages. Without this intent, discord.py won't be able to detect prefix commands, so prefix commands won't respond.
Privileged intents, such as message content, have to be explicitly enabled from the Discord Developer Portal in addition to being enabled in the code:
intents = discord.Intents.default() # create a default Intents instance
intents.message_content = True # enable message content intents
bot = commands.Bot(command_prefix="!", intents=intents) # actually pass it into the constructor
For more information on intents, see /tag intents. If prefix commands are still not working, see /tag on-message-event.
i have to put that code in?
Your code is fine, you need to go to the Discord developers page
Go to Bot
this?
Enable this
hey so using input blocks the things heartbeat, i tried using threading to fix this and im certain i did it right but it still blocks the heartbeat :p any workaround or do i just have to remove that function entirely or make my decision within 10 seconds lol
input as in terminal input?
No problem
yeah :p
Why not just instruct your bot through discord?
You have basically a better terminal already
the goal was to be able to fetch information on a guild through the terminal, ig it’s just a quirky way of doing it lol
but I think the problem is that I have the input inside the on_ready function
Yeah but...you could just do it from discord
or is this meant to do one thing and then exit? You don't need a connected bot
Hey
I need help with my python code
An error occurred: Command raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embeds.0.fields: Must be 25 or fewer in length.
@bot.command()
@commands.cooldown(1, 300, commands.BucketType.user) # 300 seconds = 5 minutes
async def viewteams(ctx):
managers = load_managers()
if not managers:
await ctx.send(f"No manager information found. | {ctx.author.mention}")
return
embed = discord.Embed(title="Team Information", color=discord.Color.blue())
for manager_id, team_name in managers.items():
manager = ctx.guild.get_member(int(manager_id))
if manager:
team_role = discord.utils.get(ctx.guild.roles, name=team_name)
if team_role:
team_members = len(team_role.members) - 1 # Excluding the manager from the count
embed.add_field(name=f"Team: {team_name}", value=f"Manager: {manager.mention}\nTeam Members: {team_members}", inline=False)
else:
embed.add_field(name=f"Team: {team_name}", value=f"Manager: {manager.mention}\nTeam Members: 0", inline=False)
else:
embed.add_field(name=f"Team: {team_name}", value=f"Manager ID: {manager_id}\nTeam Members: 0", inline=False)
message = await ctx.send(embed=embed)
# Message timer
for i in range(30, 0, -1):
embed.set_footer(text=f"Embed deleting in {i}")
await message.edit(embed=embed)
await asyncio.sleep(1)
await message.delete()```
You're sending more than 25 fields in an embed
dont cross post, I already answered in your thread
how does the bot create its own invite if its not even in that server its in and supposed to use my own invite?
Please rephrase your question.
You want to know why it says to get a new invite from the "nss portal bot" when the bot is not in the server?
sounds about right sure
I think that is just how discord works. It really means nothing for bots as "asking for a new invite" from a bot is not relevent.
Help pls!
Error said that textchannel doesn't have attribute send
You're calling send on something that's None
basically yeah
also whaa?
basically i was writing it to be able to grab info on a guild or user but was thinking about expanding into some more stuff so i wanted to not have to change the code later which is why im doing it this way now
That’s not what it says
What are you calling .send on, and why might that be None?
any idea why this isnt pinging the role correctly?
i was told an extra ampersand but even without it it fails
You cannot ping roles/people in embeds. You have to put it in the message content
nvm turns out i was using the wrong role id ☠️
Why are you using & anyway?
And the & at the end breaks it
<@&roleid> mentions a role
yea i checked stack overflow they told me to do that but that failed obviously
I think it will still display the ping it just will not actually ping anyone
yea thats even better
ty friends
actually one more question, this is sending as LITERALLY ## TOP 5 KAISERS instead of
TOP 5 KAISERS
am i doing something wrong?
field names don't support header markdown
I think bold works, you will have to try it and see
ah, is there any way i can put a header in an embed? because im moving this server's already existing embed (sent via webhook) to my bot so it can auto update
Fields are already bold though
I thought you could make them more bold ¯_(ツ)_/¯
@bot.command()
async def delpassword(ctx):
if ctx.author.id in passwords:
del password[ctx.author.id]
passwords()
await ctx.sent(f'Password is now removed')
What's my fault here?
the "password" is not defined
the error says it
Well I put the password still doesn't work
My bud tried it
Still doesn't work
first of all, the screenshot quality took years off of my life
and apparently the list password doesn't even exist
(or whatever the variable password is)
nvm, password appears to be a dictionary
you shouldn't be using a dictionary for that anyways, you're going to lose all that data the moment you restart your bot
Well I'm just testing my projects I set the password before I try to delete it
So how I can fix it?
So I set the password first then try to delete it?
no you have to make a variable called "password"
because it clearly does not exist within the scope of your function
and based on your testing you already attempted to set the password first
Ohh okay okay ill try I'll try
also what you gave us is not helpful
you don't tell us where "password" is defined and where the function "passwords()" is defined, and we don't know what it does
Well I'm just training my self
wtf is that supposed to mean
Just experiencing about Coding and programming
and how is that related to what i told you
Nvrmnd
😐
I'm just a teen so while im young need to learn about something I want than playing games
how is that related to what i told you
Dayumm Imma make a discord bot for my bud
and how is that related to making a discord bot for your bud?
Are you trippin ME?
no you're tripping me
Nahh I'm serious
you're not giving the necessary information to make your discord bot work
i need to know where you defined the "passwords" variable and what the "passwords()" function does
It's just a testing don't mind it HAHA
Well If I have a problem with my self-training
lol
😐
how do i get the bot token from .env?
Using dotenv
i tried that but it said the import doesn'texist
Go to your terminal and type pip list
See if that module is there
Make a prefix command and put an arg that takes in the guild number you want to check out
How do i get just the message that was changed
I tried to doing before.Message but it resulted in an error
how do i get it?
If you're putting peoples' message data somewhere they don't have access to, I hope you're observing the privacy protections you've agreed to in the TOS
its my own messages
lol
Nothing in your code suggests that will always be the case, and it's pretty clear what this is meant to do
it will always be the case because the bot is only in a server i have access to
🤓
And that's the entire purpose of this bot. To sit in a server with only you and copy your messages.
That you send in a server with yourself
We're not stupid dude
Well we might not be, but you are
You can learn things that don't violate privacy
How do you expect me to learn without using the bot 😭
oh yeah i'm violating my own privacy in a server with only me in it
Good job!!!
It is very clear what the purpose of this bot is
Yeh to help me learn
Idk why you're being such an ass about it
💀
There are a million other things you could be learning in this space. You chose this for a specific reason
Unless you're claiming the only possible thing a bot could do would be to copy people's messages in a way that violates the privacy protections they are afforded by law, there are other things you could build to learn and it's odd that you're picking this specifically
💀
How do you think mod logs work
I bet this server is showing deleted/edited messages in a channel we can't see
People doing something doesn't mean that thing is ethical or within TOS to do. You pointing at people doesn't change what you've agreed to
No I'm just someone who cares about user protections and privacy
🤓
I choose to learn the messages topic in discord.py
SolsticeShard: "OMGG YOU'RE VIOLATING PEOPLES PRIVACY"
Not interested in arguing with someone in bad faith. Ultimately this sort of message dumping is against TOS unless you implement privacy protections, which you've made it clear you don't have any interest in doing so. You saying it's only in your server doesn't change that this code is TOS violating as is and you have no interest in fixing that. You could also choose to learn about those protections, but instead you're being condescending and rude
report me then
😭

@sacred sand if you want to code something that violates the TOS you signed, you should not be asking how to break it inside that same platform
If you do it at least search in a different place 🤦♂️
If it breaks TOS then why is it so open to use
There's no warning in it at all
and if it breaks TOS then all mod bots would have broken TOS
Its meant to be used for good intentions
It breaks tos if the protections aren't put in place
and its in the resource in the channel description
whats bad about showing when someones edits a message
Their message content is their data, which they have rights to
Well its like deleting a message, you can't see it (unless you are breaking TOS ofc)
basically to protect their data as said above
??
When you copy that somewhere, without the correct protections you are stripping them of those rights
This is spelled out in the TOS which you have agreed to
wdym you can't see it, it literally shows edited in small text when someone edits their tex
there i edited it
content
I can't see the message before it was editied
yeh but my code shows both before and after
so what now?
Exactly
A normal person wouldn't be able to see the before message, so there shouldn't be a reason to be storing this
go sue them
Cool, and that's irrelevant
Again, other people violating tos is not remotely relevant to this conversation
why would you want to sue dyno
because apparently it breaks TOS
It doesn't matter what anyone else is doing
also does anyone know a free discord bot hosting service
You're just deflecting
I heard of glitch and github pages
It really does
do they work
There isn't anything reliable for free eternally, no. They have to make money
There are a lot of "free discord hosting services" but they do come with a lot of draw backs
Costs money to run servers and they aren't going to spend theirs on you, a rando, forever
hmm can i have some services names?
I tried hosting it on my hp pavilion dv2700
They either are limited trials or are so bad they frustrate you into paying
!hosting
Using free hosting options like repl.it or Heroku 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.
link the tos
It takes 15 seconds to google discord developer tos
Specifically section 5
To reiterate, using/storing message content isn't inherently against TOS, just if you do not also implement the required privacy protections. Pointing at other services doing this does not change that, and also does not indicate whether or not they have those protections
I have this snippet here that checks if a user is already in a certain position on a regional lb (example OCE 1) and its supposed to check if the position in the region is already taken, however it completely goes through and writes it into the file despite already being taken. Screenshot 2 shows exactly what its searching for via a print. Screenshot 3 shows the file being read
This would be a lot cleaner (and more performant and safe) with a proper db fwiw
Why can I buy a knife with all the illegal practices I can do with it?
i don't have access to a db nor do i know how to operate them, im using a file because this project isnt too big and is just for a small group (4 regions, 10 spots available in each
And if a bad write happens, you will corrupt and lose all of your data. This isn't about scale, it's about using the correct tool for the job
As is, you're looking for substrings which is probably conflicting with other fields
would it not just search for /OCE/1 and if it finds it just discontinue?
Id be more worried about the fact that what you have now will randomly crash and lose all of your data 
But one thing to do is actually print out the things you're comparing in your if statement, it probably isn't behaving like you expect
i'll look into databases and how to use them while i program this, if it really does become a problem ill fully move to databases now but if i sanitize everything enough to the point where it wont break formatting i should be all good right
That's not the problem here, you're trying to write to a flat file without atomic writes, which a failure causes the entire file to be corrupted
It will only become a problem once that happens and you've lost your data and your app crashes
I get it now lol but it doesn't say how to put in the protection
would this be better then?
you can host HTTP/interaction-based bots on glitch
for gateway bots (like discord.py), you have to get a VPS
I'm new to bots, does interaction-based mean it only uses app commands? And that makes it easier to host?
mhm
for the interaction based bots, you host an HTTP server and Discord sends requests to it
which is pretty neat because some services allow you to serve HTTP requests for free
I see, thanks! That's very cool, because I only wanted to use slash commands anyway
but beware because there aren't a lot of libraries that abstract this functionality really well
other than hikari (example)
Hmmm, they seem to be completely separate for hikari (gateway vs REST)
Does this mean that a discord.py bot, even if it only uses interactions, cannot be hosted as an HTTP bot?
I mean sure, this is a lot safer in terms of data privacy but I'm not sure why you'd want it
I see no reason that logging the before and after content of an edited message would be against developer TOS
From my understanding it would not be for the reasons of
- There is no expectation of privacy on a discord server so a discord message is not private information
- The bot is not storing the information but rather posting it
- In the intended use case the data would only be able to be seen by a subset of the group that could see it originally
- The bot is exempt from personal data deletion regulations due to the posted information being
- Non-Private
- Essential for the functionality of the service (IE a mod log)
The bot would just need to state this is their privacy policy to be extra safe
Nothing in the tos mentions an "expectation of privacy". This is an entirely made up distinction
The tos state that you must meet requirements for storing any api data you obtain from discord. It does not make an exception if you happen to also use discord as the storage mechanism
And storing API data from a message edit event does meet the requirements
No it doesn't
How would it not?
Are users granted the right to be forgotten when you do so?
No, but it falls within the exceptions of the "right to be forgotten"
The data is being used to perform a task that is being carried out in the public interest
-# GDPR Source
Publicly available information (such as your address, which is often in public real estate/property records)
-# CCPA Source
Discord has to delete it because they have no need for it.
A logging bot does not have to delete it because the data is being used to maintain an "orderly environment" for public interest and deletion of this data would make the "officials" unable to maintain a "orderly environment"
GDPR aside, you don't even have to get into legal aspects. Discord has a privacy feature where users ask for their messages to be deleted, and you as a bot owner have agreed to not interfere with discord privacy features
Except to the extent you are required to retain API Data under applicable laws or regulations, you will (1) promptly update the API Data upon request from us or the applicable user, and (2) promptly delete the API Data when: (a) retaining it is no longer necessary for your Application’s stated (and approved through App Review, as applicable) functionality that is permitted under the Terms; (b) you stop operating your Application (whether on your own, due to an enforcement action by us, or otherwise); (c) we request you delete it; (d) the applicable user requests you delete it; or (e) required by applicable laws or regulations. You will give users an easily accessible way to ask for their API Data to be modified and deleted. If you have received API Data in error, you will immediately tell us, delete it, and provide proof of deletion upon our request.
These are separate and in addition to local data privacy laws. None of this cares about "expectation of privacy".
The application is not retaining the API Data. If someone screenshots messages on discord, discord is not responsible for hunting down this person and making them delete the screenshot when they need to delete data. The data is no longer in the bots control
The bot's messages are in the bot's control. You are using discord as a database
That does not absolve you of the responsibilities just because of where you choose to store these things
Whether you are reposting my messages in telegram or an excel spreadsheet or discord itself, you have a responsibility to delete my api data when I tell you to. Unless you are claiming that it is a third party, in which case there is a whole separate subsection
I prefer py-cord over discord.py.
I have not heard much bad about disnake, I just have not used it
Personally I would look at the documentation/examples/guides of each and choose based off of that as feature and structure wise they are all quite similar
On the second question, discord.py resumed development and is actively being maintained yes
I use discord.py haven't tried disnake. I enjoy working with discord.py
dpy 
py-cord >>>
whatever works well >>>>>>
how can i make a command with both keyword args and normal args?
a function with args and kwargs or a written command with args and kwargs?
can you elaborate?
a function with args and kwargs
thats basic python
but sure hold on
!args-kwargs
These special parameters allow functions to take arbitrary amounts of positional and keyword arguments. The names args and kwargs are purely convention, and could be named any other valid variable name. The special functionality comes from the single and double asterisks (*). If both are used in a function signature, *args must appear before **kwargs.
Single asterisk
*args will ingest an arbitrary amount of positional arguments, and store it in a tuple. If there are parameters after *args in the parameter list with no default value, they will become required keyword arguments by default.
Double asterisk
**kwargs will ingest an arbitrary amount of keyword arguments, and store it in a dictionary. There can be no additional parameters after **kwargs in the parameter list.
Use cases
- Decorators (see
/tag decorators) - Inheritance (overriding methods)
- Future proofing (in the case of the first two bullet points, if the parameters change, your code won't break)
- Flexibility (writing functions that behave like
dict()orprint())
See /tag positional-keyword for information about positional and keyword arguments
i mean a command that support bot args and kwargs
🤦🏽♂️
so a command with required arguments and default arguments, yes?
yes
its the same thing
nonono
like i can specify the arg in command
(..., arg1: type1, arg2: type2, arg3: type3 = None)
i dont get your use case?
!ban @someone
!ban user=@someone
show me an example
like this
i dont think thats possible
oh
also dont make a ban command
its already part of discord and by making your own, you're reducing the security of such an action from falling into the wrong hands
no im just using it as an example
use a different command as an example
you're reinventing the wheel by making it square
not a good idea
wouldn't a check help
you're not hearing me correctly
it's already been done
yeah also if you want your own system or whatever like @unkempt canyon :)
The concerns aren't something you could solve with a check
- your audit log becomes shit because it's your bot doing everything, which is just worse than people doing it themselves
- you won't reasonably be able to recreate 2FA requirements
- your bot now has to ask for permissions it doesn't actually need to do things people can already do, which just unnecessarily increases risk if your bot is ever compromised for no actual functional gain
On your initial question you could look into making a flag converter, but there's really not a case where you'd want both. If it's ambiguous enough where flags are useful, you don't want people using positionals
yes but i want it to work with normal args too
normal args?
without flag converters
args and kwargs in functions, but in dpy instead
also why would you want this?
if you want individual arguments you can fill in separately then just use slash commands
Mixing the two will lead to ambiguous behavior. You do not want this
Even better, just move to app commands and eliminate the problem entirely
^this
it's kinda what they were designed for. Allow you to have more clarity in your arguments with little to no extra typing on the users part
Is there a more recent basic cog + extension example?
I found this one https://gist.github.com/pinheaded/ac880263084a65b8d2f769c1fa46a3d7
But it says it's for discord.py v2
There are live examples for each in the docs. They do not need to come together, and it's important to understand why
I'm asking for an example specifically
If you have any to provide
https://discordpy.readthedocs.io/en/stable/ext/commands/cogs.html?highlight=cog#
This one is not showing an full example as the previous link
What does "full example" mean
Dude
And how is this not "full"
Did you check the link?
I did.
https://gist.github.com/pinheaded/ac880263084a65b8d2f769c1fa46a3d7 is providing main + cogs
The docs are not
Because they are not going to rewrite a full bot to explain every concept. What is confusing about the example in the cog docs and how you would integrate it?
Well that's what I'm looking for
You are going to struggle learning if you do not challenge yourself to layer concepts on top of each other
People do not have the time to rewrite the entire stack to explain incremental concepts every time
I'm reading the docs too. I just want an example that's it
My advice is to read the new concept and challenge yourself to apply it to what you have vs looking and hoping someone has done that for you in every case. Up to you if you wish to take that advice
There are not official examples that do this because they expect you to layer those concepts yourself. There may be unofficial examples but these are not quality controlled or kept up to date
how can i make help command display the flags inside a flag converter?
I added:
@app_commands.command(name="ping")
async def slash_pingcmd(self, interaction):
await interaction.response.send_message(interaction.user.mention)```
But it's says "This applications has no commands"
Any idea why?
Are you syncing your commands somewhere? Are you sure this is being added to your command tree?
Is this the right way to do it?
async def setup_hook(self):
await self.load_extension("cogs.commands")
await self.tree.sync()
Ideally you should only sync when you need to, which is not every time you start your bot
But if I create a command to sync, then I will need to sync that command first?
class SorakaBot(commands.Bot):
def __init__(self):
super().__init__(
command_prefix="!",
intents=discord.Intents.all()
)
async def setup_hook(self):
await self.load_extension("cogs.commands")
async def on_ready(self):
print(f'Version: {discord.__version__}')
await self.change_presence(activity=discord.Game(name='League of Legends', type=1))
print(f'Successfully logged in and booted...!')
async def sync_application_commands(self):
await self.tree.sync()
print("Application commands have been synced.")
@commands.command(name="sync")
@commands.is_owner()
async def sync_commands(self, ctx):
await self.sync_application_commands()
await ctx.send("Application commands have been synced.")
[2024-09-04 18:01:52] [ERROR ] discord.ext.commands.bot: Ignoring exception in command None discord.ext.commands.errors.CommandNotFound: Command "sync_commands" is not found
Am I doing something wrong?
yeah but usually only once
people also make it a hybrid command so you can use the sync command to sync the sync command
You really shouldn't be publishing sensitive owner-only operations as app commands in the first place
You cannot define commands within a bot subclass
These have to be externally declared
Why can't I use
@app_commands.command(name="ping", description=f"Check {self.bot} current latency.")```
It tells me Unresolved reference 'self'
You can't use variables like that in statically declared decorators
Do you know the solution?
What are you trying to put in that sub string?
The bot's name
Well your code doesn't know what the bot's name is unless a) you tell it or b) you log in and fetch the app info
Very simple answer is to just hard code it in a constant
Can somebody review my code? It's very simple. I just wanna know if I'm on the right path.
main.py
https://paste.pythondiscord.com/IRTA
discord.py doesn't have a method called load_extensions()?
!d discord.ext.commands.Bot.load_extension
await load_extension(name, *, package=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Loads an extension.
An extension is a python module that contains commands, cogs, or listeners.
An extension must have a global function, `setup` defined as the entry point on what to do when the extension is loaded. This entry point must have a single argument, the `bot`.
Changed in version 2\.0: This method is now a [coroutine](https://docs.python.org/3/glossary.html#term-coroutine).
Not afaik
Ah ok, the library I use has that method, it allows you to load all extensions at once and I thought discord.py also had it.
I guess you can load all the extensions in a single loop if you prefer that
Well, in general I think it's good, just make sure you have a good organisation of your files.
How can i make help command display flags inside a command with FlagConverter?
how to use open cv for robotics
code:
async def setup_locales(self):
os.makedirs('src/locales', exist_ok=True)
try:
i18n.load_path.append(os.path.join('src', 'locales'))
i18n.set('locale', 'en')
i18n.set('fallback', 'es')
i18n.set('enable_memoization', True)
i18n.set('format', 'json')
print(i18n.t('greeting'))
print('Languages have been setup successfully')
except Exception:
print('An error occurred while setup the languages:')
traceback.print_exc()```
error: When I try to do a print like print(i18n. t('greeting')) instead of the translation appearing, "greeting" appears which it shouldn't, how do I fix it?
@hushed galleon
You set the locale to english did you not?
Yes, but something like hello should still appear instead of greeting.
class A(commands.FlagConverter):
x: str
b: int
@commands.hybrid_command()
async def test(self, ctx: commands.Context, *, flag: A):
result:
!test
Arguments:
flag No description given
default help command does not display A's flags
How do i make it show the inside flags?
Why not just make this an app command
Is there a way to set icon from a url of drop-down menu
Only emojis
try:
result = mongomanager.marketplace_posts_collection.insert_one(document)
except Exception as e:
print("error 1:", e)
try:
new_data = mongomanager.marketplace_posts_collection.find_one({'_id': result.inserted_id})
print("new data")
print(new_data)
print("----")
print(self, guild_id, author_id, type)
await prompt_post_editor(self, guild_id, author_id, new_data, type)
return
except Exception as e:
print("Error 2:", e)
why on earth does this happen?
: (
It's generally not a good idea to catch all exceptions. In your case you are catching it and not displaying the traceback which is essentially for finding your problem quickly
i fixed it <3
What is this about?
5:31 ERROR discord.ui.view Ignoring exception in view <View timeout=180.0 children=4> for item <Button style=<ButtonStyle.secondary: 2> url=None disabled=False label='2' emoji=None row=None sku_id=None>
New to cogs. Can someone please review the code? It's very basic. I just wanna know if I'm on the right path.
main.py
https://paste.pythondiscord.com/IRTA
There's not really a point in putting an error handler in a cog if it's a core part of your bot's infrastructure and not something you'd load/unload. And in general there isn't a point in making cogs that only have one thing, you could just add that thing to the bot on its own, that's just overhead at that point
This is the beginning. So it's better to add error handler directly for the commands in the same file?
I mean it depends on what you want
Local error handlers are for logic specific to commands when errors happen. A global error handler is for things you want to happen when any command errors
But you said it's a bad thing to use a global error handler?
How else can I add a global error handler for my cogs?
That's like taking an apple out of the fridge, putting it into a container, then taking it out of the container so you can eat it immediately
@bot.error, or implement it in a subclass of Bot
You mean the main.py?
Wherever you want it. Things don't have to be in cogs to be in different files
Where would you put the error handler?
Personally I'd subclass Bot and put all of my central implementations in it
. I also think people obsess way too much about what file they put things in
Thanks. What about load the extensions in the subclass too?
This way I don't need to duplicate the loads in every cog
Huh?
Can you review my code one last time?
main.py https://paste.pythondiscord.com/3XKQ
commands.py https://paste.pythondiscord.com/MG5A
So now main.py will act as a fallback for unhandled exceptions
Which is the subclass Bot
Let me know if there is something I missed
You should not be changing presence in on_ready, that can actively disconnect you
On_ready fires repeatedly and randomly too
Where should I change it?
Under setup_hook maybe?
You can pass presence data into the bot's constructor
You don't have to change it yourself
Is this fair?
class Bot(commands.Bot):
def __init__(self):
super().__init__(
command_prefix=["!", ">"],
intents=discord.Intents.all(),
case_insensitive=True,
help_command=None,
activity=discord.Game(name='League of Legends'),
status=discord.Status.online
)
Should I keep on_ready completely empty? Could I print out "Bot is ready"?
You can do that if you want, but do you really want a print every time the bot does a routine reconnect?
I mean it would be good to see in the console when the bot is fully connected. Do you have any other suggestion?
You can make a task that does it once when it initially connects if that's what you want, rather than doing something on every reconnect
Up to you, it's just logging
Would a print actively disconnect me on_ready?
Nah, it's just going to give you noise about something you probably don't care about
Hmh intreseting
When I do !whois 38630748474022293939 way more than 17-18 digits the bot crashes
@commands.command(name="whois", description="Get user information.")
@commands.guild_only()
@commands.cooldown(1, 5.0, commands.BucketType.user)
async def whois(self, ctx, member: discord.Member = None):
[2024-09-06 01:53:28] [INFO ] discord.gateway: Shard ID None session has been invalidated. [2024-09-06 01:53:33] [INFO ] discord.gateway: Shard ID None has connected to Gateway (Session ID: 0d2cc6f4dfafcf67b98ea53f49327447). [INFO] Successfully connected as Developer Bot.
Reconnecting and falling back to the error handler
@hushed galleon one question
Do you know why the bot crashes if you use 20 digits for member: discord.Member?
lol
The bot crashes on exact 20 digits
Not 21, 22 etc
"Crashes"?
Yes when I do !whois 38630748474022298722
No, what does "crashes" mean
[2024-09-06 02:27:05] [INFO ] discord.gateway: Shard ID None session has been invalidated.
The session is invalidated. The bot reconnects and falls back to the error handler
On exactly 20 digit integers
🤨
That's not even a valid snowflake, and I don't think anything in the library would straight up disconnect you. Probably something in your code
Why would it do that on exactly 20 digit integers?
My code
@commands.command(name="whois", description="Get user information.")
@commands.guild_only()
@commands.cooldown(1, 5.0, commands.BucketType.user)
async def whois(self, ctx, member: discord.Member = None):
if member is None:
await ctx.send(f"NOT OKAY")
await ctx.send("OKAY")
return
That is not all of your code
Must be something in your code, I'm calling the MemberConverter with a 20 digit id and immediately getting the error id expect
My full code:
import discord
from discord.ext import commands
import datetime
# Set up the bot with a command prefix and all intents enabled
intents = discord.Intents.all() # Enable all intents
bot = commands.Bot(command_prefix='!', intents=intents)
check_mark_emoji = ''
x_emoji = ''
@bot.event
async def on_ready():
print(f'Logged in as {bot.user.name} ({bot.user.id})')
@bot.command(name='whois', description='Get user information.')
async def whois(ctx, member: discord.Member = None):
if member is None:
await ctx.send("NOT OKAY")
return
await ctx.send("OKAY")
# Global error handler
async def on_command_error(self, ctx, error):
if isinstance(error, commands.NoPrivateMessage):
return
elif isinstance(error, commands.MissingPermissions):
return
elif isinstance(error, commands.CommandNotFound):
return
elif isinstance(error, discord.ext.commands.errors.MemberNotFound):
await ctx.send(f"{x_emoji} I could not find the user `{error.argument}`.")
return
elif isinstance(error, discord.ext.commands.errors.UserNotFound):
await ctx.send(f"{x_emoji} I could not find the user `{error.argument}`.")
return
elif isinstance(error, commands.CommandOnCooldown):
# Create an embed message
embed = discord.Embed(title="",
description=f"{x_emoji} This command is on cooldown. "
f"Try again in {round(error.retry_after)} seconds.",
timestamp=datetime.datetime.now(), color=discord.Color.red())
await ctx.send(embed=embed)
return
else:
await ctx.send(f"{x_emoji} An error occurred while processing the command.")
raise error
bot.run('TOKEN_HERE')
Crashes as well
discord.gateway: Shard ID None session has been invalidated. discord.gateway: Shard ID None has connected to Gateway (Session ID: f2d07faabe7c3ee9e5df6d8b57d9b131). discord.ext.commands.bot: Ignoring exception in command whois raise MemberNotFound(argument) discord.ext.commands.errors.MemberNotFound: Member "38630748474022298722" not found. Logged in as Developer Bot (1064279645215793173)
And that's the entirety of your code?
and where are you hosting this? Fetching a user doesn't invalidate your session, you got something fucked in your environment
PyCharm -> New project

Did you try with exact 20 digits?
Can someone help me with discord embeds and sending images from a file path. Ive got it to send like before the embed gets sent but i cant get it inside of it
filename needs to match for it to be inside the embed
https://discordpy.readthedocs.io/en/latest/faq.html#how-do-i-use-a-local-image-file-for-an-embed-image
Is it possible to run a discord bot using eval function?
im learning about flags
but theyre not showing in help prompt
If your goal is to let a user provide multiple optional arguments and to make that easy, app commands are the right tool
Anyone knows please?
Why? What is your goal?
Yep
Beside the danger of this command, you'll have to adjust your code a little, but yeah. It is possible.
Basically make a jsk like thingy to run the bot from another python program
Thank you so much
Why would that need to be an eval? You could just write the code
That’s not the issue..
How would I run it from another python program?
Just...put the code in that program...?

Like what is the actual flow here in concrete terms, what are these programs doing
It's specically the ID 38630748474022298722 that makes is crash. I tried other ID's with the same length and they didn't
Error message: https://paste.pythondiscord.com/GTPQ
I have a quick question.
How do I make all elements of a view disappear after a timeout if there's no interaction? What I mean by this is, what object do I refer to in order to edit the message without requiring a message/interaction?
Example is
async def on_timeout(self) -> None:
for button in self.children:
self.remove_item(button)
# or
self.clear_items()
#The below function call will not work as there won't be an interaction (no button press or similar interaction)
#await interaction.response.edit_message(view=self)
Problem solved now
👍

