#discord-bots
1 messages ยท Page 240 of 1
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.
can you fix it?
Make an instance of discord.Intents and pass it to intents kwarg of your Client
can you rewrite it?
No, you should learn to fix your own code
its not my ccode it from chat gpt i just wanted to try something.
We don't help with ChatGPT code here
i tried to fix it
but
still not working
what about now?https://paste.pythondiscord.com/adujejumom
how
Whether message content, attachments, embeds and components will be available in messages which do not meet the following criteria:
โข The message was sent by the client
โข The message was sent in direct messages
โข The message mentions the client
This applies to the following events...
Set this to True on ur instance
Like how it's done here
https://paste.pythondiscord.com/jipoyizire what about now?
Read my messages carefully
Just set intents.message_content to True bruh
done
Now enable it in dev portal
where
you don't pass a role id to utils.get
This is explained in great detail in the tag which you clearly didn't bother reading
And u need to update discord.py
how to update
Ur on like 1.7.3 you should be on 2.2.3
pip install -U discord.py
How can I make a bot detect a message like any message not a certain word
Wdym
So for example a person sends a message I want the bot to detect it and delete it
Like any message
Do you know what an event is?
Yes
Use the message event and delete the message
Oh I see
How would I go about finding the latest command usage in a server? For example I want a bot to solve an equation, and after that I want to do /graph, for example, to graph the equation, do I need to store the command myself or is there some discordpy magic I can use
Make a dict with user ID and whatever values you want to store
And then when someone uses the graph command you get the user ID from that dict
hello zeffo bro!
why not just register a context menu command
@app_commands.context_menu()
async def graph(interaction: discord.Interaction, message: discord.Message) -> None:
# do things with message here
honestly I have no idea what that is
Why message context Menu 
right click on a message in this server and go to "apps"
because you could do /solve_equation and then store the message id in a database of some sort, then when the user uses the graph command on the message you can look up the message id
or just parse the data of the equation from the message content
Okay then it makes sense
I see, thanks 
i only recommend a database because i did something like this before and it's hell ```py
class MyData:
def init(self, a: str, b: int) -> None:
self.a = a
self.b = b
@classmethod
def from_message(cls, message: discord.Message, /) -> MyData:
return cls(
a=message.content.split()[0],
b=message.content.split()[1]
)
stop harassing that poor man
no it doesnt !!
what if the message accidently get deleted
what u will do then @smoky sinew
then u can't use context menu command on it
why not just store the session state in like a dict tho
Need a help real quick , My bot is online and have no problems but "/" isn't working , IDK WHY , all libraries are updated and Code have no problem
Mention me out if anyone can help me
how are you syncing the commands?
and are the commands defined in cogs or directly via the client.tree.command decorator?
Naming a bot variable client 
noob i m
how about naming your bot a
Don't need a professional to name your variables correctly, e.g.
bot = commands.Bot(...) # Makes sense
client = commands.Bot(...) # Doesn't make sense
script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:3
+ & "c:/Users/jashv/OneDrive/Desktop/Discord Bot/.venv/Scripts/python.e ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (c:/Users/jashv/...ipts/python.exe:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException```
I am getting this error when i run the file. idk why
please help
parent_id = category.id if category else None
^^^^^^^^^^^
AttributeError: 'int' object has no attribute 'id'
channel = await interaction.guild.create_text_channel(name=f"coins-request{interaction.user.id}", category=1107249039377977404 , topic=f"Hello")
You cannot get the id attribute of an integer
channel is an integer, and potentially already your category ID
category = interaction.guild.get_channel(1107249039377977404)
?
hey i want to set image from my computer's temp folder
embed.set_image(url=f"./temp/qr{userid}.png")
This is not working
I dont have any url
how to set image
thanks it works
Does anyone know how to add buttons to messages using discord.py
hey my command doesnt work for 19 digits discord id user
@commands.command(name='balance' , aliases=['bal'] , help="Check your balance")
async def balance(ctx , user: discord.Member = None):
if not user:
user = ctx.author
else:
user = user
help
it work for people with 17 or 18 digit id
doesnt work for 19
got it
its due to animated avatar
You don't need that else block btw
does anyone know how i can get the content of a message by message id?
how to get user avatar only png
if user avatar is animated then make png
user = user or ctx.author
?
This will work as well
I'm just saying that doing else: user = user
Changes nothing
ik
No idea
user.avatar gives gif for animated?
what does user.avatar gives
Check the docs 
!d discord.Member.avatar
property avatar```
Equivalent to [`User.avatar`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.avatar "discord.User.avatar")
channel = bot.get_channel(110479386170597966) message = await channel.fetch_message(110704355759056569) await channel.send(message)
this returns:
<Message id=110704557598056569 channel=<TextChannel id=11047938615977966 name='key-list' position=6 nsfw=False news=False category_id=110479337219623063> type=<MessageType.default: 0> author=<Member id=78692517431826432 name='malehs bot' discriminator='2109' bot=True nick=None guild=<Guild id=11047206720815104 name='fuck the world' shard_id=0 chunked=False member_count=5>> flags=<MessageFlags value=0>>
but i want it to return the content of the message
!d discord.Message.content
The actual contents of the message. If Intents.message_content is not enabled this will always be an empty string unless the bot is mentioned or the message is a direct message.
how do i implement that into my code?
How would you change the colour of that side thing?
!d discord.Embed.colour
The colour code of the embed. Aliased to color as well. This can be set during initialisation.
thanks
is this in the embed = Embed(title=item, description=item_info.get(item))?
class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if itโs within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
x == y Checks if two embeds are equal.
New in version 2.0...
aight thanks
Bri ish pepl
wdym colour
is way better
EMBED = Embed(title='`[ - Rules - ]`', description=item_info.get(rules)) whys there a unsolved reference to rules
What
it says unsolved reference to rules
Show the error
async def announce(ctx, *, message = None):
if message == None:
return
else:
EMBED = Embed(title='`[ - Rules - ]`', description=item_info.get('rules'))
await ctx.send(EMBED)
This code isn't working when i type !announce
wait is it because EMBED doesn't = EMBED
embed=EMBED
I got it
avatar = discord.Asset.replace(avatar, format="png")
this works
๐
It' still doesn't work.
@bot.command()
async def announce(ctx, *, message = None):
if message == None:
return
else:
EMBED = Embed(title='`[ - Rules - ]`', description=item_info.get('rules'))
await ctx.send(Embed=EMBED)
bot doesn't do anything when i do !announce
message is None
the same problem i'm facing , "/" commands aint showing for me
oh .
you returned the function and else block is not run
sync your command tree
`@bot.slash_command(description="Sends Reports")
async def report(ctx, username):
for k in range(5):
p = Process(target=profile_attack_process, args=(username, [],))
p.start()
print_status(str(k + 1) + ". Transaction Opened!")
color = discord.Color.blue()
bot_embed = discord.Embed(title=f'{username}',color=color)
bot_embed.add_field(name="โก Started sending reports to...",value=f'```@{username}```' )
await ctx.respond(embeds=[bot_embed])`
no
then
still doesn't work
idk much about dc bots, i need help
this is so annoying.
this describes a way to sync in setup_hook
although it would be better to sync manually
what do you mean by this
show your code again
async def announce(ctx, *, message = None):
if message == None:
return
else:
EMBED = Embed(title='`[ - Rules - ]`', description=item_info.get('rules'))
await ctx.send(Embed=EMBED)
async def announce(ctx, *, message = None):
if message == None:
return
^^^
why do you even need the message param
Lowercase embed
!d discord.ext.commands.Context.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
This works similarly to [`send()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Messageable.send "discord.abc.Messageable.send") for non-interaction contexts.
For interaction based contexts this does one of the following...
the else block will not be executed at all with just !announce
wtf??
Looks like description was None
Why do you even need message if you don't use it
But you use item_info varriabls
bruhhh library is up-to-date
What do you get when you print in console this discord.__version__
ye ik
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'str' object is not callable
it's just .content, you can't call a str object (.content())
is there any bot that can auto remove a role after it was assigned in a specific time delay?
like a discord bot
nothing youd have to program
Why is he playing 2 time audio_search_a
await inter.response.defer(ephemeral=True)
vc = await inter.user.voice.channel.connect()
await inter.guild.change_voice_state(channel=inter.user.voice.channel, self_deaf=True)
check_mark_png = File("pictures\\check_mark_maja.png", filename="check_mark_maja.png")
re_connected.set_thumbnail(url="attachment://check_mark_maja.png")
await inter.edit_original_message(embed=re_connected, file=check_mark_png)
audio_source_a = nextcord.FFmpegPCMAudio("audios\\maja_hello.mp3")
vc.play(audio_source_a)
while vc.is_playing():
await asyncio.sleep(5)
audio_source_b = nextcord.FFmpegPCMAudio("audios\\maja_soundboard_info.mp3")
vc.play(audio_source_b)```
help in #1107318291107692615
There is only a point. Nice help request
can you preview this idk how to fix it
engine = pyttsx3.init()
@bot.command()
async def join(ctx):
if not ctx.author.voice:
await ctx.send("You are not connected to a voice channel.")
return
channel = ctx.author.voice.channel
voice_client = await channel.connect()
text = "Starting code Alpha"
text2 = "What would you like me to do?"
engine.save_to_file(text, 'text1.mp3')
engine.save_to_file(text2, 'text2.mp3')
engine.runAndWait()
audio_source = discord.FFmpegPCMAudio('text1.mp3')
voice_client.play(audio_source)
while voice_client.is_playing():
await time.sleep(1)
audio_source = discord.FFmpegPCMAudio('text2.mp3')
voice_client.play(audio_source)
while voice_client.is_playing():
await time.sleep(1)
await voice_client.disconnect()
Nope sry
oke
I installed the pip install discord.py.
just do pip install discord
Reload?
yep i did
Its discord.py
Really? Oh sry
I've done that a few times.
do pip freeze and send the output
wdym send the output
Output = What is spent
it wont let me send the img.
Copy and Paste it
!dashmpip
When trying to install a package via pip, it's recommended to invoke pip as a module: python -m pip install your_package.
Why would we use python -m pip instead of pip?
Invoking pip as a module ensures you know which pip you're using. This is helpful if you have multiple Python versions. You always know which Python version you're installing packages to.
Note
The exact python command you invoke can vary. It may be python3 or py, ensure it's correct for your system.
Someone can help?
nope doesnt work
you have to run your code with the python command after installing the package with the python command
no... look
hover over it
are you sure it isn't just telling you that the variable is not accessed?
ok, and when you run your script with the python command does it give you an importerror
no module named 'discord'
you ran this with the python command or with the IDE run button
I explicitly said run it with the python command
your environment is misconfigured, the interpreter used by the IDE is different from the one attached to pip
how to make some python code look in the python format on discord
i forgot how to do it
which is if you can tell me?
it said nothing.
why does it thingy underlined/
^
Ah.
you can run pip -V and see which python it's tied to
why ffmpeg not working???
this is the error discord.ext.commands.errors.CommandInvokeError: Command raised an exception: ClientException: ffmpeg was not found.
did you install it and add it to PATH?
or are you passing the executable lcoation?
typo, "prefix" not "perfix"
a..
and your client.run call is indented inside the on_ready event so it'll never run
wdym
did you install ffmpeg
pip install ffmpeg i did that
how do i do it
^
mhm.
@vocal snowwhat code in def on_ready for slash commands ?
yes
use setup_hook instead of on_ready and use bot.tree.sync
send a code
thank you
@vocal snow can you look over it?
can someone help me with this error
I'm using discord py v2
https://pastebin.com/8fmYH94n
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Unknown interaction
You're trying to respond to something non existent
how do I use discord.Member.activities and send the activity that the user is doing
You get a member object
You get its activities attribute
You iterate over it
You send them
i know that
@tree.command(name = "track", description = "?")
async def self(interaction: discord.Interaction, user: discord.Member = None):
if user == None:
user == interaction.user
await interaction.response.send_message(f"Your activity is {user.activities}!")
This doesn't work, just sends ()
and when I dont specify a user it doesnt work
Then you know everything to do it
Why is he playing 2 time audio_search_a
await inter.response.defer(ephemeral=True)
vc = await inter.user.voice.channel.connect()
await inter.guild.change_voice_state(channel=inter.user.voice.channel, self_deaf=True)
check_mark_png = File("pictures\\check_mark_maja.png", filename="check_mark_maja.png")
re_connected.set_thumbnail(url="attachment://check_mark_maja.png")
await inter.edit_original_message(embed=re_connected, file=check_mark_png)
audio_source_a = nextcord.FFmpegPCMAudio("audios\\maja_hello.mp3")
vc.play(audio_source_a)
while vc.is_playing():
await asyncio.sleep(5)
audio_source_b = nextcord.FFmpegPCMAudio("audios\\maja_soundboard_info.mp3")
vc.play(audio_source_b)```
I have a nextcord view where i create 4 button objects in, the button is a separate class not a decorator. How do i stop the view that created the button object from inside of the button class
can someone answer my question
use is None instead of == None, user = interaction.user instead of comparison double ==
it still says my activity is () though, even when I am listening to spotify
do you have the intents enabled
Did you try to enable the presence intent in the discord developer portal
where
idk the rules about links here just google "discord developer portal"
should be the first link
go into the applications tab. select your bot, in the bot tab
Privileged Gateway Intents
WHY MY BOT isnt syncing
`*@bot.tree.commands(name="Sends Reports")
async def report(interaction: discord.Interaction, username):
for k in range(5):
p = Process(target=profile_attack_process, args=(username, [],))
p.start()
print_status(str(k + 1) + ". Transaction Opened!")
color = discord.Color.blue()
bot_embed = discord.Embed(title=f'{username}',color=color)
bot_embed.add_field(name="โก Started sending reports to...",value=f'```@{username}```' )
await interaction.response.send_message(embeds=[bot_embed], ephemeral=True)*`
@bot.event async def on_ready(): print(f"We have logged in as {bot.user} and are serving at {len(bot.guilds)} Guilds!") try: synced = await bot.tree.sync() print(f"Synced {len(synced)} command(s)") except Exception as e: print(e)
try:
await interaction.user.send(embed=qr_code_embed(interaction.user.id , amount , channel_id) , file=discord.File(f"temp/qr{interaction.user.id}.png"))
except:
await interaction.response.send_message("Please enable your DMs to get the QR Code", ephemeral=True)
await channel.delete()
return
discord.errors.InteractionResponded: This interaction has already been responded to before
How straight forward
Did you invite your bot with correct scope?
application.commands scope needs to be enabled
dumb question to ask but since i havent made a discord bot in a while and i heard discord.py is discontinued, what package is good to make a discord bot?
discord.py has resumed development again
!pypi discord.py
yeah i did
hey guys, I have a discord bot that I am attempting to get to run with a python script to do an automessage, which I'd put on a schedule, wondered if I could get assistance with that
i have the script, and the bot in the discord, just trying to put the pieces together at this point
?
im at a bit of a loss when it comes to actually getting it to run
sure
!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 floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
You want a message to be sent at a set time each day?
then not posted if there was a previous one still there, or less than three messages since the last one
the bat I'm running to run that is giving an error (after i put in the bot token and website link) of "no module named config"
Sorry? Not sure I'm understanding
i'm guessing you didn't code this bot
from discord.ext import commands
from discord_slash import SlashCommand
intents = discord.Intents.all()
bot = commands.Bot(command_prefix="!", intents=intents)
slash = SlashCommand(bot, sync_commands=True)
@bot.event
async def on_ready():
print("Successfully logged in as {0.user}".format(bot))
@slash.slash(name="ping", description="Gives you bot's current ping latency.")
async def ping(ctx):
await ctx.send(f"Bot's Current Ping is **{round(bot.latency * 1000)}ms**")
bot.run("bot_token")```
this is my code, it keeps giving me this error:
File "c:\Users\jashv\OneDrive\Desktop\Discord Bot\main.py", line 3, in <module>
from discord_slash import SlashCommand
ModuleNotFoundError: No module named 'discord_slash'```
how to fix?
Don't use it.
what?
The Discord library already has build in slash commands this is an old library.
oh i see
now it's showing me this error
File "c:\Users\jashv\OneDrive\Desktop\Discord Bot\main.py", line 12, in <module>
bot.tree.command(name="ping", description="Gives you bot's current ping latency.")
^^^^^^^^
AttributeError: 'Client' object has no attribute 'tree'```
i updated the code to
import discord
from discord.ext import commands
from discord import app_commands
intents = discord.Intents.all()
bot = discord.Client(command_prefix="!", intents=intents)
@bot.event
async def on_ready():
print("Successfully logged in as {0.user}".format(bot))
bot.tree.command(name="ping", description="Gives you bot's current ping latency.")
async def ping(interaction: discord.Interaction):
await interaction.response.send_message(f"Bot's Current Ping is **{round(bot.latency * 1000)}ms**")
bot.run("token_of_bot")```
why it's showing that? what is the fix?
You need to use a bot instead of a client. You can use a Client but I'd only suggest it if you want a more advanced bot.
Just change discord.Client to commands.Bot
oaky
I was tryna send a discord embed with an added image, but it's just blank.
Of course, no errors.
Could you show what you are doing?
it's booting the bot up but not really showing commands up
i can't use slash command because it's not showing up
That makes sense since you didn't sync them to the guild yet.
how to do that?
!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.
I'd pass a guild where you are developing then it's instant if you leave it empty it takes up to an hour to sync.
@commands.command()
async def rare(self, ctx, *, query: str) -> None:
"""
Send an image test.
"""
await ctx.send(embed=discord.Embed().set_image(url="https://rare-gallery.com/thumbs/669363-George-Washington-quote.jpg"))
but, where to put that code?
under which line in here?
I'd use the setup hook to sync it on launch then change it once it actually goes in production.
... ?
Idk if Discord allows this, just an image.
didn't understood....
!d discord.ext.commands.Bot.setup_hook
await setup_hook()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A coroutine to be called to setup the bot, by default this is blank.
To perform asynchronous setup after the bot is logged in but before it has connected to the Websocket, overwrite this coroutine.
This is only called once, in [`login()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.login "discord.ext.commands.Bot.login"), and will be called before any events are dispatched, making it a better solution than doing such setup in the [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready") event.
Warning
Since this is called *before* the websocket connection is made therefore anything that waits for the websocket will deadlock, this includes things like [`wait_for()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.wait_for "discord.ext.commands.Bot.wait_for") and [`wait_until_ready()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.wait_until_ready "discord.ext.commands.Bot.wait_until_ready")...
Idk either, thanks though I'm gonna investigate.
https://github.com/Rapptz/discord.py/blob/master/examples/app_commands/basic.py here is an example.
so I have to write:
@bot.event
async def login():
await await setup_hook()
I mean no error means Discord does accept it but just isn't formatting it in the channel (educated guess). I'd try to add a title or description or use a embed that does work and then remove some elements.
I provided an example that also has some explanation. Feel free to ask questions as well.
yeah i will try that.
why it's taking so long ๐
Did it finish?
nope
What/ how are you running the code?
wait... it's showing some error
Traceback (most recent call last):
File "C:\Users\jashv\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 842, in _do_call
return await self._callback(interaction, **params) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "c:\Users\jashv\OneDrive\Desktop\Discord Bot\main.py", line 40, in hello
await interaction.response.send_message(f'Hi, {interaction.user.mention}')
File "C:\Users\jashv\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\interactions.py", line 778, in send_message
await adapter.create_interaction_response(
File "C:\Users\jashv\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\webhook\async_.py", line 221, in request
raise HTTPException(response, data)
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In name: Username cannot contain "discord"
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\jashv\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "C:\Users\jashv\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 867, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\jashv\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 860, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'hello' raised an exception: HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In name: Username cannot contain "discord"```
Code?
Btw you can't change names that contain Discord
@client.tree.command()
async def hello(interaction: discord.Interaction):
"""Says hello!"""
await interaction.response.send_message(f'Hi, {interaction.user.mention}')
Why not?
Ask Discord
xD i kept the name Discord Bot. in dev portal
Yep that's ir
should i change it?
Well that's odd they should prevent you from doing that in the Discord portal then not just throw an error.
If you want it to work then yes
okay
It doesn't let you
Or at least for me
How did he invoke the command then? hmmm
hmmm
Could someone help i have my code like this
class Main(commands.Bot):
def __init__(self):
super().__init__(command_prefix='$',intents=discord.Intents.all())
async def blacklist(self,ctx):
await ctx.send('HI')```
and when trying to run the command it wont work
and it says the command does not exist
@client.command(name = "commandName", aliases=["aliase"])
async def commandName(ctx):
await ctx.send("template command")
then im no use because i havent seen or used this method to me it looks like the class of a cog
Not a cog just in a class
class MyClient(discord.Client):
async def setup_hook(self):
print('This is asynchronous!')
client = MyClient()
client.run(TOKEN)```
something like that in there example
you mean like if message.content
no so if i do ping and Ping it still runs the cog
rip me
LOL
LOL
im slow the function is case_insensitive i read it as case_sensitive and set it to false so it never did anything
๐
you don't have a decorator
Oh
!d discord.ext.commands.command
@discord.ext.commands.command(name=..., cls=..., **attrs)```
A decorator that transforms a function into a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") or if called with [`group()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.group "discord.ext.commands.group"), [`Group`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Group "discord.ext.commands.Group").
By default the `help` attribute is received automatically from the docstring of the function and is cleaned up with the use of `inspect.cleandoc`. If the docstring is `bytes`, then it is decoded into [`str`](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.11)") using utf-8 encoding.
All checks added using the [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") & co. decorators are added into the function. There is no way to supply your own checks through this decorator.
This deco he is talking about
I need hep
help*
can anyone assist ,e
me
why is this not working ???
my python version is 3.11
@orchid falcon
@full lily
@vivid mango
No one here gets paid to help. Everyone has a life. Learn to be patient
!dashmpip
When trying to install a package via pip, it's recommended to invoke pip as a module: python -m pip install your_package.
Why would we use python -m pip instead of pip?
Invoking pip as a module ensures you know which pip you're using. This is helpful if you have multiple Python versions. You always know which Python version you're installing packages to.
Note
The exact python command you invoke can vary. It may be python3 or py, ensure it's correct for your system.
On windows the python command is py
Unless you install from MS Store
This is very basic knowledge that you should have before starting a discord bot... Are you new to python?
I would really recommend you learn it first
You won't be able to make a discord bot otherwise, they are quite complex
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
You can find some good courses and books to learn from here for free
I have a command that registers 2 scores and I try to set boundaries of the scores to be 0-30 using discord.app_commands.Range but the command is still executed (RangeError should be raised from what I read in the docs) when the user inputs a number not in that range (like 100)
async def register_match(self, ctx: commands.Context, winner1: discord.Member, winner2: discord.Member, loser1: discord.Member, loser2: discord.Member, winner_score: Range[int, 0, 30], loser_score: Range[int, 0, 30]) -> None:
idk if I did anything wrong when defining the command
@commands.Cog.listener()
async def on_automod_action(self, action):
Reason = action.content
user = action.user_id
print(f"the reporter is {user}")
print(f"content: {Reason}")
print("test")
with open("Warns.json") as w:
Warndata = json.load(w)
if str(user) in Warndata:
Warndata[str(user)].append(Reason)
else:
Warndata[str(user)] = [Reason]
with open("Warns.json", "w") as w:
json.dump(Warndata, w)
can someone review my code and tell the error
The thing I see you doing wrong is using Context instead of Interaction in app command
it was a hybrid command
In app commands it is
async def cmd(self, interaction: discord.Interaction):
await interaction.response.send_message(...)```
Ah okay
Unless discord.py is infinitely stupid there shouldn't be any errors but wrong input must be prevented on client side
I said the command is still executed when input score is like 100
Actually dunno how it is in discord.py
!d discord.app_commands.Range
Oh wait frick it's hybrid command
I keep forgetting these even exist
??????????
!d discord.ext.commands.Range
class discord.ext.commands.Range```
A special converter that can be applied to a parameter to require a numeric or string type to fit within the range provided.
During type checking time this is equivalent to [`typing.Annotated`](https://docs.python.org/3/library/typing.html#typing.Annotated "(in Python v3.11)") so type checkers understand the intent of the code.
Some example ranges...
I have tried both and it didn't show up
@north kiln k do you have error handlers?
but it does warn me when I am not inputting integers
Yeah sure but where da code is
๐ง๐ง๐ง
i'm sending u code in pvt
Heck that's weird
so half of the check works but other half does not
Are you using commands.Range or app_commands.Range?
I have tried both
what kind of bot u r making?
Did you sync?
Switch to disnake and never think about sync again
Errors?
In syncing
I need complete traceback
I'll send u the file
Starting the bot at the top is not a too smart idea
huh?
You start your bot at line 24 and create commands etc. below it, not such a good idea
I still don't know the good practices when configuring a bot
my bot is verified with the proper intents enabled and verified yet i still get this.
what's the simplest way to have a button at the bottom of a text message
on a message command if that's the right term to use
wonder if this would work for the message
async def send_message(self, ctx: Context) -> disnake.Message:
f = io.StringIO("Some text to download")
return await ctx.channel.send(
content="some content",
file=disnake.File(
fp=f,
filename="message_log.txt"
)
)```
i guess that would just have the attachment directly not a button
Depends what you want that button to do and in what context
I don't quite understand how buttons and files are related in your problem
If you mean you want buttons to be below attachments that's not possible to customise
Personally I use this project structure
ext
- cog1.py
- cog2.py
utils
- bot.py (here's bot class)
main.py
config files
And in main.py it's just
from utils.bot import Bot
Bot().run()
and now I want to check if the members passed in this command has reacted to a message the bot sent
is the only way to do that by setting up a listener
Is that message sent by command
That's simple wait_for
r, u = await bot.wait_for("reaction_add", check=lambda r, u: u.id == ctx.author.id and r.message.id == message.id and r.emoji == "๐
ฑ๏ธ")```
Iirc that's how it's done
something I don't understand here is wait_for should return the reaction and users once the check is met
but I want sth like a condition to run more code
kinda lost here
The condition comes after the wait_for or if it was timed out
r is reaction, u is user
so I run my wanted code in check that's weird
You can check the reaction emoji afterwards
For example alter the check condition to allow several emojis and then check using simple if what emoji was selected
the thing is I am passing other users than the author in my command so I thought the way is to use reaction.users() but it is async and cannot be used in the check function
!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 "(in Python v3.11)"). 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 "(in Python v3.11)") 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 "(in Python v3.11)") 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**...
now I think
wait_for is like finding a event where some event requirements are met
but what I want is to run some more code when some event requirements are met (eg. all the users I mentioned have reacted with ๐
ฑ๏ธ on the message sent by the bot after command is executed)
What
as if I put some code after wait_for, it could run even when the condition is not met
so like:
reaction, user = await self.bot.wait_for('reaction_add', timeout=60.0, check=check)
await ctx.send('hiiiii')
will the bot send hiii only after wait_for returns
Yes? Why don't you just test it
I have tried but didn't get my expected result
maybe I did something wrong somewhere else
What's the actual code then
sorry but I am gonna take a break for myself first
This was one of my problems when using check
Then just alter the check condition to interact with reaction.users
required_users = {u.id for u in your_users_list}
r, _ = await bot.wait_for(..., check=lambda r, u: r.message.id == message.id and {user.id async for user in reaction.users} == required_users)
The code will only proceed after all the required users have reacted
!d discord.Reaction.users
async for ... in users(*, limit=None, after=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator "(in Python v3.11)") representing the users that have reacted to the message.
The `after` parameter must represent a member and meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.
Changed in version 2.0: `limit` and `after` parameters are now keyword-only.
Examples
Usage...
Frick asynchronous iterator
Not sure if comprehension works with async expressions but try
Eh wait
I will resolve this now
!d discord.ext.commands.Bot.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 "(in Python v3.11)"). 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 "(in Python v3.11)") 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 "(in Python v3.11)") 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**...
Uh tell me what exactly you are trying to do
hi when i create a bot will i have "active developer" badge?
You get it after you use at least one slash command of your bot
cool, can i create one?
Sure why not
If you only need the badge there are plenty of tutorials on yt, it doesn't require professional help from here
oh ill see an youtube tutorial
uh it is not necessary ill study first
AH There r so much disctraction to my study
Someone executes a command, passes 4 other discord member (might not include the author), the bot sends a message in response to the command, and wait until the 4 members passed have reacted that message with a reaction given by the bot let's say
then the bot gives another response
Idk if I could replace the reaction part with like the 4 members all clicking a button or sth but the bot needs to wait until all of them responded
Error
Yeah for this case you would better reaction add listener
If you want to wait in actual command code until all reactions are completed you can do this (pseudocode)
async def command(...):
future = asyncio.get_event_loop().create_future()
reactions[message.id] = [1, future]
await future
# next code
async def listener(reaction, user):
data = reactions[reaction.message.id]
data[0] += 1
if data[0] >= 4:
data[1].set_result(True)
It's pseudocode and you need to add a few checks but this is the principle
is there a way to call a command from a different cog on let's say a button callback in a different cog
Make a function and call that one from both the callback and the cmd
How can i translate embeds with my bot
How do I check if the user is the user in my command tho
My listener will share variable with my command?
That's just how python works
Or I have to store every execution detail in a database then query the database everytime

