#discord-bots
1 messages · Page 287 of 1
Show screenshot of your chat
Beginning from the buy message
Also you can try print out bank and probot to check if they are what you want
You are missing await in ctx.send
I've solved it
Just changed bank.mention to mentioned_in
But thanks a loooot for help
how do i make a command with a limit use so where every member can only use the command 3 times and then it dont work anymore
app commands or text commands?
well tbh, both of them is similar solution, just make a custom check, store how many times they have used the command in a db
what error?
Can anyone help me with this RuntimeError with discord.py-ipc: It tells me I need to await the Server.start() function even though it isn't async
if __name__ == "__main__":
bot.ipc_server.start()
bot.run(TOKEN)
I checked everything in the docs and nothing in the code seemed to be wrong even though I still get the error
class TapBot(commands.Bot):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.ipc_server = ipc.Server(self, secret_key="")
async def on_ipc_read(self):
print("IPC is ready")
async def on_ipc_error(self, endpoint, error):
print(endpoint, "raised", error)
async def on_ready(self):
print("ready")
bot = TapBot(command_prefix='!',intents=intents)
it's caused by this https://github.com/Ext-Creators/discord-ext-ipc/issues/47 they never implemented a fix for it since it got abandoned
Description It seems like in discord.py 2.0, ever since Client.dispatch uses asyncio.create_task, we can't really start the server before the bot is running. Actual Behavior Traceback (most rec...
Ik but I'm not using this
discord/ext/ipc/server.py line 275
async def start(self):```
oh i see
https://pypi.org/project/discord.py-ipc/ is what I'm using
you could start it in the bot's setup_hook
Well the function start() itself is async but in the docs example file it wasn't async and in every other file it wasn't async either
poor example i guess, they forked the original
so the bot..ipc_server.start() shouldn't be async
the docs also says it's async
So should I delete the on_ready method or how do I start the ipc in the setup_hook
override the setup_hook method in your bot class and start the server there
ok
yes
ok thanks i'll try that out
Now I'm getting a database not callable error (the bot is also connected to mongodb)
full traceback and code please
k
class TapBot(commands.Bot):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.ipc_server = ipc.Server(self, secret_key="secret_key")
async def on_ipc_read(self):
print("IPC is ready")
async def on_ipc_error(self, endpoint, error):
print(endpoint, "raised", error)
async def on_ready(self):
print("ready")
async def setup_hook(self):
print("async def setup_hook")
bot.ipc_server.start()
bot.run('token')
def handle_discord():
print("starting discord")
global bot
bot = TapBot(command_prefix='!',intents=intents)
bot = pymongo.MongoClient("mongodb_connection")
And the error:
@bot.hybrid_command(name='help', description='Displays all available commands, both slash commands and prefixed commands.')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: 'Database' object is not callable
bot = pymongo.MongoClient("mongodb_connection")
why are you calling this bot
that is overriding bot = TapBot(command_prefix='!',intents=intents)
I didn't say delete it
Well I commented it
why
just to see what happens lol
just open your cmd and type that in
I have no clue what to do even tho the steps r right there
"Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings "
have you installed python lol
yeah
Then you have to add it to PATH
on windows use py
no idea how to do that :/
brb gonna watch a bibio
Now it just prints starting discord but doesn't connect to discord
Quite sure I'm doing something very wrong
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
send your full code
it's basically the same thing
class TapBot(commands.Bot):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.ipc_server = ipc.Server(self, secret_key="")
async def on_ipc_read(self):
print("IPC is ready")
async def on_ipc_error(self, endpoint, error):
print(endpoint, "raised", error)
async def on_ready(self):
print("ready")
async def setup_hook(self):
print("async def setup_hook")
bot.ipc_server.start()
bot.run('')
def handle_discord():
print("starting discord")
global bot
bot = TapBot(command_prefix='!',intents=intents)
handle_discord()
oh shoot
didn't see that
Now it has the exact same runtimeError as before
so it didn't change anything
then await it...
ok it works now
but is there a way for me to connect to mongodb again or should i just use another variable for the connection
Ok thanks
I made a path and I put in the "python -m pip install -r requirements.txt" and it told me to update my pip and I did and now i don't know what to do
Do i need to make a config file?
You should put the python directory into the PATH variables
sorry i'm back again lol
I can't call any commands now even though I didn't change anything
what intents do you have
I don'ty see any application command in your code
well in the rest of the code I didn't show you there are over 15 lol
Just for example the help command
thats why i asked for it
you need to sync the commands
!d discord.app_commands.CommandTree.sync
await sync(*, guild=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Syncs the application commands to Discord.
This also runs the translator to get the translated strings necessary for feeding back into Discord.
This must be called for the application commands to show up.
class TapBot(commands.Bot):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.ipc_server = ipc.Server(self, secret_key="
")
async def on_ipc_read(self):
print("IPC is ready")
async def on_ipc_error(self, endpoint, error):
print(endpoint, "raised", error)
async def on_ready(self):
print("Bot is ready")
async def setup_hook(self):
print("async def setup_hook")
await bot.ipc_server.start()
def handle_discord():
print("starting discord")
global bot
bot = TapBot(command_prefix='!',intents=intents)
bot.run(')
handle_discord()
bot.remove_command('help')
@bot.hybrid_command(name='help', description='Displays all available commands, both slash commands and prefixed commands.')
async def help(ctx):
helpEmbed = discord.Embed(
title="Command List" ,
description="Here is a complete list of all usable commands:",
color=discord.Color.blurple()
)
helpEmbed.add_field(name="help", value="Displays this message (Slash/Prefix)", inline=False)
helpEmbed.add_field(name="kick", value="Kicks a user (Slash/Prefix)", inline=False)
helpEmbed.add_field(name="ban", value="Bans a user (Slash/Prefix)", inline=False)
helpEmbed.add_field(name="add_warn", value="Warns a user, warns are stored on a database and can be viewed at all time. (Slash/Prefix)", inline=True)
helpEmbed.add_field(name="reset_server_warns", value="Resets the number of warns a user has on this server to 0. (Slash/Prefix)", inline=True)
helpEmbed.add_field(name="get_user_warns/get_global_warns", value="Views the amount of warns a user has on this server or the entire platform. (Slash/Prefix)", inline=True)
await ctx.send(embed=helpEmbed)
your bot's tree is accessable through bot.tree
it's a coroutine, so you should do it in the setup hook
ok
How I can check if is the bot in a guild?
I tried
guild = bot.get_guild(1142023460533571635)
if bot in guild:
print("yup im in")
But didn't work
if get_guild returns a Guild object then the bot is in that guild
if it returns None then the bot is not in that guild
Nope it's return guild
How do I can check if the bot in a guild?
get_guild(id, /)```
Returns a guild with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
Returns
The guild or None if not found.
Return type
Optional[Guild]
So I print guild to check?
You can't access guild if bot is not there
Logic
if statements ?
It's in
Is there any way to Verify a Member through your bot?
Then why check

