#discord-bots
1 messages ยท Page 393 of 1
salut
I think you're missing an async with
yeah it works when using with block but i want to return the database connection though
You need the async with. Where do you want to use it without async with?
What is an instance variable?
i realized you need to await for the class for it to be alive which i didnt and with block isnt needed
You still need the with block to close the thread
you can do manually it using db.close() though?
yeah but sometimes i want to close it manually
You can close it manually and still use the with
A variable that is associated with an instance (object) of a class
isnt that duplicate?
Good context managers are idempotent
aiosqlite connection is refusing me to shutdown my bot (using ctrl + c) when it's not closed, what's the solution?
I'm being comissioned by someone to make a discord bot for them, but I have no frame of reference for how much to charge for. The bot is supposed to facilitate running a 'ranked match' in an external game (with things like character bans) and also taking the results of the match and using a ranking algorithm to rank the players.
@bot.tree.command(name="start_election", description="Start an election in a specific region.")
@app_commands.describe(region="1,2,3,4")
async def start_election(interaction: Interaction, region: int):
region_map = {1: 'Aryavart', 2: 'Dravidian Rashtra', 3: 'Saurashtra', 4: 'Purvanchal'}
if region not in region_map:
await interaction.response.send_message(f"Invalid region: {region}. Please choose between 1, 2, 3, or 4.", ephemeral=True)
return
eci_role = discord.utils.get(interaction.user.roles, name="ECI")
if not eci_role:
await interaction.response.send_message("You do not have the required ECI role to start an election.", ephemeral=True)
return
selected_region = region_map[region]
candidates = await db.get_candidates_for_region(selected_region)
if not candidates:
await interaction.response.send_message(f"No candidates found for the {selected_region} region.", ephemeral=True)
return
options = [discord.SelectOption(label=candidate['candidate_name'], description=candidate['party_name'], value=candidate['party_name']) for candidate in candidates]
class VotingDropdown(ui.Select):
def __init__(self, candidates_options):
super().__init__(placeholder="Choose your candidate", min_values=1, max_values=1, options=candidates_options)
async def callback(self, interaction: Interaction):
user_id = interaction.user.id
party_name = self.values[0]
username = interaction.user.name
already_voted = await db.check_if_voted(user_id, region)
if already_voted:
await interaction.response.send_message("You have already voted!", ephemeral=True)
return
await db.add_vote(user_id, party_name, region)
await interaction.response.send_message(f"You voted for {party_name}!", ephemeral=True)
print(f"Vote added for {party_name} by {username} from {selected_region}")
view = ui.View()
view.add_item(VotingDropdown(options))
await interaction.response.send_message(
embed=Embed(
title=f"Election Poll for {selected_region}",
description="\n".join([f"{index + 1}. {candidate['candidate_name']} ({candidate['party_name']})" for index, candidate in enumerate(candidates)]),
color=Color.green()
),
view=view
)
it says interaction failed if I restart the server
You should be making a View class, not a generic View object that you then staple items into. If you're using discord.py, look at the persistent.py example for options on how to get things to persist across restarts
can you give an example
There are examples in the example file I mentioned
Hello! I'm doing my first Discord bot with Python, but I saw a tutorial that said to go to the internal PC commands and run "pip install discord" but it doesn't work, any ways to fix this? And if it can't be fixed, what do I do to install that Discord thing?
how can I make a discord bot?
The async with, will close it
ยฟ
Why won't this work?
@bot.command()
async def hello(ctx=None):
await ctx.send("Hello there!")```
It says that "hello" isn't a command.
I mean, where can I find that example file
Replace = with :
It's in the examples folder in the repo
Alright! Thanks!
Don't give people advice if it does not solve the actual problem.
Whatever tutorial you are following sounds like it is pretty bad. I recommend looking at the docs and examples for the library you are using
Why does my bot keep saying that my command doesn't exist as an error?
Probably because you're not registering it properly
How to fix it?
Should the command be grey when I type it or?
Going to need to see the full code
Alright!
Here it is. ```py
@bot.command()
async def sendembed(ctx:None):
embeded_msg = discord.Embed(title="Title of Embed", description="Description of embed", color= discord.Color.blue())
embeded_msg.set_thumbnail(url= ctx.author.avatar)
embeded_msg.add_field(name="Name of the author", value="Value of field", inline=False)
embeded_msg.set_image(url=ctx.guild.icon)
embeded_msg.set_footer(text="Footer Text", icon_url= ctx.author.avatar_url)
await ctx.send(embed= embeded_msg)```
It says that the "sendembed" command doesn't exist.
Alright.
(removing any tokens)
Don't worry, I got it covered.
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="!",intents=discord.Intents.all())
@bot.event
async def on_ready():
print("Bot ready!")
@bot.command()
async def hello(ctx:None):
await ctx.send(f"Hello there, {ctx.author.mention}.")
@bot.command(aliases=["gm", "morning"])
async def goodmorning(ctx):
await ctx.send(f"Goodmorning, {ctx.author.mention}!")
@bot.command()
async def sendembed(ctx:None):
embeded_msg = discord.Embed(title="Title of Embed", description="Description of embed", color= discord.Color.blue())
embeded_msg.set_thumbnail(url= ctx.author.avatar)
embeded_msg.add_field(name="Name of the author", value="Value of field", inline=False)
embeded_msg.set_image(url=ctx.guild.icon)
embeded_msg.set_footer(text="Footer Text", icon_url= ctx.author.avatar_url)
await ctx.send(embed= embeded_msg)
with open("token.txt") as file:
token = file.read()
bot.run(token)``` Here.
(Currently following a tutorial which doesn't get these types of errors).
You should not nest commands inside of each other, or inside of an event
these should all be indented to the top level
Alright!
connection pool
Ah maybe aiosqlite is different and needs async with contextlib.closing
hey guys, I have a problem, so I fire a HTTP request to get the members of a guild, but instead receiving only my name, why?
Members intent.
token.txt ๐ผ
Use dotenv
What is it?
# .env
key=value
# main.py
>>> import os
>>> os.getenv("key")
"value"
It secures secret keys
Make a new file called .env
Alright, thanks!
I activated that in the discord dev portal, but not working
you need to load it using dotenv.load_dotenv first, am i wrong?
Yes you do
What about in code?
Oh wait http request
fetching a guild doesn't return its members
I don't in my code. I think it may be system dependent
Environment variables 
Typed modern config formats like toml or yaml 
is making a shutdown command good?
Interesting
Yeah nothing wrong with that
How do I use that?
Hello I need help, when I try run setup command on bot it sends smth weird
what is a "setup command"
Did you install this off of github or something? It is probably a bad idea to run files that you dont know what is in them or what they do that you find on the internet
Do you even have python installed?
GUILD_ID= discord.Object(1149794271935873126)
@bot.tree.command(name="hello", description= "Says hello back to the user that used the command.", guild= GUILD_ID)
async def sayHello(interaction: discord.Interaction):
await interaction.response.send_message(f"{interaction.user.mention} Hello there!")```
Why won't this work?
It says this: "builtin_function_or_method" object is not subscriptbale.
oh no I dont
tysm much
What's the full error?
An Error while syncing applications commands has occured: 'builtin_function_or_method' object is not subscriptable
But the try: command was wrong, now it says "Synced 0 commands".
You should have a traceback
If you don't know what line that error happened on, youre shooting in the dark
How to get that?
What's a library? I'm a beginner.
Here if the full code:
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="!",intents=discord.Intents.all())
@bot.command()
async def sendembed(ctx:None):
embeded_msg = discord.Embed(title="Title of Embed", description="Description of embed", color= discord.Color.blue())
embeded_msg.set_thumbnail(url= ctx.author.avatar)
embeded_msg.add_field(name="Name of the author", value="Value of field", inline=False)
embeded_msg.set_image(url=ctx.guild.icon)
embeded_msg.set_footer(text="Footer Text", icon_url= ctx.author.avatar)
await ctx.send(embed= embeded_msg)
@bot.command(aliases=["gm", "morning"])
async def goodmorning(ctx):
await ctx.send(f"Goodmorning, {ctx.author.mention}!")
@bot.command()
async def hello(ctx:None):
await ctx.send(f"Hello there, {ctx.author.mention}.")
GUILD_ID= discord.Object(1149794271935873126)
@bot.tree.command(name="hello", description= "Says hello back to the user that used the command.", guild= GUILD_ID)
async def sayHello(interaction: discord.Interaction):
await interaction.response.send_message(f"{interaction.user.mention} Hello there!")
@bot.event
async def on_message(message):
if message.content == "You are rude":
await message.delete()
await message.channel.send("Please be kind to others.")
@bot.event
async def on_ready():
print("Bot ready!")
try:
synced_commands= await bot.tree.sync()
print(f"Synced {len(synced_commands)} commands")
except Exception as e:
print('An Error while syncing applications commands has occured:', {e})
with open("token.txt") as file:
token = file.read()
bot.run(token)```
You're not going to have a good time implementing something this advanced not knowing what a library is
This is like walking into a brain surgery class and asking what a scalpel is
Oh wow, is it that bad?
Soo, what is a library?
You have a try and except in your code. Do you know what these do or why you put them there?
Ohh a library it's like discord.py?
I do know, to know if the commands synced correctly in the guild.
Nice.
That is not what try and except do, generally
Oh, what do they do then?
Why is it in your code if you don't know what they do 
I thought they did that, as in the tutorial that I'm following they use try and except to see if the command synced and if not what is the error.
I'm trying to do my first slash command, but it won't sync into my guild.
This tutorial is teaching you bad practices and not even explaining why they're doing it lol
Oh..
Wherever you're getting it from is talking out of their ass, because what they're doing is actively making your code less usable
Oh nah the solsticeshard ignored me #discord-bots message
Oh, so I should remove it?
You should first understand what it does. You should never add/remove/change code just because someone tells you to, that's lesson 0
Then I'm so bad at this.
Does that count as spoon feeding?
Spoon feeding is really bad, especially when they spoon feed you shit code they don't even explain
So, what should I do to sync my command?
ChatGPT be like
And generally toml/yaml are pretty googleable, there are good libraries out there
await bot.tree.sync()
Put that in a command
You should understand what try and except do, and why they are bad here
Alright, could you explain it to me?
So that syncs my command?
What about json?
It will sync all your app commands and make them available for use
Alright!
json is a data exchange format. It Works โข๏ธ but it's unnecessarily verbose and limited for configuration imo
Though it will get rate limited if you use it too often
As long as it's not used for databases, should be about fine
Google python try except is a good starter
It's just not meant for this, the only reason to use it is a refusal to learn the correct tools
Alright.
Configuration like editing data?
Or creating
configuration as in...things that configure how your application works
It says that I can only use await with the async function.
But like I just recently migrated to that, I use those for settings
Nvm.
Fixed it?
How to not make it rate limited?
Yep.
Just don't sync too much
For me when I add app commands it doesn't pop up yet
But restarting Discord should work
No errors in the console right?
Show the code
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix="!",intents=discord.Intents.all())
@bot.command()
async def sendembed(ctx:None):
embeded_msg = discord.Embed(title="Title of Embed", description="Description of embed", color= discord.Color.blue())
embeded_msg.set_thumbnail(url= ctx.author.avatar)
embeded_msg.add_field(name="Name of the author", value="Value of field", inline=False)
embeded_msg.set_image(url=ctx.guild.icon)
embeded_msg.set_footer(text="Footer Text", icon_url= ctx.author.avatar)
await ctx.send(embed= embeded_msg)
@bot.command(aliases=["gm", "morning"])
async def goodmorning(ctx):
await ctx.send(f"Goodmorning, {ctx.author.mention}!")
@bot.command()
async def hello(ctx:None):
await ctx.send(f"Hello there, {ctx.author.mention}.")
GUILD_ID= discord.Object(1149794271935873126)
@bot.tree.command(name="hello", description= "Says hello back to the user that used the command.", guild= GUILD_ID)
async def sayHello(interaction: discord.Interaction):
await interaction.response.send_message(f"{interaction.user.mention} Hello there!")
await bot.tree.sync(GUILD_ID)
@bot.event
async def on_message(message):
if message.content == "You are rude":
await message.delete()
await message.channel.send("Please be kind to others.")
@bot.event
async def on_ready():
print("Bot ready!")
with open("token.txt") as file:
token = file.read()
bot.run(token)```
Oh nah bro no cap fr
You synced inside the command
Do it in a separate command
Do you know what syncing is, why you need to do it, and when you should do it?
Yes, syncing is when you need to basically "load" something in like a guild, I need to do it to load my slash commands and I should do it when I should like "load" something in another thing.
That's not really accurate at all
Oh...
Did the tutorial even try to explain?
No, it's that with my experience with lua I thought it was like that,
This tutorial somehow manages to get worse and worse. You really should stop reading it
I feel you man
I'm literally watching 2 different tutorials, I don't really know what to do at this point...
Slash commands (app commands) specifically are stored in a structure called the CommandTree. Calling sync() on that command tree is effectively telling discord about the commands that it's storing, because discord needs to know about them and their metadata
Ok make another command then sync when you use it, that's all
Then restart Discord
Alright.
This only pertains to app commands, hence why it's called on the CommandTree that stores them
Is there anything different about app_commands and tree?
CommandTree is a class made by the library that tracks app commands
Why does interaction become grey when I type it... It shouldn't..
I have not seen a single youtube tutorial for making discord bots that was good or not outdated
Just a fyi
Now that I realize, same.
What is the "def" function?
Some of these questions you're asking are very, very base level python. And if you try to learn them in the context of an advanced framework like a discord bot, you are going to get very very confused
as these libraries presuppose you have these fundamental skills and will not talk you through them
I can't do anything at this point... I don't want to continue using platforms like BotGhost.
Can you please tell me just how to fix my problems? I really want to make my slash command work..
As you are basically telling me no way on how to learn how to use Python, as you said that every single tutorial that I'm watching are just bad, so how should I learn it then?
https://www.python.org/about/gettingstarted/ is a good starting resource
Alright, thanks.
Learning python and learning how to make a discord bot in python are separate. You should learn some python first.
These concepts build off of each other but will take time, there's not an easy path to just running before you know how to walk. This community exists to help with those stages of learning but you'll need to put the effort in to self-learn
I would like to do it.
But I learn better with examples or by videos.
Or just a page that has a true explanation and examples.
Examples there are plenty once you've read the underlying concepts.
Videos are an inherently wrong medium for conveying this information, and will range from bad to outright misleading. I strongly suggest you get comfortable with reading articles and then experimenting yourself in code
Are there like any official Python books or something?
!res has a bunch of tutorials for learning python. It is not official but I started with "Automate the boring things"
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
You'll need to describe the behavior you're trying to accomplish
Hello I need help, when I try run setup command on bot it sends smth weird
You were already told not to run random batch scripts off of github lol
"setup command" is something that some random person wrote, and if you want to use it (you shouldn't), you should ask them
What is that
Batch script what is that
Read your own screenshot man
Windows Batch File
This is a script you downloaded from somewhere that some rando wrote, you are running it and it is trying to do things to your computer that you don't understand. That should be alarming to you.
Hello does someone know how to handel with user-installable apps? bc i want to make that my Discord Bot Command register also in the normal dms of a user and not in the bot dms i can use my command everywhere besides in this so if someone know it would be helpfull
Which library are you using?
the normal one

idk im a starter i just watch a youtube video
and try something out what kinda worked
yeah youtube videos will lie through their teeth at you
and give you things that are horrible practice or just not work
Anyways, at some point you will have picked a discord library to work with, and the answer to your question may vary based on that
Sorry im just new and trynna test some bots ๐ฆ
You are trying to run some bot that a specific person built. You should contact them. Your question is with what they made, not with python.
Though I would not trust this at all given what I'm seeing, and you would do really well to be more skeptical about things you get from online
im getting discord.errors.NotFound: 404 Not Found (error code: 10015): Unknown Webhook when using interaction.followup.send
hi can you share code?
@app_commands.command()
async def test(self, inter: Interaction):
await inter.followup.send('eoeakaok')
oh ok
followup is used when the intertaction has already been respionded to
so if you are sending just a message, either do interaction.response.send_message("my message") or await interaction.response.defer(thinking=True) first
is thinking needed?
the defer is used when your program will take longer than ~!3 seconds to give an output
You can try wuthout but I think so
havent used it ion a whjile tho'
thinking is always True for slash interactions
It's for components where it defaults to False, and you can actually set it
Is there a way to make like the options of the slash commands in the prefix command?
Like the option that you need to choose the members.
And how to make the bot always stay online even if I close Visual Studio?
!intents
Is there any way I can reset the cooldown of a command without the reset being executed within that command?
Run it in a process on your computer and keep it online, or rent a vps and do the same
How do i fix Unclosed connector error?
What's the full error and traceback?
2024-11-02 06:39:37 ERROR asyncio Unclosed connector
connections: ['[(<aiohttp.client_proto.ResponseHandler object at 0x000001585A847590>, 15332.187)]']
connector: <aiohttp.connector.TCPConnector object at 0x0000015859419F40>
Traceback?
theres no traceback
Sounds like something to fix or you have no idea where this problem is
Maybe because it is <:name:id> not <:name:id:> unless you mistyped?
<
286529073445076992:>
no that would just break it. Maybe you have the wrong ID?
robux
real currency
okay skid
Is it animated? I thing animated emojis need to be <a:name:id>
nah it wasnt
tbf they never said it was real currency unless they deleted a message.
i never said it lol
They have a long history of skid currency exchange
me?
Look up their message history
nun exchanging i did in my past
And yet you deleted your message anyways 
what message did i delete?
these past 5
it's js bc there was no specific error with it i js changed name of emoji and it worked after it i dont see the problem in deleting those 5
When you have a long history of writing shit trying to get people to send you money, then you post code here with the word robux next to currency values, it doesn't take Sherlock Holmes to put two and two together
when did i try to get people to send me money? ๐คฃ
and these 2 are totally different projects
you are not putting any shit together mate
blud aint sherlock holmes ๐
litteraly an automated middleman bot
where did i try to get people to send "ME" money there?
and what that has to do with robux now lol
Why don't you show the full code and describe what this is doing then if you've got nothing to hide?
because i sold that src? why would i leak it here to prove you wrong?
you rlly think i've been doing one project since july
that's when i asked abt that
No I think you're a prolific skid
think what you want ๐
Then show code
i got no reason to care abt that ๐คฃ
why would i
To prove you're not a skid
i told you to keep thinking i am skid
i dont care xd
would u show your bands if i called you poor?
to prove that you're not pooron
didnt u have some roles in this server? looks like you got demoted
You show code with currency next to robux, you delete that code, you refuse to provide more code or context of why you're displaying currency next to robux. It's not a good look, and someone who wasn't breaking rules would have nothing to hide
where did i show code with currency next to robux?
show that again please
You just deleted it lol
gigabrain
Shows something
Deletes it
Gets pointed they've shown something
Asks to show and prove where they sent it

u litteraly saw what i've asked, i showed my description of embed and i asked why would emoji not display
i didnt mention real currency in there
and the message that he sent id of was sent in july
so you are connecting those two projects?
gg big brains ๐
๐คฃ mate they saw what i've sent already
it got no thing to do with real currency
The connection is you skid together shit asking people to send money to your bot
LOL
"Nothing to do with real currency"
Posts code with "$24.99"
Immediately deleted
yea they do send money to bot because it works as automated middleman?
You can't make this shit up
it still doesn't have anything to do with the code u mentioned that i've asked about in july
You literally just posted code with currency prices and deleted it a second later
Why are you deflecting
you are actually ed ๐คฃ
still got nothing to do with the code you mentioned before
You can try to gaslight me into thinking you didnt post skid code you immediately deleted, but you did. Hopefully there are logs
how skid when made by me ๐คฃ
logs for what
blud thinks staff gonna look trough logs to prove him wrong xd
why does my ping command not work
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
print(f"{__name__} is online")
@commands.command()
async def ping(self, ctx):
embed = discord.Embed(
title = "Pong!",
description = f"Latency in MS",
color = discord.Color.light_gray()
)
embed.add_field(name="Bot Latency", value=f"{round(self.bot.latency * 1000)}ms")
embed.set_footer(name=f"Requested by {ctx.author.name}", icon_url=ctx.author.avatar)
await ctx.send(embed=embed)
async def setup(bot):
await bot.add_cog(Test(bot))```
added this in the main file
```async def Load():
print("Attempting to load cogs...")
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
try:
print(f"Loading {filename}...")
await bot.load_extension(f"cogs.{filename[:-3]}")
print(f"{filename} loaded successfully.")
except Exception as e:
print(f"Failed to load {filename}: {e}")
async def main():
async with bot:
await Load() # Ensure cogs are loaded here
await bot.start(TOKEN) variable for security
asyncio.run(main())```
oops
now imma continue doing my thing and u can continue wasting time aruging with yourself bc u got nothing else to do in your life ๐
why does the ping command not work it says that the command doesnt exist
Are you sure that extension is loading?
The image they posted here had no real life currency values.
It was something like __100,000__R$
yes
The code they posted and deleted then literally had "$24.99" on it
How are you verifying that?
is that the indentation in your file as well?
probably doesn't load if that's your indentation
yea it doesnt
the load function includes print statements that confirm each cog file is found processed and loaded
and it prints loaded succesfully
its just discord
So you're getting the success print for that specific extension? Are other extensions loading commands properly?
idk i have only 1
Are you loading these commands into the same bot object you're running? Seeing the full main file minus token would be helpful
yeah
how can i fix thhis
all other commands in that cog work but the ping one not
Show your code now, you didnt have other commands before
ive got it through the website but doesnt work
anyone able to join a vc and help me
post screenshots containing the errors, no point in joining a vc
Try py -m pip install discord.py
Python is for macos/Unix, py is for windows
i did that and it worked having issues with my main.py
There goes your bot token
delete the screenshot and reset your token now
How are you running your script
you just need to install audioop-lts the same way you did for discord.py
Also you're using python 3.13, I doubt dpy supports 3.13 yet
Python 3.13 doesn't have it in the stdlib anymore
And you shouldn't use 3.13 either way - downgrade to 3.12
yea
shall i move to 3.12?
Yes
any of these
Download the 3.12 installer from python.org and don't forget to add python to path
im doing off microsoft store
can you vc and help me?
I can't help on vc
Uninstall the Microsoft version before you install 3.12
32 or 64?
depends your device, probably 64 if it's not old
shall i uninstall this too
yes
done now do i install the pip install discord.py?
Have you installed this?
yes
Sorry for the ping
First go to vsc and create a venv
do py -m venv venv
In the terminal
And then a popup should come asking if you want to select that venv, click yes
In vsc
in vsc
Not in your cmd
in cmd or vsc
Vsc
"terminal" in vsc = cmd
i forgot how to kill it not used vsc in ages
just exit ๐คท
Hover over the Python tab and a dustbin icon should popup
And with the PowerShell also
And press ctrl + `
done
hey guys, hope yall doing well. I receive several events from the discord websocket, how would you guys make the event listener with all the events?
Personally I have a separate cog listening to all events
The popular discord libraries already provide a framework for listening to specific events
pip install discord.py
done
Run your code
On windows you shouldn't be running raw pip commands
It's ambiguous which pip installation that uses
Doesn't matter once you activate a venv
it works i only got that code now what shall i add
how they manage that, can you provide a github link to that file like for example events.py or something like that?
Whatever you want..?
alr cheers
๐๐ฟ
are you trying to rewrite it yourself?
not at all, but started with the discord api and read along the article and how to manage that an app stays alive.
It's unclear what you're trying to do and why you can't use the things already given to you, is this more of an educational exercise?
you can look through library source but those are internals that aren't going to be documented as they're not intended for consumer use
ok, I will look through a library that wraps the discord api pretty well
The structure and types of events sent through the socket are also documented by discord itself for people writing this
ah myb sorry didn't see that they were in a venv, pretty rare to see people jump right into that
Lmao yea
Once I started using venv I couldn't go back to using my global environment
can you help me fix this? i see no errors
You need to indent your code
wdym
Do you know what indenting is, and how it's important in python?
not really
should I use app_commands.command or Bot.tree.command for making slash commands?
This is pretty fundamental like first week python stuff. You will struggle to learn those basics while also trying to do so in the context of an advanced subject like this
indenting (tabs and spaces at the beginning of a line) have a fundamental purpose in python to signify when code is "nested" inside of a statement above it.
def something():
abcdef()
is invalid, compared to
def something():
abcdef()
the former just declares a command in that context. It won't add it to the bot's command tree on its own. The latter declares it as a command and registers it into the command tree in one go
what does that mean?
Which part is confusing?
I'm talking about the decorators btw
Yes, I was responding with that in mind
so what is context, and the command tree?
@app_commands.command()
async def cmd(...):
...
This just makes a command sitting there. Same as creating any variable like x = 5. This alone doesn't do anything
A command being in the CommandTree is what actually gets it sent to discord when you sync that command tree
oh, so if I call tree.sync, it won't appear in the server?
@bot.tree.command()
async def cmd1(...):
...
@app_commands.command()
async def cmd2(...):
...
bot.tree.add_command(cmd2)
are equivalent
oh, ok, thanks
If you declare an app_command with method 2 inside of a Cog and then load that Cog into the bot, that will automatically register that command in the commandtree as well. This is the majority use-case for @app_commands.command but not necessarily the only one
without bot.tree.add_command(cmd2)?
Yes, loading the cog itself effectively does that for all app commands contained in the cog
much appreciated, thanks
?
rent a vps
Already got answered for that.
What do you mean no?
you ask if something is possible and get "no" as answer
can someone help me make an announcment command
Prefix commands cannot have options like slash commands because well... at that point just use slash commands
If you mean to create a prefix and slash command at the same time py-cord has ext.bridge not sure if other libs have something simialr
You will have to explain what you mean
I canโt manage to make a slash command work tho. But like Circle has both Slash and Prefix commands that have options.
Slash commands are definitely better, so if you can make them work that is best.
Can you show a screenshot of what you mean with the "Circle" bot?
Diluting your code to give people 2 ways of doing the same thing (one of them worse), vs just setting the expectation that they do it the right way
Sure thing!
Like this, same command that does the same exact thing, just one with prefix and one as a slag command.
Yeah, you can have arguments with prefix commands, you just cant have discord Options.
You just need to add arguments to the command definition for it to work with prefix commands
How?
It's the same as adding arguments to any python function
def my_function(argument1: Type1, argument2: Type2, ...):
Alright so if I want to do like the that you have to specify a member and a reason for the reason I have to make an argument like โmsg: strโ, while for the members one how to do it?
Typehint it how you want to, discord.Member is one such type. Although if your bot is going to be DM'ing people, you'll want to make sure you got their consent to ahead of time
Alright! Thanks! Iโll ping you if I encounter any issues.
So i can do a acommand what will send a announcement to a channel pinging everyone and in a embed and select a title wtc
What do you have so far? You should just be able to take an argument in the command for the announcement content and send it to the channel with the embed
Consider publishing these to an announcement type channel. There's really no need to have a bot as an intermediary
I dont think the intent is to spread it to multiple servers. I think the intent is to have an embed. I may be wrong tho
Generally it's good to do this off of an existing message rather than an input to a command, that way you can review markdown and have much easier multiline input. Publishing is the first-class way to do this and doesn't need a bot running. You could implement this as a message context menu alternatively
so i can have a everyone ping and make announcments through the bot brodcasted to a channel
yeah, just make sure you set allowed_mentions properly
i dont know how to make the command
have you looked at the examples of the library you are using?
Which part are you specifically having trouble with? Making a command, period? Making the command accept a message? Having that command send a message to a channel?
im using visual
im here gonna move the command to my cogs
@bot.tree.command(...) goes over a command function
Isnt that / command?
yes
Can someone help me with a script for announcements
That's...what we're doing?
i dont know what else to put
this is all i got
If you don't know how to make a function in python, you should learn that first
also would it be worth doing command folders
What is a command folder?
I'm trying to make a "level" mechanic for my bot, just for the lulz really. and having difficulties with the math part. anybody got a recommended formula or can help me out with the math?
I want users to level up at a normal rate and not have huge gaps between levels
NGL this is such a weird thing to ask lol
I've installed discordpy 1.7.3 but it wouldn't let me run my script showing this error
install discordpy 2.4
But i need 1.7 for my current bot
why
That's what it's requirements is
1.7.3 uses discord api v8 which is deprecated and shouldn't be used
upgrade the code to 2.x -> https://discordpy.readthedocs.io/en/stable/migrating.html
the API v8 also should've been removed based the timings discord gave, but it hasn't been removed yet
so any bots using 1.7.3 may die at any moment when discord decides to delete v8
Glad that aiohttp is helping with breaking 1.7
so guys, for understanding purpose. Was the discord py library always async or no, and if not, how could it handle such inputs outputs from various commands?
Whenever i take input from user and user added emoji to it then it shows :emoji:, how do i fix this?
async def def(): โ ๏ธ โ ๏ธ โ ๏ธ โ ๏ธ โ ๏ธ โ ๏ธ โ ๏ธ โ ๏ธ โ ๏ธ โ ๏ธ โ ๏ธ โ ๏ธ โ ๏ธ โ ๏ธ โ ๏ธ โ ๏ธ
In very early versions it wasn't. It didn't handle them concurrently but in the classic way (sequentially), which was a big issue
some1 knows why I get these?
These are like warnings that your code might or might not work, unlike errors (red lines)
And you might want to ask this here
for discord.py what type of python version need?
I don't there's any set requirement other than Python3.8+
How can I detect mentions of channels from other guilds but not in direct message (DM) channels?
elif any(message.guild.get_channel(channel_id) is None for channel_id in message.raw_channel_mentions):
The code above is detecting DM channels as well.
Did you define instance for it?
That is not true, it is python 3.8-3.12
You will have to explain more what a normal rate is. This is something that I came up with quickly. F(x) is how much total XP is needed to reach a level X. G(x) is how much more XP is needed to get from the current level to the next level. Each level gets a little bit harder to get.
But if you want even less of a gap you might just want a linear line. Where ever 200 XP a user gets a new level
Hi
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
a sextuple skull emoji is delirious work
Bro went to bed at 5am 
Can discord bots use custom emotes?
Like if I add some custom ones to a private server im in with the bot, and then have it use those emotes in another server its in?
what's the type annotation for multiple selections for app commands?
Literal?
yes but you have to specify the emoji id, so <:emoji_name:emoji_id>
I can get that with like, right click, copy id?
Im on my phone rn so cant test it out
apparently you can do that
Will check out in the morning thankies
np
Guys Where can i learn Python faster to code discord bots/tools?
Command raised an exception: TypeError: argument of type 'Member' is not iterable
@client.command()
async def add(ctx, user: discord.Member):
role = ctx.guild.get_role(1301284017789861950)
if not role in ctx.author:
return
await ctx.channel.set_permissions(user, view_channel=True, send_messages=True)
embed = discord.Embed(description=f"{user.mention} added to ticket {ctx.channel.mention}")
await ctx.reply(embed=embed)
@add.error
async def add_error(ctx, error):
if isinstance(error, commands.MemberNotFound):
await ctx.send("Member not found, please ask him to join server")
await ctx.send(error)
@merry cliff can you help?
You can't check if a role is "in" a member
try Member.roles instead
so in this case, if role not in ctx.author.roles
Oh lemme try this
perhaps raise an error / send a message to tell the person they don't have the right role or something similar
If this is meant to be a check, it should be implemented as one rather than checking it directly in the command body tbh
yup
!d discord.ext.commands.has_role
@discord.ext.commands.has_role(item)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check) that is added that checks if the member invoking the command has the role specified via the name or ID specified.
If a string is specified, you must give the exact name of the role, including caps and spelling.
If an integer is specified, you must give the exact snowflake ID of the role.
If the message is invoked in a private message context then the check will return `False`.
This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole) if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage) if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure).
Changed in version 1\.1: Raise [`MissingRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingRole) or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage) instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure)...
Or use if not <Member>.get_role(ROLEID) if you really need it inside
- Why did you reply to an unrelated message from me?
- You're in the wrong server. That's Javascript, not Python.
- Selfbots are strictly against the Terms of Service. No one will help you with that.
- Refer to point 2 again.