!e
def func():
a = 0
def inner_func():
print(a)
inner_func()
func()
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
0
But I don't define the listener in my command function or do I
What does that supposed to mean
I am on my phone now
Traceback (most recent call last):
File "C:\Users\lona\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 842, in _do_call
return await self._callback(interaction, **params) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "E:\files\meow-py\recode.py", line 35, in load
await bot.load_extension(f"cogs.{cog}")
File "C:\Users\lona\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 1013, in load_extension
await self._load_from_module_spec(spec, name)
File "C:\Users\lona\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 952, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.hello' raised an error: TypeError: object NoneType can't be used in 'await' expression```
what's the issue? This is my cogs load command
```py
@bot.tree.command(name="load", description="Loads a cog file")
async def load(interaction: Interaction, cog: str):
await interaction.response.defer()
try:
await bot.load_extension(f"cogs.{cog}")
print(f"Loaded '{cog}.py'")
await interaction.followup.send(f"Loaded `{cog}`", ephemeral=False)
except commands.ExtensionNotFound:
print(f"Extension '{cog}.py' not found")
await interaction.followup.send(f"Extension `{cog}.py` not found.", ephemeral=True)
it means your extension file is the issue, not the command
but usually there's more to that error message, i think you've only copied the bottom half of it
this is my hello.py file
import discord
from discord import app_commands
from discord import ui
from discord.ext import commands
from discord.interactions import Interaction
class hello(commands.Cog):
def __init__(self, bot):
self.bot = bot
@app_commands.command()
async def my_command(self, interaction: Interaction):
await interaction.response.send_message("Hello")
def setup(bot):
bot.add_cog(hello(bot))```
File "C:\Users\lona\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 842, in _do_call
return await self._callback(interaction, **params) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "E:\files\meow-py\recode.py", line 35, in load
await bot.load_extension(f"cogs.{cog}")
File "C:\Users\lona\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 1013, in load_extension
await self._load_from_module_spec(spec, name)
File "C:\Users\lona\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 952, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.hello' raised an error: TypeError: object NoneType can't be used in 'await' expression
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\lona\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "C:\Users\lona\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 867, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\lona\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 860, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'load' raised an exception: ExtensionFailed: Extension 'cogs.hello' raised an error: TypeError: object NoneType can't be used in 'await' expression``` here you go
setup function needs to be a coroutine
async def
is it the @app_commands.command() or
I am sorry I am new to these
or its the class
there might actually be a third traceback that's missing from this too, but regardless follow the migrating guide i linked above for correctly defining your setup() function
import discord
from discord import app_commands
from discord import ui
from discord.ext import commands
from discord.interactions import Interaction
class HelloCog(commands.Cog):
async def __init__(self, bot):
self.bot = bot
@app_commands.command()
async def hello(self, interaction: Interaction):
await interaction.response.send_message("Hello")
def setup(bot):
bot.add_cog(HelloCog(bot))```
this is my current cog file code, its still throwing errors
what is a cog
not __init__, setup needs the async
I see
async def setup(bot):
bot.add_cog(HelloCog(bot))```
like this?
you can see exactly what's missing in the migrating guide i linked
thank you, i didnt notice that
is it possible to sync commands in a cogs file aswell? using await bot.tree.sync()
its a feature of discord.py for defining commands and listeners inside a class, and its usually combined with their extensions mechanism
https://discordpy.readthedocs.io/en/stable/ext/commands/cogs.html
https://discordpy.readthedocs.io/en/stable/ext/commands/extensions.html
Why
sure, you just need access to your bot instance, e.g. using self.bot in your cog
I will try to explain what I want to do with a minimal example
@commands.hybrid_command()
async def register_match(self, ctx: commands.Context, user1: discord.Member, user2: discord.Member, user3: discord.Member, user4: discord.Member):
await ctx.send(f'Hi {user1.mention} {user2.mention} {user3.mention} {user4.mention}, please react with โ
to confirm your registration'
#wait until all 4 of them reacted โ
#run code to insert data into database
but when I define a listener in the same cog, like
@commands.Cog.listener('on_reaction_add'):
async def check_if_all_reacted(reaction: discord.Reaction, user: discord.Member):
pass
it shouldn't have access to user1 to user4 right? So I couldn't check if user1 to 4 has reacted to that message, maybe I could store every execution detail in a database then try to query the database with reaction.message.id to fetch info but I don't want to do that
so I define bot = commands.Bot in the cogs file also?
definitely dont do that
Why not just use wait_for ๐ง
you're already given the bot instance in setup(), which you've passed to your cog as a constructor argument and then assigned it to an attribute of your cog
I can't use wait_for as I couldn't get the users reacted in the check function
reaction.users returns an async generator
You can do something like storing who reacted
can you please give me an example? I don't quite get that
Like
reacted_members = []
def check(reaction, member):
reacted_members.append(member)
return member in reacted_members
Why would you need a database for something like that
(this is a dumb example, but it's just an example of what you can do)
the condition I need is when all 4 members reacted tho
Then check it
so I should be checking the len or sth
Like
reacted_members = []
def check(reaction, member):
reacted_members.append(member)
return all(member in reacted_members for member in (member_1, member_2, member_3, ...))
There are many things you can do depending on what you want
I am just kinda frustrated that I couldn't use the reaction.users as a shortcut and has to do some weird workaround around check not being a coroutine
You don't need it anyway
Declare the list inside the method
Since you can just store them yourself
Wait nvm
Why? It would be redefined when the check gets called again
I thought you were doing something else
does that mean I have to assign a different attribute?
why would you? you're already assigning the bot instance to self.bot
would you prefer giving it a different name
I see, cause I am currently using slash commands, I don't know if its possible to load and sync a slash command using cogs
I'd use the on raw reaction add event and then if count is equal or larger to 4 then check if the 4 valid members have reacted.
oh do you mean just syncing from anywhere else? yes after adding the cog properly the bot will recognize your slash command
https://pastebin.com/raw/CbLutW9j
this is my currently main.py code
but I need to access those 4 members in the listener (not just when it has 4 reactions)
how would I do that
so do i still use @app_commands.command() or
Need to rewrite my shit was treating cogs like extensions when i realised i can just solely use extensions ๐
the cogs need to be loaded before you call sync()
wait, what's extensions?
extensions is what provides Bot.load_extension() and the setup() function, cogs are the commands.Cog class definitions
they're almost always combined together which gets people pretty confused about the difference
I just want 1 command in the file that iโm working on at the moment
I feel like I should be using extensions instead, how can I do that?
you already are
but isnt this just normal cogs?
i see
should I be using @app_commands.command() if I am using Interaction?
yeah
but that doesnt sync so I am not sure
Are you syncโing them globally or locally.. globally can take some time
local youโll need to specify the guild to sync them to
I am using synced = await bot.tree.sync()
so I think thats global
and I am not sure how to specify guilds
iโm on mobile 1 sec
take your time dw
This looks like it has what you need
I was wondering how I could import a slash command from a different file with discord.py. I have the following slash commands that simply greets the user:
@tree.command(name = "hello",
Mainly this bit
I use a setup_hook cause your not meant to call some things in on_ready
Should load extensions and sync the commands in here
#discord-bots message An example
thank you, does that mean I don't need to sync the commands in async def setup but the main.py file?
What are the 4 members?
Yeh i donโt think you need to. In the command file you just have setup then in main you will run the setup hook which will first load the extensions then sync them
You have to load the extensions before syncing otherwise will have no slash commands
the params passed in my command
so have like setup_hook = YourSetupFunction
SetupFunction:
load_extensions()
sync_slash()
Then obv need to make the load and sync functions somewhere in main also
Could you show that command?
here
for the past few months i've had a bot i programmed with discord.py and i gave up motivation for it around november, this is because i can't figure out how to get slash commands in every guild the ...
thank you
I will try making a setup hook, 1s
I guess this works
I'd do it like this```py
self.memb = ["dunno", "some", "members", "etc"]
@commands.Cog.listener("on_raw_reaction_add")
async def check_if_all_reacted(self, payload: discord.RawReactionActionEvent) -> None:
emoji_name = "idk some emoji"
if payload.emoji != emoji_name:
return
message = await payload.member(payload.message_id)
reaction = discord.utils.find(lambda e: e.name == emoji_name, message.reactions)
if reaction.count >= 4:
users = [user async for user in reaction.users() if user in self.memb]
if len(users) == 4:
print("Yeey they all reacted")
umm
what will happen if I executes the command multiple times
the 4 members are different everytime I call the command
def load_extensions():
for foldername in os.listdir(r"./cogs"):
if foldername.endswith(".py"):
bot.load_extension(f"cogs.{foldername[:-3]}")
print(f"Loaded {foldername}")
def sync_slash():
bot.tree = app_commands.build_tree()```
Does this look good?
I'd build it so that it looks at the message id's as well. If message id not in dict then don't execute it.
And then you could also delete the record and remove reactions. Fancy :3
Why is cogs a raw string?
donโt think your syncing it right but along right tracks then you just call both of those in a setup function
What even is build_tree
do you have an exmaple? I dont quite get it ๐ฅฒ
lemme look
The discord.py github has various examples. -> https://github.com/Rapptz/discord.py/blob/master/examples/app_commands/basic.py
Some are a bit dated but it's an example.
^
thank you
so I guess this works for me
confirmation_msg = await ctx.send(f'Hi {user1.mention} {user2.mention} {user3.mention} {user4.mention}, please react with โ
to confirm your registration'
pending_members = set((user1, user2, user3, user4))
reacted_members = set()
def check(reaction: discord.Reaction, user: discord.Member):
if reaction.message != confirmation_msg: #ignore reactions on messages other than the one bot has sent
return False
reacted_members.add(user)
return pending_members.issubset(reacted_members) and str(reaction.emoji) == ':white_check_mark:'
try:
reaction, user = await self.bot.wait_for('reaction_add', timeout=60.0, check=check)
except asyncio.TimeoutError:
await ctx.send('The command has timed out.')
return
await ctx.send('All 4 members have reacted!')
doesnt matter
how
help pls:(
well it is
@client.command
async def gamble():
thx
also reset your token
do you even know basic python syntax
nah

XD
then perhaps you should learn it
pls bro
Looks good to me
like this? @reef gazelle @north kiln
hell
still hell
๐
everything is outside gamble rn
I'm confused
duh

nah bro idk
https://paste.pythondiscord.com/ulocunurev
Bot wakes up when I run , but commands don't work
helpme urgh
How would you make a database and then make commands which can change the value of a specific variable in the database?
Or is there any way to link Google excel to the value of a variable?
Traceback (most recent call last):
File "/home/runner/zag/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 842, in _do_call
return await self._callback(interaction, **params) # type: ignore
File "main.py", line 56, in clear
await interaction.response.send_message(f"deleted {amount} messages")
File "/home/runner/zag/venv/lib/python3.10/site-packages/discord/interactions.py", line 778, in send_message
await adapter.create_interaction_response(
File "/home/runner/zag/venv/lib/python3.10/site-packages/discord/webhook/async_.py", line 219, in request
raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/zag/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/home/runner/zag/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 867, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
File "/home/runner/zag/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 860, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'clear' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction```
@commands.has_permissions(manage_messages=True)
async def clear(interaction: discord.Interaction, amount: int):
await interaction.channel.purge(limit=amount)
await interaction.response.send_message(f"deleted {amount} messages")```
idk how to fix this
unidentified names
Just put " " around each roles
As for random.randint that is not correct since int is for integers
Instead use random.randomchoice(Roles)
can somone help me?
Roles = ["Role 1","Role 2"
roles= random.randomchoice(Roles)
It's not a problem with your command
what is it then?
It's just that bot fails to respond in the time it is required to
so how do i fix it?
how do i fix it then?
weird
Yeah my commands were working fine till earlier today
But when i uploaded the new cog it just kept giving me the error
Tho sometimes the commands work
But mostly they don't work
oh
still doesn't work
@turbid condor
Just random.randomchoice(Roles)
k
not roles[]
like this?
Remove the Roles before random too
Sorry it's random.choice not random.randomchoice
import random ?
:/
can someone help me?
definitely hasnโt
U setting up cogs??
doesn't look like neuralintents is maintained anymore (https://github.com/NeuralNine/neuralintents)
oh
i checked and it still doesn't work
Send the whole code
you need to give us more information than "doesn't work"
i've just copied a yt tutorial xD
show your imports
the full traceback, code, etc
And if any error u getting when running the file
and that command code will not be reachable if it's under client.run
it will execute after the bot logs out
ty
Client.run should be at the end
show your imports aswell\
!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 floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
Can you send a full screenshot from line 1 to where gamble is or paste it in that^
is there any chance to get my code working?
Youโre not importing random
There goes the fish
yeah you need to import random
add a line at the top and import random
In line 3 put import random
not with neuralintents since that package itself doesn't work anymore
k
Move client.run to the last line also
mhhm okay is are there any other packages to train a chat ai?
And copy the client.run to the end of your code
lots, you can ask in #data-science-and-ml or just search online
Doesn't matter
i use client
Let him do what he's comfortable with
yeh itโs personal pref
ty :)
accurate variable naming does matter
especially when someone else is reading the code
When we know what the variable is is there still a need to change it?
yes
Am dead
if weโre being picky iโd change role to selected_role for readability ahaha
cause got Roles then role
What do about the client.run part
client.run should be the very last thing that gets called
Btw can u give me the pistol u holding??
You reckon u can handle it ?
Almost sent hasbulla to the shadow realm with the kickback
Welp I'll probably fine just need to be careful not getting my finger prints on it
That's a desert eagle I'd say it has good recoil but nothing too much if u can handle g3

did I do something wrong ?
does anyone know this error? or is it a discord thing
The same 404?
What's the problem
yes
It's running
You took too long to respond to the interaction
wdym?
I heard something like defer it
I mean exactly what I said
What does that mean?
The same thing i said
whats the command in discord
!d discord.InteractionResponse.defer
await defer(*, ephemeral=False, thinking=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Defers the interaction response.
This is typically used when the interaction is acknowledged and a secondary action will be done later.
This is only supported with the following interaction types...
=gamble @molten panther
Can this help with the error?
Yes, you'd get some extra time to respond to the interaction
Without using it, you need to respond within 3 seconds
!d discord.ext.commands.Context.defer
await defer(*, ephemeral=False)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Defers the interaction based contexts.
This is typically used when the interaction is acknowledged and a secondary action will be done later.
If this isnโt an interaction based context then it does nothing.
Probably
Ok thx
Isn't that obvious
nah bro I'm a noob
pls explain
The error already did, the user argument is missing
U not tagging a member when using command
How do I tag the person who is typing that command
bc i don't want to tag myself
U have to tag the person on which u want to run the command
ctx.author.mention
oh wait
Can I make a button to press instead of a command in discord?
!discord.ui.buttons
where do you want the button to be?
in a text message on my server
U should first learn how to fix the error in your command
ok, and do you know how to use classes?
Then move to the buttons
no sadly
you'll need to know those to use rich ui components like buttons
elaborate
https://github.com/Rapptz/discord.py/blob/master/examples/views/persistent.py you can see an example of a persistent view with buttons like the one you want here
k
you need to know classes to do what you want to do
@vocal snow how to make select menus ?
Please add =None (ctx, user : discord.Member=None)
This means that when you do not specify the user it will make it None
do you know python?
It is recommended you learn python first before hopping to discordpy
pls bro
Is this from chatgpt
Watched a video about buttons on discord and than i mixed everything
How to fix this?
can someone help?
@bot.command()
@commands.has_permissions(ban_Members=True)
async def unban(ctx, user_id: int, *, reason=None):
try:
user = await bot.fetch_user(user_id)
await ctx.guild.unban(user, reason=reason)
embed = discord.Embed(title="Unban", description=f"{user.name} ({user.id}) has been unbanned.", color=0x00ff00)
await ctx.send(embed=embed)
except discord.NotFound:
embed = discord.Embed(title="Error", description=f"User with ID {user_id} not found.", color=0xff0000)
await ctx.send(embed=embed)
except discord.Forbidden:
embed = discord.Embed(title="Error", description="I do not have permission to unban users.", color=0xff0000)
await ctx.send(embed=embed)
except Exception as e:
embed = discord.Embed(title="Error", description=str(e), color=0xff0000)
await ctx.send(embed=embed)
@discord.ext.commands.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member has all of the permissions necessary.
Note that this check operates on the current channel permissions, not the guild wide permissions.
The permissions passed in must be exactly like the properties shown under [`discord.Permissions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions "discord.Permissions").
This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingPermissions "discord.ext.commands.MissingPermissions") that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Ctrl + click the commands and see where it leads you. If that's your own code, rename it to something else, because you redefined what you were not supposed to
How come error isnt being handled in the extension here?
Do I need to do it in on_command_error ?
Changed it to an error on its own but the error is still printed to console
I tried returning the error but still prints
Fixed
Was handling this globally
async def on_command_error(ctx, error):
if isinstance(error, commands.CommandNotFound):
raise error
Meant to be return
are you using slashcommands by chance or no
then just configure what channel it can be ran in from the integrations tab in server settings
Not getting any embed if its a different response any ideas?
can you please copy paste this code into a codeblock so i can help you?
from datetime import datetime
import discord
from discord.ext import commands
import requests
@commands.command(aliases=["isitdown"])
async def check(ctx, website):
response = requests.get(f"https://{website}", timeout=5)
code = response.status_code
print(code)
try:
if code == 200:
embed = discord.Embed(title="โ
Success 200", description=f"{website} appears to be up.", color=0x11d61e)
embed.set_footer(text=f"{datetime.utcnow().strftime('%d-%m-%Y at %H:%M')}")
await ctx.send(embed=embed)
except Exception as e:
embed = discord.Embed(title="๐ Down", description=f"{website} appears to be down. Code: {code}", color=0xde1032)
embed.set_footer(text=f"{datetime.utcnow().strftime('%d-%m-%Y at %H:%M')}")
await ctx.send(embed=embed)
@check.error
async def check_error(ctx, error):
if isinstance(error, commands.BadArgument):
embed = discord.Embed(title="โ ๏ธ Whoops..", description=f"Enter a valid URL!", color=0xe0cf48)
embed.set_footer(text=f"{datetime.utcnow().strftime('%d-%m-%Y at %H:%M')}")
await ctx.send(embed=embed, delete_after=5)
await ctx.message.delete(delay=5)
elif isinstance(error, commands.MissingRequiredArgument):
embed = discord.Embed(title="โ ๏ธ Whoops..", description=f"Enter a URL!", color=0xe0cf48)
embed.set_footer(text=f"{datetime.utcnow().strftime('%d-%m-%Y at %H:%M')}")
await ctx.send(embed=embed, delete_after=5)
await ctx.message.delete(delay=5)
async def setup(bot):
bot.add_command(check)
If I put like a random address in get nothing presuming cause it doesnt send a response at all
@commands.command(aliases=["isitdown"])
async def check(ctx, website):
response = requests.get(f"https://{website}", timeout=5)
code = response.status_code
print(code)
if code == 200:
embed = discord.Embed(title="โ
Success 200", description=f"{website} appears to be up.", color=0x11d61e)
else:
embed = discord.Embed(title="๐ Down", description=f"{website} appears to be down. Code: {code}", color=0xde1032)
embed.set_footer(text=f"{datetime.utcnow().strftime('%d-%m-%Y at %H:%M')}")
await ctx.send(embed=embed)
```try something like this, you were sending the appears to be down embed on Exception which wouldn't be hit because it wouldn't be raising an exception
Working for 404
should work in general :)
Will try it on a random URL that wont exist
If you put a random URL nothing happens but dont think thats really worth handling
yeah tbh lmao
Thank you ๐
np man
i edited the codeblock again, i didn't realize you doubled setting the footer to the same thing, check it out
Thanks just seen I like that didn't know could be done that way will change my other embeds ๐
niceee
np
why are you splitting the user to receive the username? calling user.name returns just the name ๐
how to make "!test" it will send an embed??????
make a command
how
U tried making any command before?
nope
Then u will need check at the very least on how to get started
- Before even attempting to create a discord bot, please learn python (
?tag lp) - To install discord.py, please run
python3 -m pip install discord.py(linux), orpy -3 - m pip install discord.py(windows)
... a. If you wish to use voice functionality, please usediscord.py[voice]instead ofdiscord.py - Take a look at https://github.com/Rapptz/discord.py/blob/master/examples/basic_bot.py Mess around.
- When you start making your bot, use the commands ext: https://discordpy.readthedocs.io/en/latest/ext/commands/commands.html
- The library documentation is available at https://discordpy.readthedocs.org/en/latest/
If you are migrating from the old version of this library (0.16.XX; async) to version 1.XX.XX please follow the migrating guide http://discordpy.readthedocs.io/en/latest/migrating.html
This will help u getting in getting started
from discord.ext import commands, tasks
spam_id = os.environ['spam_id']
user_token = os.environ['user_token']
intervals = [2, 3.2]
@tasks.loop(seconds=random.choice(intervals))
async def spam():
#for i in intervals:
# if i < 1.9:
# print("โ You can't put less than 1.9s! Your interval was changed temporally to 2s.")
# intervals = [5]
channel = client.get_channel(int(spam_id))
await channel.send(''.join(
random.sample(['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'], 7) *
5))
@spam.before_loop
async def before_spam():
await client.wait_until_ready()
spam.start()
@client.event
async def on_ready():
print(f'Logged into account: {client.user.name}')
keep_alive.keep_alive()
client.run(f"{user_token}")```
task has to run in an async function i think
inside async?
run the task in on_ready
how?
import re, os, asyncio, random, string, keep_alive
from discord.ext import commands, tasks
spam_id = os.environ['spam_id']
user_token = os.environ['user_token']
intervals = [2, 3.2]
@tasks.loop(seconds=random.choice(intervals))
async def spam():
#for i in intervals:
# if i < 1.9:
# print("โ You can't put less than 1.9s! Your interval was changed temporally to 2s.")
# intervals = [5]
channel = client.get_channel(int(spam_id))
await channel.send(''.join(
random.sample(['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'], 7) *
5))
@spam.before_loop
async def before_spam():
await client.wait_until_ready()
@client.event
async def on_ready():
print(f'Logged into account: {client.user.name}')
await spam.start()
keep_alive.keep_alive()
client.run(f"{user_token}")