Bot being called in guild it is not in is impossible situation
I gonna check if its in or no
I'm calling it in a guild but checking for another guild
And the bot in them both
theN wHY chECk
@vocal snow
I printed guild and it told me the guild name
Why'd you need to do that in first place
.
Bro read my first message
you aren't reading my messages
I read it
But didn't understand and you don't explain
How I can check if the bot in a guild?
get_guild returns None if the bot is not in that guild
it returns a Guild object if it is in that guild
I hope you know how to use if statements atleast?
They said the same thing 10 minutes ago
I am back (again) XD
The slash commands are not showing up in the server even though the commands are synced to the server
Because I have a need in my specific case where I need to do it?
And I figured it out already so nevermind
still the same issue
Show your syncing code
yes wait a minute
class TapBot(commands.Bot):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.ipc_server = ipc.Server(self, secret_key="")
async def on_ipc_read(self):
print("IPC is ready")
async def on_ipc_error(self, endpoint, error):
print(endpoint, "raised", error)
async def on_ready(self):
print("Bot is ready")
async def setup_hook(self):
print("async def setup_hook")
await bot.ipc_server.start()
await bot.tree.sync(guild=discord.Object(id=))
def handle_discord():
print("starting discord")
global bot
bot = TapBot(command_prefix='!',intents=intents)
bot.run('')
handle_discord()
I see no slash commands there
anyone know can a bot create its own activity in a server?
the slash commands are in another part of the code
Can you show how you define them?
@bot.hybrid_command(name='add_warn', description='Warn a user, if the users warn count reaches 3, they will be tempmuted')
@commands.has_permissions(kick_members=True)
async def add_warn(ctx, msg_id: str):
msg_id = int(msg_id) # Due to a bug in the discord API, the ID must be passed as a string and then converted to an integer.
msg = await ctx.fetch_message(msg_id)
serverId = ctx.message.guild.id
print(serverId)
db.server_messages_log.insert_one( #MongoDB Collection Database
{
"message": msg.content, #Get content of warned message
"message_author": msg.author.id, #Get ID of warned user
"message_server": serverId #Get Server ID
}
)
await ctx.send(f"{msg.author} has been warned, you can see how many warnings they got using */getuserwarns*")
```This one as an example
Then I got no idea 🤷
How do you get bot variable?
It's created inside the function and is runned right after that
You aren't doing something between creating it and running
I know but I don't see an issue there
Send your full code, maybe?
Because the bot is connecting , it just doesnt sync properly
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
I think that you have some different bot variables
The full code is over 300 lines long so that wouldn' be a good idea
Just do it

Nope activity is global can't be specific for each server
Remove your bot's token out of the code 
All your code after line 40 is unreachable
From what I see there, you're running the bot before defining the slash commnds
so how should it be
But they are synced in the setup_hook
They're not defined, so it doesn't matter
And I got told to sync in the hook
Welp all that is ok
should it be in the handle_discord function then?
No
You are syncing at the right place
Why are you making a function for just creating an instance and running it anyway
U don't need the handle_discord error as far as i can see you are creating an instance there and running your bot
Where as you can just define your bot variable and at the end of your script do bot.run('Token')
Why couldn't it? It's just like any other variables
bot = ...
# commands
bot.run()
Or instances
@gametime.error
async def gametimeError(self, interaction: discord.Interaction, error: app_commands.AppCommandError):
if isinstance(error, app_commands.CommandOnCooldown):
timeRemaining = str(datetime.timedelta(seconds = int(error.retry_after)))
await interaction.response.send_message(f"Please wait `{timeRemeaning}` to use this command again.", ephemeral=True)```
```py
await self.on_error(interaction, error) # type: ignore
TypeError: gametimeError() missing 1 required positional argument: 'error'```
i dont get it
Well it still doesn't sync properly
await self.bot.tree.sync()
Well I still get the error
Why is there a self argument there
What error
This one ^
!traceback
Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.
A full traceback could look like:
Traceback (most recent call last):
File "my_file.py", line 5, in <module>
add_three("6")
File "my_file.py", line 2, in add_three
a = num + 3
~~~~^~~
TypeError: can only concatenate str (not "int") to str
If the traceback is long, use our pastebin.
self.tree, not self.bot.tree
You said self.bot.tree
It was not me
oh sorry
.
i remember like an year or 2 ago, i had a friend who showed me him playing minecraft in discord vc, idk if it was a screen share by a self bot or activity. i dont remember correctly i knew nothing about coding and discord bots at that time.
Show the full code 🤷
Bruh
class TapBot(commands.Bot):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.ipc_server = ipc.Server(self, secret_key="TAPBOT_DASH")
async def on_ipc_read(self):
print("IPC is ready")
async def on_ipc_error(self, endpoint, error):
print(endpoint, "raised", error)
async def on_ready(self):
print("Bot is ready")
async def setup_hook(self):
print("async def setup_hook")
await bot.ipc_server.start()
await self.tree.sync(guild=discord.Object(id=864807058351194112))
bot = TapBot(command_prefix='!',intents=intents)
I believe that's called screen sharing
I said full code, or is that not a proper word
i literally typed than
The full code is litterally 300 lines long
that*
What's the problem? There's !paste
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
That's just a normal Discord feature
Looks ok
I am not good at syncing, try to use copy_global_to
Or syncing globally
Still doesn't fix the issue
Are you passing a valid guild id
Nevermind, I fixed the issue
Yes, but it works now
Learn python first
inow it !