Bro deleted all their messages
how can i modify my views so when it's timed out and when someone clicks on it, it sends a interaction message?
You can use the on_timeout() event to modify the view when the timeout ends.
i want it to send everytime the user interact tho
You can now add emojis directly to your bot in the discord developer portal. You can then send them in the same way. This is recommended instead of uploading them to a server.
use the callback() of the components that have the view
I have never tested this myself but ...
In theory you could edit the views on timeout so that all of the components have a custom Id of timeout or similar. Then in on_interaction, check for that custom Id and respond
if you already have a timeout handler, there's no reason to leave the buttons enabled
worse user experience and you need hacky code to handle it
Depending on the situation it might be better user experience to have a response. You could include why it was closed for example (If it was not a timeout)
That could (and arguably should) be captured in the message content rather than visually communicating to them that you want them to interact with this element
You didn't call the super init when overriding it
999 times out of 1000 you want to do that first
someone able to help me with a discord bot please message
Feel free to ask your question here and get better help with more eyes
indeed that class definition does not typehint any support for generics, so pyright is declaring it incorrect as per typing specs
it looks like they rewrote range and fixed it in disnake v2.9.0+
https://github.com/DisnakeDev/disnake/blob/v2.9.0/disnake/ext/commands/params.py#L379-L411
<@&831776746206265384>
Hello, I've deleted this message as we don't allow recruiting or paid work in this server
Guys Where can i learn Python for discord bots/tool
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
does commands.is_owner work for app commands?
It should, at least it does in Pycord.
Although if you want owner only commands it is best to register them to a guild you own and limit the visibility to yourself. That way users will not get confused why they can't use the command
IMO best to not even register this as an app command at all. The entire point of app commands is to be discoverable, which is the exact opposite of what you're trying to do. Unless you're making use of app command specific features like autocomplete, you really shouldn't publish this
What do you recommend then? A terminal command?
Text commands are the standard, but really any unpublished way to send signals to the process
!eval 2+2
:warning: Your 3.12 eval job has completed with return code 0.
[No output]
!eval "2+2"
:warning: Your 3.12 eval job has completed with return code 0.
[No output]
Use print() lol
!eval console.log("Hello World");
There is not much reason to set up prefix commands in a bot that does not already use them. That would mean you have to have the message intent (and most people would want to use the message content intent for this)
If you use a guild command in a private guild it is essentially unpublished
This is not #bot-commands by the way
Unpublished like not synced?
I'm not sure what exactly they mean by that word. I see unpublished as anything not available to the public.
There isn't any "setup" to text commands though. You write the function and it's there
Sure you could jump through hoops to publish to a private guild but like why
Does discord.py use the same bot object for app and prefix commands? I just see very little reason to be promoting prefix commands at all.
At least for py-cord the hoop to publish a command to a guild is as simple as passing a guild_id to a kwarg
Prefix-based commands don't count as activity for the active developer badge, that's BS
Call me old school I don't give a damn
So all I have to do is add a ping slash command and problem solved
It is because discord does not want bots using prefix commands anymore.
I have seen 1.5 valid reason to use prefix commands. Everything else I have seen can be done with app commands
But I don't think the badge should be based on a preference. In my eyes, you can be an active developer by using only prefix commands
The problem is the active dev badge is somewhat meaningless. There are plenty of people who are not devs who have it too.
In the end discord makes the requirements and if they dont like prefix commands. they probably will not promote them in any way
pycord ๐ฉ
So I started my host and my dc bot and it doesnt show commmands, I restarted discord and etc. So I need to wait bcs It needs to configure?
Are you syncing the commands?
Well the commands show up instantaneously now u just need to refresh your discord client still my questions remains
how to check it
This is simply not true. Pretty much all of the forks that are in active development are of high quality
The differences are pretty much all pedantic, and the functional ones aren't that impactful in the grand scheme of things
@wanton current care to explain?
Hi guys, do yall have any good vids or website that can teach me how to create a discord bot?
All of the popular libraries will have documentation, though this presupposes some base level of python experience. Videos are ass, don't rely on them at all
When I wanted to create a discord bot, First, I made a connection to the gateway in order to receive event updates and then http requests and so on. It gets really deep this kind of stuff, so glad we have discord.py and other wrappers
!res
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Thereโs a few ones tagged โDiscord Botsโ
Can discord bots check reactions from messages?
Would it be able to like, save the id of the message i replied to, given only this message
Yes, message.reactions returns a list of discord.Reaction
And you can get the id with message.reference.message_id
You should probably read the docs ๐
in discord.py is it possible to have a alias for a slash command?
There's no first-class alias system provided by discord. I'd encourage you not to do this (just making multiple wrappers on the same logic), as this just makes the slash menu far more cluttered and less usable while also eating up the limited number of commands you have available. Because commands are searchable, there's really no need for this if they're intuitively named.
Commands are also permissioned individually, so this adds burden to server managers and margin for error
Ideally they add this as metadata on the command at some point in a way that doesn't clutter the UI
maybe as some kinda tree view
but that seems like it could be a nightmare for mobile
I have been told that the slash command menu searches the description of the command when trying to suggest commands. This may be worth a try, I have not tried it myself tho.
Looks like it does but the effectiveness of it will depend on how common the "alias" you are trying to use is in other commands descriptions. (And if you are trying to do the 1-2 character alias it might not work super great)
Can bots run other bots' commands
Weird, our dependecies is currently set with that version
hhmm
Trying to make a discord bot that has a whole bunch of features people may or may not want in their discord bot.. But IDK what people want? ๐ค any ideas or suggestions?
I don't believe bots can use other bots interactions, however a bot could use another bots "on_message" commands. Like !help but you'd have to program the bots to accept this.
Interactions being /help (slash commands) and buttons etc.
assuming you're remaining within TOS, there's no way for 1 bot to use another bots interactions. As far as I am concerned anyway
I'm sure someone smarter is going to come wooshing on any moment now, pushing their glasses back up towards their eyes as they say "Well uhhm actually."
What do you mean auto redraw?
Basically someone wins a giveaway, they can accept or decline in dms, if they decline it automatically rerolls the winner
Okay.. So why would you need a 2nd bot?
The lottery bot isnt mine
Then make a lottery bot
I made a bot to watch for wins and log them
Idk how ๐ญ, thats gonna take so much longer
Id have to start from scratch pretty much qww
A lottery bot is literally takes a list of people. rolls a random number, celebrates
with some shit in between
The time issue tho
well a simple lottery bot shouldn't be hard
Well. @spiral crypt you just solved this issue xD #discord-bots message
Im not the best programmer so i might have to turn the bot off to fix stuff, and thatll fuck up the timing
Give me a few hours I'll make a basic lottery bot. ;D
After my rhett and link episode tho. Not before or during. But after.
you can store the time in a db
Yeah thats getting a bit complicated for me
The closest thing i have is a json thats holding lottery wins
Fuck databases. I got a "level" bot that uses a json file ๐
!paste
I only use json for storing dictionaries, idk how to do anything else
well depends on your usecase for a small audience a json might work but for a larger one it will get slower as time passes
Made in like 15 minutes using duct tape, gorilla glue and a whole lot of caffeine
Wtf is a cog ๐ญ
โ๏ธ
OFC. A proper database will always be ideal. But who has time for that when you're trying to get the maths right? lol
Mine will probs add a new entry every like 2 days
So 175 entries a year
Itll be fineee
At such a low volume, you could even use pen and paper technically lol. But in terms of efficiency, you got json files (or similar. doesnt necessary need to be json), then lightweight databases like sqlite. then your more heavier databases. I dare not list one in fear of being struck down from someone from #databases
They're ruthless
Listed in worst to best. not best to worst
Im taking a database class, but theyre not teaching how to connect to it with languages
Theyre just teaching it using a dbms
TBH most of what you're learning now will be transferrable to most languages. The same stuff
if u can use basic SQL then the other part isn't hard
Im learning java, im self taught in python for the most part
Yeah im pretty good at sql
then using sqlite for starters shouldn't be a problem for you
Just select * and youre good
While I love this. select * is always fun. It's recommended you be more direct with what you want.
Ik x3 im jokin
I was blown by this
I do things the absolute laziest way possible. But if you want to be efficient with your resources you really should only grab what you need.
Ikik
Which is partly why a json file is not ideal
Literally i just use it to save a dictionary, and load it when the bot starts
Thats all its used for
Is this lottery bot going to be used as part of your classwork?
Naw this is for a guild from a game i play
oh
then why not use java for the bot?
Bc im better at python x3
I see
And its more convenient
Dicts in java are dum maps
Theres easy string parsing in python
With the silly [::[:[:[:[:[:[:]]]:];];];]
well then u should have map for how to go about your bot in mind?