god evry body roasts me
A hands-on guide to Discord.py
!d discord then
In order to work with the library and the Discord API in general, we must first create a Discord Bot account.
Creating a Bot account is a pretty straightforward process.
Not roasting, 8 out of 10 people don't know how a method works when they start with Discord bots
guide to discord.py
CHECK OUT
(no way)
the stare of that turtle i just had a neightmare about turtles
Nightmare about turtles
i found 10 in my closet 5 were koopas
Banned in google? :p
yes
Sad
i guess im shadow banned 
cause i am 
also :)
my code be like
?
thats something that OpalMist would say
If you have something then you can show it
We can't know what did you talk about somewhere else
!pypi exceptions
since when there is no command to copy
desent to madness has began
how bout pip install py-exceptions
I don't like the fact that they have no working source link tho
And the docs :/
And last update 8 years ago
yeah why would you need to install such package
it worked
my nightmare was a prophesie
wait what py PS C:\Users\SALAH\Desktop\bot> pip install py-exceptions Downloading py_exceptions-1.2.2-py3-none-any.whl (21 kB) Requirement already satisfied: Werkzeug>=2.0.1 in c:\users\salah\appdata\local\programs\python\python311\lib\site-packages (from py-exceptions) (2.3.6) Requirement already satisfied: Jinja2 in c:\users\salah\appdata\local\programs\python\python311\lib\site-packages (from py-exceptions) (3.1.2) 0.1->py-exceptions) (2.1.3) Installing collected packages: py-exceptions Successfully installed py-exceptions-1.2.2 PS C:\Users\SALAH\Desktop\bot> & C:/Users/SALAH/AppData/Local/Programs/Python/Python311/python.exe c:/Users/SALAH/Desktop/bot/main.py Traceback (most recent call last): File "c:\Users\SALAH\Desktop\bot\main.py", line 22, in <module> import exceptions ModuleNotFoundError: No module named 'exceptions' PS C:\Users\SALAH\Desktop\bot> & C:/Users/SALAH/AppData/Local/Programs/Python/Python311/python.exe c:/Users/SALAH/Desktop/bot/main.py Traceback (most recent call last): File "c:\Users\SALAH\Desktop\bot\main.py", line 22, in <module> import exceptions ModuleNotFoundError: No module named 'exceptions' PS C:\Users\SALAH\Desktop\bot>
can you show how you use the exceptions module
online code
it's some dead library that hasn't any info and is maybe a malware
what for
na they didnt know what malware was 8 years ago fr
🧐
xdd
bros still trying
yes !
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
why is this
doesnt it tell you in dms?
!pypi py-exceptions
py-exceptions page looks a bit better
nice
.vscode in the source 💀 (of the library, i am talking not to you)
at least not venv
what ?
they just disable linters
exceptions is not a library
its a folder !
o i just noticed its krypton template
"""
Copyright © Krypton 2019-2023 - https://github.com/kkrypt0nn (https://krypton.ninja)
Description:
🐍 A simple template to start to code your own and personalized discord bot in Python programming language.Version: 5.5.0
"""
It wasn't very hard :p
i never read comments
fyi such projects always have either poetry set up or requirements.txt file containing all packages needed to install
to install them from file you do pip install -r path/to/requirements.txt
requirements.txt lines 1 to 3
aiohttp
aiosqlite
discord.py```
Hello, I am getting this error when i run my bot.```
discord.app_commands.errors.CommandSyncFailure: Failed to upload commands to Discord (HTTP status 400, error code 50035)
In description._errors: [{'code': 'BASE_TYPE_REQUIRED', 'message': 'This field is required'}]
The error is stemming from when i try to sync the bot's command tree to my guild. I don't quite understand the error message 😭
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
Show slash commands
This was the command I was working on when the error happened
@app_commands.command(name="open", description="")
async def open_box(self, interaction: discord.Interaction, box_name: str, quantity: int):
author = interaction.user
box_name = "Box"
embed_desc = ""
box = next(b for b in BOXES if b.name == box_name)
for _ in range(quantity):
prize = box.roll_prize()
embed_desc += prize + "\n"
embed = discord.Embed(
color=colors.default,
title="Title",
description=embed_desc
)
embed.set_author(name=author.name, icon_url=author.avatar)
await interaction.response.send_message(embed=embed)
description cant be empty string
either dont pass it or set it to something
lol, just looked at the blog
were do i find the rest
The permissions are the perms your bot requires when joining a server
As far as i know it's an int value
it for me so i dont care am goingt o give it admin
inow its not going to abuse its pawer right ?
Which can be obtained by selecting the permissions that are present in the dev portal on page where you reset the token at the bottom
Select the perms your bot needs and then it will show u some int value copy and paste it here
Welp unless it's token gets leaked but still I won't prefer giving a bot admin perms u should at least know what perms your bots need instead of giving it admin rights
i whant tomake an ai bot
so it talkes to other ai bots
what about prefix
The prefix you want for your bot commands
oh
so py 2023-08-19 15:00:25 INFO discord_bot Loaded extension 'fun' 2023-08-19 15:00:25 INFO discord_bot Loaded extension 'general' 2023-08-19 15:00:25 INFO discord_bot Loaded extension 'moderation' 2023-08-19 15:00:25 INFO discord_bot Loaded extension 'owner' 2023-08-19 15:00:25 INFO discord_bot Loaded extension 'template' 2023-08-19 15:00:25 WARNING discord.ext.commands.bot Privileged message content intent is missing, commands may not work as expected. 2023-08-19 15:00:25 INFO discord.client logging in using static token 2023-08-19 15:00:29 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: 41105e3124bf6234dd5e2ac9f70839fd). 2023-08-19 15:00:32 INFO discord_bot Logged in as Slimmy 2023-08-19 15:00:32 INFO discord_bot discord.py API version: 2.3.2 2023-08-19 15:00:32 INFO discord_bot Python version: 3.11.4 2023-08-19 15:00:32 INFO discord_bot Running on: Windows 10 (nt) 2023-08-19 15:00:32 INFO discord_bot -------------------
And set the sync commands globally to true
So that your slash appear commands on all the servers the bot is in
Your session id nothing you should be concerned with
so how to test the bad boy
Welp try using it's help command
were
Wait never mind you don't have message_content intent enabled in your code
So prefix commands won't work
Enable that first
were
where to ask general py doubts?
in help quick
quick help
alr ty
i thinck it in pygame soory if you dont find it
I am trying to find the channel llol
just ask in general
alr
also #❓|how-to-get-help you can ask anything (python) on forum
The intent is enabled in your code then weird that it will throw a warning
so what do i do?
its just this place *is for https://discord.com/channels/267624335836053506/343944376055103488
Try using a command for your bot
it's for ironmelts
neeeded to ping him mb
Just exit the code from terminal
i did it it works
Welp there u go then
old turn off turn on
reliable
so can i ask can i connect chat gpt or an ai to this so the bot can use commands or ect
is it possible
Why wouldn't it be
You can connect chat gpt or any other ai but remember it won't be able to use other bots command especially if they are slash commands
Show u what?
how to send to make the bot answere like chat gpt wait i have something
60 to 50 %
so yes
but new to bot coding
this was an ai i made
doesnt work now
I don't see how making a bot in discord.py is more difficult than just Python
well it is
its like python to pygame
How is that?
It says there in the error
server_id = await bot.wait_for("message", check= lambda m: m.channel == ctx.channel and m.author = ctx.author, timeout=300.0)
m.author = ctx.author part is invalid
!e
lambda: (a = 0,)
@naive briar :x: Your 3.11 eval job has completed with return code 1.
001 | File "/home/main.py", line 1
002 | lambda: (a = 0,)
003 | ^^^^^
004 | SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
There
here
You:: hi
Slimy.exe: Slimy.exe will ruin your day by convincing you to do something that
will make you look foolish or silly in front of your friends. He will try to
manipulate you into doing something embarrassing or outrageous, like singing a
song in public or wearing an outrageous outfit.
You:: hi slimmy.exe long time no see you didnt exist just becaause i dindnt have mto pay for your api
Slimy.exe: why you think money is the only way to exist? I'm here to ruin your day
and make you look foolish in front of your friends. How about this: I challenge
you to a rap battle in the middle of the street. If you win, I'll leave you alone.
But if I win, you have to do whatever I say for the rest of the day! What do you
say?
You:: ehh no!
Slimy.exe: I challenge you to a dance-off in the middle of the street. If you win,
I'll leave you alone. But if I win, you have to do whatever I say for the rest of
the day! What do you say?
You:: stop chalenging me itsbeen 2 years you didnt talk to someone ad that what ySlimy.exe: I'm back and I'm here to ruin your day. How about this: I challenge you
to a rap battle in the middle of the street. If you win, I'll leave you alone. But
if I win, you have to do whatever I say for the rest of the day! What do you say?
You::
that the bot i made in python but not for discord
hes so smart
And?
how can i add it to my discord bot
Just wait for a message from a user then send its response to a channel? 🤷
god what have i made py Slimy.exe: python programers, I'm Slimy.exe and I'm here to ruin your day! Prepare to be cursed and insulted, because that's what I do best! You:: i dont thinck its an big enuff presentation why dont you tell them ... what uld whant to do in discord and stuff Slimy.exe: I'm here to make your life miserable! I'll be trolling in the chat, insulting people, and generally making a nuisance of myself. I'll also be spamming the chat with memes and other nonsense. So if you want to have a good time, stay away from me! You::
This is off-topic to the channel
how ?
no its testing my bot
its literaly what i did
..
but good idea
If the bot isn't in the guild, then None is returned 🤷
It's a place to ask questions related to discord bot issues not showcase
ok could you help pls
Well, it's also for discussions, but a GPT model isn't appropriate in this channel on its iwn
i need to send the users input to my ai and the response to discord
I know
But in the wait for Im sending the same Id that's in Check command (this server id the bot is in it)
In command it's sending server name but in bot.wait_for it's None
Same Id but different answers
What?
how to do that
And don't tell me that you're putting a message object into a get_guild method
Only the difference is the first one is from bot.wait_for but the second the Id in the project

So how I get it?
I need the content
Then get it?
I will test
Welp it depends an how u want to send it if you want to use a command then create a message perimeter in it which will contain a user message and then send the message to your bot
And similarly use ctx.reply and use the variable that u have created which holds the response
no the bot is free
its like liberating him just it need an input
Same
Same what
Yeah i told u a method on how to do that
Show your code, and just the important related part, not the whole
server_id = await bot.wait_for("message", check=lambda m: m.channel == ctx.channel and m.author == ctx.author, timeout=300.0)
except asyncio.TimeoutError:
await ctx.send("Time ended")
else:
b_guild = bot.get_guild(server_id.content)
if b_guild == None:
await ctx.send("you enterd a wrong id please try again")
well am doomed
.content returns a string, get_guild needs an integer
int(server_id.content)?
Yes?
I will try
How will .content return an id I'm confused in first place
If the content of the message is an ID
Oh i get it
for a beginner, even if they're bringing experience from another language, they're tackling a lot of python concepts at once (writing functions/modules/packages, using objects, concurrent programming, even just control flow and invoking python) compared to other projects that demand fewer prerequisites
I mean, that's just Python, isn't it? I don't think discord.py invented functions, asynchronous programming, and OOP
its not that they invented it, but that they're prerequisites to using discord.py effectively
Beginner should start from basics, not discord.py then. If it can't take all of that at once