This will result in an error. Not enout : and [
Naw it works trust
I also dont like writing system.out.println every time i have to test something
XD
oh sure
Andddd not having to worry about data types is also nice
Well in my case its setup pretty strictly so there isnt room for type errors
I dont have any user input stuff, anything going into the bot has a data type that i expect
๐ค How should the lottery setup proccess go? Multiple commands? 1 big ass command? maybe a command and buttons? ๐ค
hhmm..
Ngl id want it like the one thats already made is
It like opens a window or something with the info needed
oh
Time for lottery, name, description, and one more thing i forgor
Ignore my brainrot 
Description can have images too
I think
Tbh u could find a bot on github
Are you watching a minecraft live stream?
Hypixel skyblock
So you'd want the command/setup process to be easier to use on mobile than pc?
On pc its like that too, im just on my phone rn so that's where i yoinked the screenshot from
It makes a little box
This bot i have to make as ease of use as possible as the people using the lottery bot dont rlly wanna do extra work
And since theyre used to the old bot, well yeah
Aight
Well. Then it's really simple.
you want a command like /lottery or some crap. idk you figure that part out.
The command creates that popup dialogue box (forgot the discord name for it, it has a name.)
Fill it out. Then the bot throws an embed into a channel. is like "HEYYYY guys! @ everyone. Checkout my snazzy giveaway!" and people press a button to enter. It logs it.
Then after X time it's like "Oh hey hey. Checkout the winners.. @ <people who won>" and then DMs them
simple really
It uses a button
OKAY its 3:30am i need to sleep
I have class in 4 hours
Goodnight
Sorry to ask but I'm new to this and just if i can play MP3 or any other audio format file in discord bot by connecting it to vc?
Yes that's possible
Any audio should work as long as you have the codecs
What's codecs?
It's a program that compresses or decompresses streams or signals
Either they be audio video or others
By default most codecs come pre installed with os
Just use most commonly used audio format that is mp3
Yeah I'll just convert and upload it
You will need to use ffmpeg for that
Any guide for this?
As for how to actually configure that you might want to look up yt
As the voice part of discord is pretty much a mystery to me
Yeah that's what used for streaming audio via vc
The copyright law of the United States grants monopoly protection for "original works of authorship". With the stated purpose to promote art and culture, copyright law assigns a set of exclusive rights to authors: to make and sell copies of their works, to create derivative works, and to perform or display their works publicly. These exclusive r...
Good luck
Yeah in all my time doing this I can count on one hand the number of people with a legal and ethical use case for audio lol
๐
Lol I'll be using it for my personal bot in personal server
Doesn't matter
The TOS don't make a distinction anywhere that says the word "personal"
So what can they do
Terminate the bot
- my audio file will be like soundboard recorded by me and my friends
They don't fall under any copyright
Yeah, you are fine. They assumed you were downloading off of YouTube
This sounds like a use case for the built in soundboard
Any of you know good hosting providers for dc bots or just using a raspberry pi?
!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.
I host mine on cloud, as example digital ocean, i been using it for quite a few years, it has NEVER dropped down or had any sort of issues, prices are not so affordable, depending on your budget
Digital Ocean assures you 99.9% of uptime, only in cases as global disaster they drop
Indeed, very pricy. I researched and found netcup, sounds great and I think cheap pricing for the VPS
why discord profile images not loading iPhone , can anyone help??
Not related to this channel, contact https://dis.gd/support
So I have purchased A bot and the seller like isnt not responding to me and there is exe file where I can run the bot, and bot is online but its not showing commands, and on cmd its showing this eror:
[ERROR] Failed to load msgcmd cog. Error: Extension 'files.msgcmd' could not be loaded.
Well that's pretty ambiguous
It only tells tells there's something wrong with a file files.msgcmd and nothing else
im not a programer but what is files.msgcmd?
A file named msgcmd inside a folder called files
Tho there is nothing else here that tells what exactly is causing the issue
May be look for a log file inside your project directory
ah, I cant im not that good programar
Well then ask the guy from who you bought the code to fix his stuff
Cuz we can't help without a traceback of the error
there really is no reason for someone to sell you the code, as an exe
unless you asked specifically for an exe, that's pretty weird
Well an exe could be dangerous so i wont trust using one unless it s from a trusted source
Somehow I get the feeling even if they got source, they wouldn't be combing through it before running it
hey uhh how do these @ things work and how do i use them
They're called decorators, it's a built in python syntax
how can i make one?
It's usually whatever you called your Bot instance
skibidi = commands.Bot(...) # <-
# ^^^
@skibidi.event
...
@skibidi.command(...)
...
skibidi.run(...)
how would i do it in an eval?
crazy
Lol yeah
Yeah
without extensions ^^
You can do something like !jsk py _bot.user.name
Or !jsk py await _ctx.send("pog")
||even tho !jsk py "pog" works too||
idk python that much, can you only do it with that library?
An eval command?
yes
You can do it yourself but it'll probably be unsafe and be less functional
For a good eval command without any extensions, etc., see the following: https://github.com/Rapptz/RoboDanny/blob/rewrite/cogs/admin.py#L214-L259
Remember to follow the license if you plan to copy it
thx bro
hello
how do you add a cooldown to a slash command in a cog? (if it's different from setting it up outside a cog)
have you tried this import discord
from discord.ext import commands
Define a cooldown: 1 use every 10 seconds
@commands.cooldown(rate=1, per=10, type=commands.BucketType.user)
async def your_command(self, ctx):
await ctx.send("This command has a cooldown of 10 seconds per user.")
That's for prefix commands
from discord import app_commands
...
@app_commands.checks.cooldown(rate, per)
do you guys know how i can add an auto-react with a bot on every message
We do
But do you really want that
Reactions are heavily ratelimited.. adding one to every message can potentially get your bot api banned, temporary
really
how ratelimited
Well getting banned is a little extreme
async def on_message(message):
if message.author.id == myid:
message.add_reaction()
i want it to react me
Idr the exact numbers
I guess that's better than all messages
Do you know how make listeners generally?
no
!d discord.ext.commands.Bot.listen
@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready)
The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Example...
idk where to place it
I think above the async def on_message(....)
idk where to place that tho
In the file where your bot is declared, at any point after you declare it
# This example requires the 'message_content' intent.
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')
the decorater registers the on_message event, kinda like adds it to the bot I think and when an event is received through the gateway that equals that event name, the on_message will be executed
[ERROR] Failed to load view cog. Error: Extension 'files.view' raised an error: TypeError: SlotView1.init() takes 1 positional argument but 2 were given
Anyone could help me what I should change there?
Code?
yep listen decorator goes right above async def on_message
^
which is the module which runs your bot instance?
um docker
um idk
If you don't even know what file runs your bot, you're gonna have a bad time trying to modify that bot lol
Did you not make this code?
yes
its ballsdex bot
You should ask them then
Or build your own so you understand how the architecture works
another easy way to tell, which module is grabbing your discord token lol
they said its easy
its easy if you know whats going on
idk which one
If you don't understand it because you didn't build it, you're effectively asking us to fix something someone else built when they could just do it themselves
whats the actual issue OLi
Somewhere in all of this code should be a line which creates a Bot or Client object
Your goal is to find that
your listener isnt functioning correctly?
i just want my* bot to react me
are you sure the bot has the right permissions
setup intents and permissions is important
yes
it can react
read messages content and messages and channels
so you want it to react to what, text messages based on content?
kinda
but idk where to make the on_message
if it works
idk python
i want it to react me only
That's your first issue lol. Generally you're not going to get people here willing to do it for you for free
i thought they already did
like this
this is easy if you are the bot owner
That's an example
or you can filter responses by user ID
If you don't know python, you're asking us to write the code for you
he gave me a concerned emoji when i asked him
im just asking where to put it~
^
the most basic listener @commands.Cog.listener() async def on_message(self, message: discord.Message): if message.content.lower().strip() == "ping": await message.channel.send("pong")
its imported in all of them
is there any listener to check message content
datetime.datetime
I meant is it importing other modules from the same cog
commands core, dev dev
discord.ext.commands.bot.PrefixType
there is no .run in it
formatted kwargs.join
Imports are a red herring here. You need to find where the bot/client object is instantiated
Does anyone encounter the bug that ephemeral message is showed to all ppl in the channel ?
Then that's not ephemeral
And it's the first time I heard of this
I got 2 reports for 2 days but noone take a screenshot. But today I got screenshot that all ppl in the channel saw the message. And message has ephemeral=True set.
That's weird
Very wierd. The problem is that my messages contains passwords ;d
Idk how discord decide to not set the message to be ephemeral
https://dis.gd/bugreport if you have a concrete example that can be reproduced
Until then, probably something in your code that's wrong
It can't be wrong in my code it's hardcoded ephemeral=True
Or alternatively the library, but doubt
That's what everyone says, until they've seen the issue
Wait is the command you using a hybrid_command?
Just know that only interactions can respond with ephemeral messages
So yeah, if you have hybrid commands and use the prefix command, it will never be ephemeral
Well we found our rat i think
Well, as expected, your code that's wrong
I can see in the message it says only i can see it
Can you share the ss?
Non interaction response messages cannot have the ephemeral flag
Yes
Well incase of hybrid it doesn't throw error when ephemeral is True and you invoke it via context i think
Common hybrid command L
This is an ephemeral tho?
In here the command was invoked using prefix
slash command yes
That's why it's not ephemeral
so app command can't be ephemeral
It's not a slash command
It's a prefix command where the prefix is /pm
Check the diff in both commands usage in the screenshots u sent
On tells that which user has used the command the second one doesn't
These systems work completely differently. Setting your prefix to / just makes it more confusing that it already is
Confusing it's more like saying java and JavaScript are the same langs
Back to the topic tho
@delicate cape the solution to this problem is making your hybrid command into a pure app command
Or send in dm if it has been invoked via prefix command
This works too but it might get the bot flagged if too many users use it
aha
I have a question is it wrong to use it like this:
@commands.hybrid_group(name="pm")
async def parent_command(self, ctx: commands.Context) -> None:
...
@parent_command.command(description="Add/Update Upkeep date for House/Stronghold/Castle.")
@app_commands.describe(name="Name of the House/Stronghold/Castle")
@app_commands.autocomplete(name=get_passwords)
@app_commands.describe(upkeep="Type how much days left")
@app_commands.guild_only
async def upkeep(self, ctx: commands.Context, name: str, upkeep: int) -> None:
There's really no good reason to present them with a prefix option when you actively have a better option
@turbid condor thanks for the feedback I got it
happiness is merely a social construct..
No. How dare u deny my happiness
Anybody able to help out with some quick maths? :D
self.user_stats[member_id]['xp'] >= (self.config['xp_required_to_level'] * (self.user_stats[member_id]['level'] ** 2))
The problem with this formula is it goes quite fast. :/
It's a simple chat-level system thing that some discordbots have lol
I wanted to recrate it myself but the maths is the hardest part
I got it working with
@app_commands.checks.cooldown(1, 10.0)
but now I don't know how to get it to stop throwing errors at me and give them to the user
You just need an error function thingy.
@yourfunction.error
async def a_random_function_name_thats_useful(self, ctx, error):
# Error handling
For example this:
@app_commands.command(name="stats", description="Looks a user up")
@ app_commands.checks.has_any_role(*roles)
@guild_only()
async def stats(self, interaction:Interaction, steam:str):
await interaction.response.defer(ephemeral=self.config['ephemeral_response'])
steam_profile = await self.functions.get_steam_profile(steam=steam)
if not steam_profile:
await interaction.followup.send("That profile is set to private. To pull data the profile has to be public.", ephemeral=self.config['ephemeral_response'])
return
steam = steam_profile['steamid']
stats = await self.functions.pull_steam_data(steamid=steam)
if not stats:
await interaction.followup.send("No stats to be shown.")
return
steam_embed = await self.embed_factory.steam_embed(steam_profile=steam_profile)
base_embed = await self.embed_factory.pvp_stats(stats)
the_buttons = stats_buttons(stats=stats, config=self.config)
await interaction.followup.send(embeds=[steam_embed,base_embed], view=the_buttons)
@stats.error
async def stats_error_handler(self, ctx, error):
if isinstance(error, app_commands.MissingAnyRole):
roles = []
for role in self.config['allowed_roles']:
guild = self.bot.guilds[0]
the_role = guild.get_role(role)
roles.append(the_role.mention)
error = f"You do not have any of the required roles: {roles}"
await ctx.response.send_message(error, ephemeral=True)
else:
await ctx.response.send_message(error, ephemeral=True)
I just check to ensure they have the required role and if they dont i yeet an error at the user
seems pretty simple thx
Hi
Hi
Yep. Pretty pretty simple.
hey guys, getting an error with this code: ```py
country_codes_embed = nextcord.Embed(title="Supported Country Codes", description="").from_dict(
country_codes)
raise HTTPException(response, data)
nextcord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In embeds.0.description: This field is required
why are you using from_dict?
it is a method that suggested me and it says this: Converts a :class:dict to a :class:Embed provided it is in the format that Discord expects it to be in.
what is country_codes?
a dictionary with country codes
country_codes = {
"AD": "Andorra",
"AR": "Argentina",
"AU": "Australia",
...
That's not how from_dict() and I don't know why you got suggested that