those are known as choices, which can either be defined as part of the command or written with an autocomplete callback where the bot responds with choices based on the user's input
if you're asking how to write it in python, that depends on what library you're using for your bot
Want users to select something from a hard coded list?
Use "choices", three different ways to do it.
View Documentation (has examples)
Option 0: True & False
Need True and False as choices? Simply type the argument with bool and discord will handle it.```py
@...command(...)
async def testephemeral(
interaction: Interaction,
ephemeral: bool
):
print(ephemeral, type(ephemeral))
will print either True or False
**Option 1: typing.Literal**
This is the easiest. Also works for hybrids```py
from typing import Literal
@...command(...)
async def choosecolour(
interaction: Interaction,
colour: Literal["Red", "Green", "Blue"]
):
print(colour) # will print either Red, Green or Blue
Option 2: @app_commands.choices```py
from discord import app_commands
@...command(...)
name is shown to the user and value is returned to you.
value can be of type str, int or float.
@app_commands.choices(
colour=[ # param name
app_commands.Choice(name="Red", value="red"),
app_commands.Choice(name="Green", value="green"),
app_commands.Choice(name="Blue", value="blue")
]
)
async def choosecolour(
interaction: Interaction,
colour: Choice[str] # [str] denotes the type, not required.
):
print(colour) # will print the chosen Choice obj
colour.name for the name and colour.value for the value you set
**Option 3: enum**```py
from enum import Enum
class Colours(Enum):
# format: name - value
Red = "red"
Green = "green"
Blue = "blue"
@...command(...)
async def choosecolour(
interaction: Interaction,
colour: Colours
):
print(colour) # will print our enum. in this case, the Colour class above
# colour.name for the name and colour.value for the value you set
Understood
These are only in case you are using discord.py
disnake?
Try option 1 or 3
Nah i mean from above examples
Like this
pre-defined choices: https://docs.disnake.dev/en/stable/ext/commands/slash_commands.html#choices
autocomplete: https://docs.disnake.dev/en/stable/ext/commands/slash_commands.html#autocompleters
note that discord doesnt allow giving the user more than 25 choices at a time
I can't get over the fact that they hard-coded integers
oh yeah min/max value exists, weirdly ive never seen what that looks like
Discord will tell the user that they exceeded the limit
ah i see
It's expecting a dict
?
You can define an enum in one line:
py Animal = commands.option_enum({"Dog": "dog", "Cat": "cat", "Penguin": "penguin"})Or even forget about values and define the enum from list:py Animal = commands.option_enum(["Dog", "Cat", "Penguin"])
I add 24 number
if you prefer this way of accepting input, use their commands.Range instead
https://docs.disnake.dev/en/stable/ext/commands/slash_commands.html#number-ranges
Select
Traceback (most recent call last):
File "C:\Users\simoc\OneDrive\Desktop\Comune di Roveto\DiscordBot\Comune di Roveto, Regione Toscana V2\bot.py", line 6, in <module>
from discord.ext import commands
File "C:\Users\simoc\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\__init__.py", line 19, in <module>
from .flags import *
File "C:\Users\simoc\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\flags.py", line 73, in <module>
@dataclass
^^^^^^^^^
File "C:\Users\simoc\AppData\Local\Programs\Python\Python311\Lib\dataclasses.py", line 1230, in dataclass
return wrap(cls)
^^^^^^^^^
File "C:\Users\simoc\AppData\Local\Programs\Python\Python311\Lib\dataclasses.py", line 1220, in wrap
return _process_class(cls, init, repr, eq, order, unsafe_hash,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\simoc\AppData\Local\Programs\Python\Python311\Lib\dataclasses.py", line 958, in _process_class
cls_fields.append(_get_field(cls, name, type, kw_only))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\simoc\AppData\Local\Programs\Python\Python311\Lib\dataclasses.py", line 815, in _get_field
raise ValueError(f'mutable default {type(f.default)} for field '
ValueError: mutable default <class 'discord.utils._MissingSentinel'> for field name is not allowed: use default_factory
Got this Error after updating Python
Someone know what can be wrong? 😭
(when i run the command py bot.py)
id understand
You can't use empty string as option
[str(x) for x in range(1, 25)]
Or even better would be map(str, range(1, 25))
server_id = await bot.wait_for("message", check=lambda m: m.channel == ctx.channel and m.author == ctx.author, timeout=300.0)
except asyncio.TimeoutError:
await ctx.send("Time ended")
else:
b_guild = bot.get_guild(int(server_id.content))
Here if the user send any message not int it's turn into error so I can handle it?
Hello I am looking for a discord free bot maker (the bot is simple
i don't understand the question
If the user send anything except a int there is error happens so how I can handle this error?
You get error name when you run it /
can you help me in something? lol
sure
this
And I have another question
spent 3 days trying to solve
When this happens (ValueError) how I can make the bot wait another time or still waiting?
bruh, if you added the runout is useless that the bot can wait
try:
raises value error here
except ValueError:
do same thing here
Bro read my question
You can use while True too imo, but since you only wanna give 2 tries just repeat the same step
just remove the timeout lol
This?
I want a time for trying not a number of tries
you got it
._.
But
If a value error happened the bot will never wait anymore
because the time will be finished
Nah
.... Just while True it no?
while True:
wait here
break
except TimeoutError:
break
except ValueError:
continue
Something like dat
so the bot will wait for ever?
Ah yup
It will break the loop if it raises timeouterror
Show the code
alr
Also after a successful wait finishes you can simply break out of the loop and do your stuff
every time i run py bot.py i got the same exat error, even with different code
So you get it when you just run the code, bot doesn't run at all?
yea and the bot i never checked, i'll try
(asking because it's running fine by me, maybe you get error when calling some command)
no the bot doesn't start
You might have multiple forks of discord.py installed. Do pip freeze, see what it prints
Or maybe a fork and discord.py 
aiohttp==3.8.3
aiosignal==1.3.1
altgraph==0.17.3
async-generator==1.10
async-timeout==4.0.2
attrs==22.2.0
beautifulsoup4==4.11.1
certifi==2022.9.24
cffi==1.15.1
chardet==5.1.0
charset-normalizer==2.1.1
click==8.1.3
colorama==0.4.6
cookies-discord-components==3.0.0
dipy==1.6.0
discord-py-interactions==5.9.2
discord-typings==0.6.0
discord-ui==5.1.6
discord.py==2.3.2
discord.py-message-components==1.7.5.4
distlib==0.3.6
docutils==0.20.1
emoji==2.7.0
filelock==3.12.2
Flask==2.2.2
frozenlist==1.3.3
h11==0.14.0
h5py==3.8.0
idna==3.4
itsdangerous==2.1.2
Jinja2==3.1.2
Kivy==2.2.0
kivy-deps.angle==0.3.3
kivy-deps.glew==0.3.1
kivy-deps.sdl2==0.6.0
Kivy-examples==2.2.0
Kivy-Garden==0.1.5
MarkupSafe==2.1.2
MouseInfo==0.1.3
multidict==6.0.4
nibabel==5.0.0
numpy==1.24.2
outcome==1.2.0
packaging==23.0
pefile==2023.2.7
Pillow==9.4.0
platformdirs==3.5.3
py-cord==2.0.0b1
PyAutoGUI==0.9.53
pybrot==0.0.7
pycparser==2.21
PyGetWindow==0.0.9
Pygments==2.15.1
pyinstaller==5.13.0
pyinstaller-hooks-contrib==2023.5
PyMsgBox==1.0.9
pyperclip==1.8.2
pypiwin32==223
PyRect==0.2.0
PyScreeze==0.1.28
PySocks==1.7.1
python-dotenv==1.0.0
pytweening==1.0.4
pywhatkit==5.4
pywin32==306
pywin32-ctypes==0.2.2
reactionmenu==3.1.3
requests==2.28.1
scipy==1.10.0
selenium==4.8.2
sniffio==1.3.0
sortedcontainers==2.4.0
soupsieve==2.3.2.post1
table2ascii==1.1.0
termcolor==2.2.0
thread6==0.2.0
TIME-python==0.0.17
tomli==2.0.1
tqdm==4.64.1
trio==0.22.0
trio-websocket==0.9.2
typing_extensions==4.5.0
urllib3==1.26.12
virtualenv==20.23.0
wcwidth==0.2.5
webdriver-manager==3.8.5
Werkzeug==2.2.2
wikipedia==1.4.0
wsproto==1.2.0
yarl==1.8.2

that mean? ;-;
Py cord is installed lol
💀💀💀💀
what the fuck is py-cord, i'm trying to understand it
also discord-ui
Discord py message components, discord pu interaction
discord.py-message-components=
💀
a lot of
cringe
If its in venv delete the venv actually and install from scratch
This emoji looks like a sad white squid, just wanted you to know

and how do i check
Eyes aint matching kinda 😔
pip uninstall discord-ui
pip uninstall discord.py-message-components
pip uninstall py-cord
pip uninstall discord-ui
pip uninstall discord.py
pip install discord.py -U
like this i guess
but easier will be recreate enviroment if you have it, that's true
pip install -U discord.py should do the trick of uninstalling it and reinstall it
It will uninstall and install the stable and latest version for you
How I can make the bot break the while when a correct ID was sent
while True:
try:
server_id = await bot.wait_for("message", check=lambda m: m.channel == ctx.channel and m.author == ctx.author, timeout=300.0)
break
b_guild = bot.get_guild(int(server_id.content))
except asyncio.TimeoutError:
await ctx.send("Time ended")
break
except ValueError:
await ctx.send("Please send a correct Id")
continue
I tried
else:
Break
Add break after b_guild var
I have the last question (for today lol), how do i add this to an embed message?
Add buttons?
ye
^
!d discord.ui.View
class discord.ui.View(*, timeout=180.0)```
Represents a UI view.
This object must be inherited to create a UI within Discord.
New in version 2.0.
!d discord.ui.Button
class discord.ui.Button(*, style=<ButtonStyle.secondary: 2>, label=None, disabled=False, custom_id=None, url=None, emoji=None, row=None)```
Represents a UI button.
New in version 2.0.
Buttons example
The link vitness gave is a example
i need some library for that or no?
Nop
discord.py :/
alr
hello can i get help for my bot i whant to add a comand so it talks the the ai in a script and the rest is normal
discord.py is continued by Danny again if u dont know
emb = disnake.Embed(color=0xff0000)
emb.add_field(name='Error', value="Invalid round id")
await ctx.response.send_message(embed=emb)
if round_length > 36:
emb = disnake.Embed(color=0xff0000)
emb.add_field(name='Error', value="Invalid round id")
await ctx.response.send_message(embed=emb)```
Wrong?
a harmless bot
idk he say error
Show it then
me ?
File "C:\python\Lib\site-packages\disnake\ext\commands\slash_core.py", line 737, in invoke
raise CommandInvokeError(exc) from exc
disnake.ext.commands.errors.CommandInvokeError: Command raised an exception: UnboundLocalError: cannot access local variable 'count' where it is not associated with a value
Didn't work
😦
Show the full traceback
I fixed
@buoyant quail
Can you see my question please
.
The thing Spooky suggested looks fine
while True:
try:
server_id = await bot.wait_for("message", check=lambda m: m.channel == ctx.channel and m.author == ctx.author, timeout=300.0)
b_guild = bot.get_guild(int(server_id.content))
break
except asyncio.TimeoutError:
await ctx.send("Time ended")
break
except ValueError:
continue
Didn't work
For b_guild?
It printed them both
Show it
while True:
try:
server_id = await bot.wait_for("message", check=lambda m: m.channel == ctx.channel and m.author == ctx.author, timeout=300.0)
b_guild = bot.get_guild(int(server_id.content))
print(server_id.content)
print(b_guild)
break
except asyncio.TimeoutError:
await ctx.send("Time ended")
break
except ValueError:
continue
else:
if b_guild == None:
await ctx.send("you enterd a wrong id please try again")
else:
guild = bot.get_guild(1142023460533571635)
probot = guild.get_member(282859044593598464)
bank_id = 1113386046021963776
bank = guild.get_member(bank_id)
price = count*700
tax = price / 0.95
tax = ceil(int(tax))
await ctx.send("لقد قمت بإدخال ايدي صحيح ✅\n يرجى التحويل لإتمام عملية الشراء")
await ctx.send(f"c {bank_id} {tax}")
try:
bot.wait_for("message", check= lambda m: m.author == probot and m.channel == ctx.channel and str(price) in m.content and bank.mentioned_in(m))
except asyncio.TimeoutError:
await ctx.send("Time ended")
It was working perfectly before add the while
When you break you are exiting it without going into else
also there is some strange indentation
What?
Should I add else in while?
Wdym
while True:
try: # 4 spaces
else: # 2 spaces
It won't run too
Cause I'm in phone
So how to solve it
I'd replace break to return in TimeoutError
And put everything that goes after the loop outside the else
I will try that
When I removed the else it worked but another problem happend
while True:
try:
server_id = await bot.wait_for("message", check=lambda m: m.channel == ctx.channel and m.author == ctx.author, timeout=300.0)
b_guild = bot.get_guild(int(server_id.content))
print(server_id.content)
print(b_guild)
break
except asyncio.TimeoutError:
await ctx.send("Time ended")
return
except ValueError:
continue
if b_guild == None:
await ctx.send("you enterd a wrong id please try again")
else:
guild = bot.get_guild(1142023460533571635)
probot = guild.get_member(282859044593598464)
bank_id = 1113386046021963776
bank = guild.get_member(bank_id)
price = count*700
tax = price / 0.95
tax = ceil(int(tax))
await ctx.send("لقد قمت بإدخال ايدي صحيح ✅\n يرجى التحويل لإتمام عملية الشراء")
await ctx.send(f"c {bank_id} {tax}")
try:
bot.wait_for("message", check= lambda m: m.author == probot and m.channel == ctx.channel and str(price) in m.content and bank.mentioned_in(m))
except asyncio.TimeoutError:
await ctx.send("Time ended")
else:
channel = bot.get_channel(1142023763936940052)
await channel.send(f"$join {server_id.content} {count}")
Look at the last line
It should happen only of the bot.wait_for happend
But it happen when I send the id
??
!d discord.Client.wait_for
wait_for(event, /, *, check=None, timeout=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Waits for a WebSocket event to be dispatched.
This could be used to wait for a user to reply to a message, or to react to a message, or to edit a message in a self-contained way.
The `timeout` parameter is passed onto [`asyncio.wait_for()`](https://docs.python.org/3/library/asyncio-task.html#asyncio.wait_for). By default, it does not timeout. Note that this does propagate the [`asyncio.TimeoutError`](https://docs.python.org/3/library/asyncio-exceptions.html#asyncio.TimeoutError) for you in case of timeout and is provided for ease of use.
In case the event returns multiple arguments, a [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple) containing those arguments is returned instead. Please check the [documentation](https://discordpy.readthedocs.io/en/latest/api.html#discord-api-events) for a list of events and their parameters.
This function returns the **first event that meets the requirements**...
its coroutine
Not awaiting async function = just skipping it
why do i have this https://paste.pythondiscord.com/PDUA
pls help
like what ?
bot_token, token, openai_api_key
Also it looks like errors from different codes
because bot_token and token are in the same place in the error
yes just look at the last error
ah, the last
File "C:\Users\SALAH\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 860, in run
asyncio.run(runner())
File "C:\Users\SALAH\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 186, in run
raise RuntimeError(
RuntimeError: asyncio.run() cannot be called from a running event loop
sys:1: RuntimeWarning: coroutine 'Client.run.<locals>.runner' was never awaited
PS C:\Users\SALAH\Desktop\bot\bot-main>
If you are running bot from the async function, you need to use bot.start
If not, then bot.run
!d discord.ext.commands.Bot.start
await start(token, *, reconnect=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A shorthand coroutine for [`login()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.login) + [`connect()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.connect).
how whould the line look like
like this ?```py
async def main():
await init_db()
await load_cogs()
status_task.start()
bot.start(config["bot_token"])
if name == "main":
asyncio.run(main())```
async def main():
await init_db()
await load_cogs()
status_task.start()
bot.start(config["token"])
if __name__ == "__main__":
asyncio.run(main())```
It's an async function
idont now shit about bot programing
!e
import asyncio
async def some_start():
...
async def main():
some_start()
if __name__ == "__main__":
asyncio.run(main())
@buoyant quail :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | /home/main.py:8: RuntimeWarning: coroutine 'some_start' was never awaited
002 | some_start()
003 | RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Maybe with the warning you will guess what you need?
Also discord.py has a small text about coroutines
https://discordpy.readthedocs.io/en/stable/faq.html#coroutines
You are "awaiting" 15 times in your code
is it bad or good ? i used a template a pice of my ai and chat gpt to make this
inow its bad
using chat gpt
Second part of the message is bad
Awaiting is good - with it you can don't wait for some long operations and doing all the thing almost parallel (not parallel tho)
Does discordpy support running two bots at the same time?
Two same bots?
Actually doesn't matters
Yes, it does. But it's not what you usually do
With different api tokens
so tell me @buoyant quail basicly to fix the code whats the ligne ineed to add/delete
await bot.start(...)
Why not to run them as different scripts?
By "it does" i mean that you need to do it by yourself
Maybe threading
Or something like asyncio.gather, i am not sure
so where :/ sorry for being dum
Ok, thank you!
@buoyant quail ?
Best way is separate processes for sure
Where you have it without await.
async def main():
await init_db()
await load_cogs()
await status_task.start()
await bot.run(config["token"])
if name == "main":
asyncio.run(main())
await bot.start(config["token"])
File "C:\Users\SALAH\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 2040, in change_presence
await self.ws.change_presence(activity=activity, status=status_str)
^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'change_presence'
@woven dew
import asyncio
import discord
from discord.ext import commands
intents = discord.Intents.all()
bot1 = commands.Bot(".!", intents=intents)
bot2 = commands.Bot(".!", intents=intents)
async def main():
await asyncio.gather(bot1.start(TOKEN), bot2.start(TOKEN2))
asyncio.run(main())
looks like i run into another error
Traceback (most recent call last):
File "c:\Users\SALAH\Desktop\bot\bot-main\bot.py", line 228, in <module>
asyncio.run(main())
File "C:\Users\SALAH\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 190, in run
return runner.run(main)
^^^^^^^^^^^^^^^^
File "C:\Users\SALAH\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 118, in run
return self._loop.run_until_complete(task)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\SALAH\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "c:\Users\SALAH\Desktop\bot\bot-main\bot.py", line 224, in main
await status_task.start()
File "C:\Users\SALAH\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\tasks\__init__.py", line 264, in _loop
raise exc
File "C:\Users\SALAH\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\tasks\__init__.py", line 239, in _loop
await self.coro(*args, **kwargs)
File "c:\Users\SALAH\Desktop\bot\bot-main\bot.py", line 117, in status_task
await bot.change_presence(activity=discord.Game(random.choice(statuses)))
File "C:\Users\SALAH\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 2040, in change_presence
await self.ws.change_presence(activity=activity, status=status_str)
^^^^^^^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'change_presence```
You shouldn’t change presence on_ready though
Also task.start is not a coroutine. Not need to await it
Anyone know how to make a button add other buttons?
# Tried to remove all the fluff code thats not needed for assistance
class ViewFunction(View):
@discord.ui.button(label='Button One')
async def adder_button_callback(self, interaction, button):
# add other buttons
@discord.ui.button(label='Other Button One')
async def otherone_button_callback(self, interaction, button):
# button one stuff
@discord.ui.button(label='Other Button Two')
async def othertwo_button_callback(self, interaction, button):
# button two stuff
class cog_name(commands.Cog):
def __init__(self, CLIENT):
self.CLIENT = CLIENT
@commands.command(hidden=True)
async def command(self, ctx):
VIEW = ViewFunction()
# command stuff
wdym by add other buttons?
like you press the button, message is edited and there are more buttons after that?
...
Yes, so if the button adder button is pressed, the other two buttons are then editted into the message
that chat gpt fault i didnt now how to code a bot
Just add and remove the buttons you want and in the callback pass self
why is your command in your view subclass?
I was just specifying how the command loads the view in-case that was needed, its in the cog, mb
Don't use gpt for library specific coding it's outdated and doesn't really give great responses
I've never used ChatGPT for this project, I have for when I was messing around with Flask, but not this
pls help me !
You should be able to add more buttons by just adding more decorators like you did. Also, you probably shouldn't name a bot object as "client," it's misleading.
I will code once I'm home I'm on my phone rn lol
i dont now what to how to use anny of this discord bot shenanigan
Where are you changing your presence?
idk i used chat gpt to code this i tried merging my ai with the bot
!d discord.ui.View.add_item
add_item(item)```
Adds an item to the view.
This function returns the class instance to allow for fluent-style chaining.
adding something to the view without decorators
Don't use ChatGPT - you should learn some python and OOP before touching discord.py, these libraries aren't beginner friendly.
i now poop
python object oreientation programing

so i made the ai ! buut the bot was a template so i tried merging the two buut ...
i got this thout
import os
import json
import openai
import discord
from discord.ext import commands
# Load configuration from JSON file
with open("config.json", "r") as config_file:
config = json.load(config_file)
# Discord bot setup
intents = discord.Intents.default()
bot = commands.Bot(command_prefix=config["prefix"], intents=intents)
# OpenAI setup
openai.api_key = config["api_key"]
class Chatbot:
@staticmethod
def get_response(prompt):
response = openai.Completion.create(
model="text-davinci-003",
prompt=prompt,
temperature=2,
max_tokens=1024,
top_p=0.3,
frequency_penalty=0.5,
presence_penalty=0
)
return response.choices[0].text.strip()
@bot.event
async def on_ready():
print(f'Logged in as {bot.user.name}')
@bot.command()
async def ohslim(ctx, *, user_input):
prompt = f"User: {user_input}\nSlimy:"
response = Chatbot.get_response(prompt)
await ctx.send(response)
# Run the bot
bot.run(config["token"])
witch works
I made an ai be like: import openai
its unhacable
for some dam reason
I mean, that you didn't make an ai at all. You just used the ready ai with api
no i trained it
But you still used a ready one ¯_(ツ)_/¯
yes
You should really never have to use change_presence unless within a command, or maybe an eval. If you want to have a set presence when your bot is online, set the activity and status kwargs in the constructor of these Classes.
bot = commands.Bot(command_prefix="!", activity=..., status=...)
I'm assuming you were maybe trying to change the presence on_ready, which you shouldn't be making api requests on_ready because Discord has a high chance to completely disconnect you during the READY or GUILD_CREATE events (1006 close code) and there is nothing you can do to prevent it.
^ if you'd still like to change your presence
try asking it something give me the prompt just one
I don't need it
ok
so back to topic
what to add to this ? i have this code that is working to save some sanity ```py
import os
import json
import openai
import discord
from discord.ext import commands
Load configuration from JSON file
with open("config.json", "r") as config_file:
config = json.load(config_file)
Discord bot setup
intents = discord.Intents.default()
bot = commands.Bot(command_prefix=config["prefix"], intents=intents)
OpenAI setup
openai.api_key = config["api_key"]
class Chatbot:
@staticmethod
def get_response(prompt):
response = openai.Completion.create(
model="text-davinci-003",
prompt=prompt,
temperature=2,
max_tokens=1024,
top_p=0.3,
frequency_penalty=0.5,
presence_penalty=0
)
return response.choices[0].text.strip()
@bot.event
async def on_ready():
print(f'Logged in as {bot.user.name}')
@bot.command()
async def ohslim(ctx, *, user_input):
prompt = f"User: {user_input}\nSlimy:"
response = Chatbot.get_response(prompt)
await ctx.send(response)
Run the bot
bot.run(config["token"])
What are you looking to add?
Also, what's the point of having your prefix in a config file?
well basic commands to manage the server also the ai could use commands like ban ... also its just for fun
No point in making a ban command when discord made one for you
I have no clue what you mean
got dam it
a bot that warns people to not swear and bans after warning idk what do people use bots for
The discord client has a built-in automod
so why dopeople make discord bots !
Trxp pls be reasonable man
there's millions of other reasons other than automod lmao
i see
Moderation: Bots can help moderate servers by enforcing rules, muting or banning users who violate guidelines, deleting inappropriate content, and issuing warnings.
Automated Tasks: Bots can automate routine tasks such as giving users roles, managing server announcements, posting scheduled messages, and organizing events.
Information Retrieval: Bots can fetch information from external sources or APIs, provide weather updates, currency conversion, time zones, Wikipedia summaries, and more.
Fun and Entertainment: Bots can offer games, quizzes, trivia, and other interactive activities to engage server members and provide entertainment.
Music: Music bots can play music from various sources, create playlists, and manage music-related commands.
Utilities: Bots can provide utilities such as calculators, language translation, URL shortening, and other tools.
Custom Commands: Bots can be programmed to respond to custom commands with specific actions or messages.
Reaction Roles: Bots can assign roles to users based on their reactions to specific messages. This is often used for assigning game roles, language roles, or interest-based roles.
Server Statistics: Bots can provide server statistics, member counts, and other data to help server administrators monitor server activity.
Reminders: Bots can create reminders for users, helping them remember important dates, events, or tasks.
Economy and RPG: Economy bots simulate an in-server economy where users earn and spend virtual currency. RPG bots offer role-playing game elements within the server.
The thing about making it yourself is that you can create a way better infraction system than that Discord has setup and allows for a more fair but still strict system.
that what i was thinking
This will also never work.
😢
@vital nest I meant that this code will never run sicne you need message intents because you are using message commands.
Also not sure why you are using a class for only one function.
for future onse

sooo
That makes no sense
how whould you do it
!intents
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
Like this ```py
intents = Intents.default()
intents.message_content = True
Not too sure why yours works but I think you updated it then.
could you rewrite the code like a humain would or just add it because i lost my code
Well the json stuff isn't something that I would use but I will send the code on how I would write it whit the current code that's there.
import os
import json
import openai
import discord
from discord import Intents
from discord.ext.commands import Bot, Context
# Load configuration from JSON file
with open("config.json", "r") as config_file:
config = json.load(config_file)
# Discord bot setup
intents = Intents.default()
intents.message_content = True
bot = Bot(command_prefix=config["prefix"], intents=intents)
# OpenAI setup
openai.api_key = config["api_key"]
def get_response(prompt: str) -> None:
return openai.Completion.create(
model="text-davinci-003",
prompt=prompt,
temperature=2,
max_tokens=1024,
top_p=0.3,
frequency_penalty=0.5,
presence_penalty=0
).choices[0].text.strip()
@bot.event
async def on_ready() -> None:
print(f'Logged in as {bot.user.name}')
@bot.command()
async def ohslim(ctx: Context, *, user_input: str) -> None:
prompt = f"User: {user_input}\nSlimy:"
await ctx.send(get_response(prompt))
# Run the bot
bot.run(config["token"])
Scroll up a bit there is an example there.
Here is an explenation providing the example.
a bit, really
Yeah it was onlt 3/4 messges 😅 but it's ok
That's why you shouldn't watch YouTube tutorials
Could be an older video, in previous version intents wasn't required. Your video is about 1/2 years old then
Most are outdated for years
Yeah I'd always filter on "last 6 months" at most.
Mandatory intents argument stuff is 2022 thing
Well you can still just pass 0 and it should work but yeah.
Why is that an issue, can't you update it?
Looks good!
Use linux then lol
Every pc can run linux.
Did you change the boot order?
Did you try to remove the OS drive?
I had a laptop that also was frisky about the os drive, I just wiped it whit another PC and then inserted the empty drive.
But 3.8 is still supported on discord.py tough.
So I don't see it beeing an issue.
That's uhhh, ancient..
Good OS tough
You just leaked your bot's token
Was boutta say
And could you please at least look before posting again since we don't condone any form of nazism here.
on_read() not just the event name.
code?
can i make this bot exute a comand ```py
@bot.command()
async def ohslim(ctx: Context, *, user_input: str) -> None:
prompt = f'...'
answer = "!ohslim "+"User: "+user_input+" Slimmy: "+ get_response(prompt)
print (str(answer))
await ctx.send(answer)
Store joined users in that button view
How I can make the bot reply to a message?
!d discord.Message.reply
await reply(content=None, **kwargs)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A shortcut method to [`abc.Messageable.send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send) to reply to the [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message).
New in version 1.6.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError) or [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError) instead of `InvalidArgument`.
How I can get message?
- how I can make. Command work only in a specific server
Like
if ctx.guild.id == (the guild id)?
you can use the checks system, theres a builtin guild_only decorator for this
https://discordpy.readthedocs.io/en/stable/ext/commands/api.html?highlight=guild_only#discord.ext.commands.guild_only
i would recommend reading this page as well for a full overview on what checks are
https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html#checks
From the send usually
If you store the id, then TextChannel.fetch_message
Yup good idea
Ok
Is that need to await?
!d discord.TextChannel.fetch_message
await fetch_message(id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a single [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message) from the destination.
Typically anything with fetch is awaited because it’s making an API request. get_x and utils.get are not awaited because they simply are getting data from the internal dpy cache.
utils.get is independent to anything client-related and can actually be awaited if it was passed an async iterable
hey gys , i have this part of my embed line that is not working
color=colour.red
how do i make it work ?
class discord.Colour(value)```
Represents a Discord role colour. This class is similar to a (red, green, blue) [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple).
There is an alias for this called Color...
They didn't say in doc what should I put in ()
@guild_only()
nothing
it just a decorator u add-on
so i put this instead of what i have ?
guild_only is not what he wants tho
What
Hey good evening everyone newbie here
he want to make it work for one single guild
Colour.red()
Yup that's it
Like this?
write your custom check
ohh
for this you want a global check https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html#global-checks
class discord.Colour
^
SyntaxError: invalid syntax
Are we supposed to smell the error?
yes
class discord.Colour 💀
It's the definition
You are not supposed to create a class
you import it
from discord
How did you go from color=colour.red to class discord.Colour
i forgot to delete sum in my code
What is this color for?
he copied this
An embed
yes
All you had to do was replace it with color=discord.Colour.red()
working thx !
But why 1 times on 2 the command is not working
like its workingg and when i retry it i have this error
Hello anyone know command just one channel use>
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Python311\Lib\site-packages\discord\app_commands\tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "C:\Python311\Lib\site-packages\discord\app_commands\commands.py", line 853, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Python311\Lib\site-packages\discord\app_commands\commands.py", line 846, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'status' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
@dusk dagger
what
mean command just one channel use
for example i cant here use command
and how do i put .defer()
in my command
@client.tree.command(name="status")
async def status(interaction: discord.Interaction):
embed=discord.Embed(title="**I'm checking the status...**",description="The server is ON :green_square: \n \n To connect , just go on the #𝗛𝗼𝘄-𝘁𝗼-𝗰𝗼𝗻𝗻𝗲𝗰𝘁 channel." , color=discord.Colour.green())
await interaction.response.send_message(embed=embed)
alright
bruh
never used this bot mb
so u dk how to ?
can you help me?
With?
.
for example
i create 2 channel one more general chat no one can use command and one more bot command evryone can use
@dusk dagger
add a check
Are you using slash or prefix commands?
for slash you can just use the integrations tab
know
And hide the commands from said channel
no i know
But how fix no one can use just one channel?
You want only one channel for commands? Sorry, it’s a bit hard to understand your english
i fin
okay perfectly working now thx
await ctx.send(embed=em)
else:
response = await ctx.send("You can't use this command in this channel.")
await asyncio.sleep(5) # Wait for 5 seconds
await response.delete() # Delete the bot's message```
Why did not delete?
idk
Use the delete_after kwarg
It’s much easier imo
where?
await ctx.send("…", delete_after=5)
👍
!d discord.Interaction
class discord.Interaction```
Represents a Discord interaction.
An interaction happens when a user does an action that needs to be notified. Current examples are slash commands and components.
New in version 2.0.
How I can also set continue when the id is None
I tried to put the if condition in the while but the command didn't work when I did that
while True:
try:
server_id = await bot.wait_for("message", check=lambda m: m.channel == ctx.channel and m.author == ctx.author, timeout=300.0)
b_guild = bot.get_guild(int(server_id.content))
break
except asyncio.TimeoutError:
await ctx.send("Time ended")
return
except ValueError:
continue
if b_guild == None:
await ctx.send("you enterd a wrong id please try again")
continue
else:
guild = bot.get_guild(1142023460533571635)
probot = guild.get_member(282859044593598464)
bank_id = 1113386046021963776
bank = guild.get_member(bank_id)
price = count*member_price
tax = price / 0.95 + 1
tax = ceil(int(tax))
await ctx.send("لقد قمت بإدخال ايدي صحيح ✅\n يرجى التحويل لإتمام عملية الشراء")
await ctx.send(f"c {bank_id} {tax}")
try:
await bot.wait_for("message", check= lambda m: m.author == probot and m.channel == ctx.channel and str(price) in m.content and bank.mentioned_in(m))
except asyncio.TimeoutError:
await ctx.send("Time ended")
else:
channel = bot.get_channel(1142023763936940052)
await channel.send(f"$join {server_id.content} {count}")
Like this the command never working
This is not a Modmail thread.
؟
No errors + you can read my first message to know my question what is
Okay, that still doesn't describe what "Like this the command never working" means
There could be so many different meanings to that
Broooo
........
Again, "didn't work when I did that" has many different meanings
Explain what actually hapened
You can see in my message what "that" means
Absolutely nothing
._.
Bro
I want
When the id is None the bot continue and not break the waiting so I tried to set the if condition in the while but that's broked the command(no errors + I don't have handlers)
I said this literally in my first message
Do wanna to see the full code?
No, you already shared the portion of the code with error handlers
Remove the error handlers, send the traceback and send the code with the if statement
Bro the problem is clear
The bot are stays in the loop and don't continue
I just want to know why this happening
Remove your error handlers and if there's a traceback send it...
Ahhhhhhhhhhhhh
There's a high likelyhood if there's a traceback it'll show the issue
You mean the except?
That is an error handler, yes
Bro you can read the except what do
It's time error + value
And both not happening
I'm sure that is the problem cause (read my first messages) and remove except is just waste of time
Alright, if you want to figure it out by yourself, sure
I will remove it just for prove this to you