#discord-bots
1 messages ยท Page 344 of 1
coroutine you gotta await it
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/api.html#discord.Client.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) 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/api.html#discord.Client.wait_for) and [`wait_until_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_until_ready)...
ya did but its not starting
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).
ya i started
just it had tokken so didnt put here
import discord
import asyncio
from keep_alive import keep_alive
from discord.ext import commands
intents = discord.Intents.all()
activity = discord.Activity(name='Knife HQ pre alpha 0.0.1 \n prefix = pls',
type=discord.ActivityType.watching)
bot = commands.Bot(
command_prefix=["pls ", "Pls ", "PLS ", "PLs ", "PlS ", "pLs ", "pLS "],
case_insensitive=True,
activity=activity,
intents=intents)
async def main():
async with bot:
await bot.load_extension('cogs.auto_task')
await bot.load_extension('cogs.Battle')
keep_alive()
bot.run(
'tokken'
)
asyncio.run(main())```
no error coming but bot isnt coming on
it was coming before setting aysnc
use bot.start instead
also what is this keep_alive function
it seems to be blocking
ah, you're probably on replit trying to host your bot?
still nothing
yes
ok it was not awaited
start
wow
Dear Community,
I need your help! I want to ensure that only the ticket owner can click the buttons in my Discord server. Can someone explain to me how I can achieve this?
Thank you in advance for your support! ```py
class frageticket(discord.ui.View):
def init(self):
super().init(timeout=None)
async def check_user_permissions(self, interaction):
ticket_opener_id = None
channel = interaction.channel
if channel.topic and channel.topic.startswith("Ticket opened by"):
ticket_opener_id_str = channel.topic.split(":")[-1].strip()
if ticket_opener_id_str.isdigit():
ticket_opener_id = int(ticket_opener_id_str)
return interaction.user.id == ticket_opener_id
@discord.ui.button(label="Yes, I still have questions", style=discord.ButtonStyle.primary, row=1, emoji="๐๏ธ", custom_id="frage_ticket")
async def ask_back(self, button, interaction):
has_permissions = await self.check_user_permissions(interaction)
if not has_permissions:
await interaction.response.send_message("Du bist nicht berechtigt, dieses Ticket zu bearbeiten.", ephemeral=True)
return
embed = discord.Embed(
title="Weitere Fragen stellen",
description=f"Alles klar {interaction.user.mention}, du kannst jetzt deine Fragen stellen.",
color=discord.Color.green()
)
await interaction.response.send_message(embed=embed)
@discord.ui.button(label="Nein, alles erledigt", style=discord.ButtonStyle.green, row=1, emoji="โ
", custom_id="no_ticket")
async def no_back(self, button, interaction):
has_permissions = await self.check_user_permissions(interaction)
if not has_permissions:
await interaction.response.send_message("Du bist nicht berechtigt, dieses Ticket zu bearbeiten.", ephemeral=True)
return
server_id = interaction.guild.id
await asyncio.sleep(1)
await interaction.channel.delete()``` but he says I am not the owner of the ticket, I am the owner of the ticket
!d discord.ui.View.interaction_check
await interaction_check(interaction, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A callback that is called when an interaction happens within the view that checks whether the view should process item callbacks for the interaction.
This is useful to override if, for example, you want to ensure that the interaction author is a given user.
The default implementation of this returns `True`.
Note
If an exception occurs within the body then the check is considered a failure and [`on_error()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View.on_error) is called.
The given user can't be found in the list
Can you please send me the code as an actual message (not image)?
@tree.command(name="info", description="Shows user info", guild=discord.Object(id=1130871795248005205))
async def info(ctx, user: discord.User=None):
if user is None:
user = ctx.user
date_format = "%a, %d %b %Y %I:%M %p"
user_id_str = str(user.id)
user_points = points.get(user_id_str, 0)
name = user.display_name
pfp = user.display_avatar
embed = discord.Embed(
title='User info',
color=discord.Colour.pink(),
)
members = sorted(ctx.guild.members, key=lambda m: m.joined_at)
embed.add_field(name="Join position", value=str(members.index(user)+1))
embed.add_field(name="Joined", value=user.joined_at.strftime(date_format))
embed.add_field(name="Registered", value=user.created_at.strftime(date_format))
if len(user.roles) > 1:
role_string = ' '.join([r.mention for r in user.roles][1:])
embed.add_field(name="Roles [{}]".format(len(user.roles)-1), value=role_string, inline=False)
perm_string = ', '.join([str(p[0]).replace("_", " ").title() for p in user.guild_permissions if p[1]])
embed.add_field(name="Guild permissions", value=perm_string, inline=False)
embed.set_footer(text='ID: ' + str(user.id))
embed.set_author(name=f'{name}', url=None, icon_url=f'{pfp}')
await ctx.response.send_message(embed=embed, delete_after=120)
Thanks!
@tree.command(name="info", description="Shows user info", guild=discord.Object(id=1130871795248005205))
async def info(ctx, user: discord.User=None):
if user is None:
user = ctx.user
date_format = "%a, %d %b %Y %I:%M %p"
user_id_str = str(user.id)
user_points = points.get(user_id_str, 0)
name = user.display_name
pfp = user.display_avatar
embed = discord.Embed(
title='User info',
color=discord.Colour.pink(),
)
members = sorted(ctx.guild.members, key=lambda m: m.joined_at)
embed.add_field(name="Join position", value=str(members.index(user)+1))
embed.add_field(name="Joined", value=user.joined_at.strftime(date_format))
embed.add_field(name="Registered", value=user.created_at.strftime(date_format))
if len(user.roles) > 1:
role_string = ' '.join([r.mention for r in user.roles][1:])
embed.add_field(name="Roles [{}]".format(len(user.roles)-1), value=role_string, inline=False)
perm_string = ', '.join([str(p[0]).replace("_", " ").title() for p in user.guild_permissions if p[1]])
embed.add_field(name="Guild permissions", value=perm_string, inline=False)
embed.set_footer(text='ID: ' + str(user.id))
embed.set_author(name=f'{name}', url=None, icon_url=f'{pfp}')
await ctx.response.send_message(embed=embed, delete_after=120)
@frosty roost It might be because of the Members intent
Go to the developer portal and try allow all of this
Then, when initializing your Discord bot, add the parameter intents=discord.Intents.all()
Okay I will try that cuz I've already enabled all of those
Also try this
...
if user in ctx.guild.members:
members = sorted(ctx.guild.members, key=lambda m: m.joined_at)
join_position = members.index(user) + 1
embed.add_field(name="Join position", value=str(join_position))
else:
print("Member not found in the guild's member list.")
And let me know if the error message appears in the console.
Correct!
did this from my memory haha
I don't think showing the member join position thing is important at all
Yeah intents.all did not work
But tbh yeah I don rly need join position XD
Ty very much for the help tho
You're welcome!
Im trying to set it so only people iwth specific permission can use this command
@tree.command(name="empress", description="empress", guild=discord.Object(id=1130871795248005205), default_member_permissions=(discord.Permissions(CreateEvents=True)))
async def empress(interaction):
await interaction.response.send_message("ttps://media.tenor.com/VR9uQrFOTmsAAAAM/gavel-order-in-court.gi", delete_after=10)
This is the error i get
What are valid permisison names for the permissions?
Are you using discord.py or pycord?
just python
So create events is not a permission I can use for this?
So from what I've seen is you can try to put @app_commands.checks.has_permissions(administrator=True) above @tree.command ...
(for example)
you can also try
if not interaction.user.guild_permissions.administrator:
# do something if the user is not an admin
and run this check before the actual command does anything
Okay ty but what if i dont want it limited to administrator permissions
Thank ya
https://paste.pythondiscord.com/KDAA can anyone fix?
the generate-... commands have the same code
manage_events
@supple locust @north kiln
https://paste.pythondiscord.com/WEGA
what can I say, these discord.py mfs are experts.
Bro is writing illegal code ๐ญ
I hate black hats / skiddies (writing illegal code) ๐
!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.
https://paste.pythondiscord.com/HMNQ
Hello, my discord bot keeps sending this every time I run it.
server leave server: `````` owner: ```None```
2 times
Now in my paste code, there is no code to do this every time it runs. It only should send the message if someone removes the bot from their server. Please help me
Do note that we will not help with projects that break rule 5 of the server.
I feel like this is basic stuff but I'm running into an issue with my code. The bot sends the messages but does not put the user in timeout and there is no error appearing. I'm new to all of this so sorry in advance!
Discord has a feature called automod that handles this for you! You can set up a list of banned words in the server settings.
Anyway, the code you show should give you errors. I would worry if it does not, that may be a sign that you haven't set up logging, and no errors are coming through to your console. The error would be because Member.timed_out_until is an attribute which tells how long until the member's timeout expires. You're confusing with Member.timeout()
I'll look into the automod. Thanks!
What's the problem?
To answer why this doesn't work, Member.time_out_until is an attribute of the Member class. The function you're wanting, or method, is Member.timeout()
Take a look at the docs, you just got two attributes of the class confused
Nothing, just wanted to show you the end result.
Do you really need the time.sleep calls?
Congrats on getting it working!
You definitely don't need it after hostDm because it's awaited
Yeah, it seems the problem was that the bot cannot create a dm and send a message in light speed.
or at the same moment.
dont use time.sleep() in a discord bot
you probably don't need the second one though
use await asyncio.sleep() instead
Alright, is there a reason to not use the built-in time library?
Imagine that you're coding a Discord bot and every time somebody uses a command, you need to get some information from a database. But there's a catch: the database servers are acting up today and take a whole 10 seconds to respond. If you do not use asynchronous methods, your whole bot will stop running until it gets a response from the database. How do you fix this? Asynchronous programming.
What is asynchronous programming?
An asynchronous program utilises the async and await keywords. An asynchronous program pauses what it's doing and does something else whilst it waits for some third-party service to complete whatever it's supposed to do. Any code within an async context manager or function marked with the await keyword indicates to Python, that whilst this operation is being completed, it can do something else. For example:
import discord
# Bunch of bot code
async def ping(ctx):
await ctx.send("Pong!")
What does the term "blocking" mean?
A blocking operation is wherever you do something without awaiting it. This tells Python that this step must be completed before it can do anything else. Common examples of blocking operations, as simple as they may seem, include: outputting text, adding two numbers and appending an item onto a list. Most common Python libraries have an asynchronous version available to use in asynchronous contexts.
async libraries
- The standard async library -
asyncio - Asynchronous web requests -
aiohttp - Talking to PostgreSQL asynchronously -
asyncpg - MongoDB interactions asynchronously -
motor - Check out this list for even more!
https://paste.pythondiscord.com/HMNQ
Hello, my discord bot keeps sending this every time I run it.
server leave server: `````` owner: ```None```
2 times
Now in my paste code, there is no code to do this every time it runs. It only should send the message if someone removes the bot from their server. Please help me
Hi, I want to do a command for my bot, which will be returning a bot response, but visible only for me as a user, who triggered. For the other users will be hidden. What is important - the replay have to be on a channel, not DM
I think this can be done with a bot interaction, with hidden being True
Hmm, can you send me some info about it? Like, i was browsing everywhere, even via chatgpt and i cannot find anything hah
!d discord.InteractionResponse.send_message
await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False, silent=False, delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by sending a message.
Set ephemeral to True
Thanks a lot!
Same for discord.ext.commands.Context (hybrid commands)- though there it only works if it's an interaction
@vale wing Sorry for the ping. I got a question, should I run docker as root or not?
I wouldn't
Heya!! ๐
Im looking how to get a followup question to the user off a discord.py interaction (slash command)
So in short:
- user does /command
- bot sends embed
- I then want the user to select something from the above embed. (For now I was thinking a number as they are listed, but another way to do it better is appreciated)
Iโve looked at followup and interactionresponse, but im not quite sure how to implement either.
what's the question?
How to implement this?
you can use a select menu (informally known as dropdowns)
Mm I don't run anything as root
!d discord.ui.Select
class discord.ui.Select(*, custom_id=..., placeholder=None, min_values=1, max_values=1, options=..., disabled=False, row=None)```
Represents a UI select menu with a list of custom options. This is represented to the user as a dropdown menu.
New in version 2.0.
Okay thanks.
Ill just send the embed and the dropdown in the appcommand?
yep. just pass embed and view
https://github.com/Rapptz/discord.py/blob/master/examples/views/dropdown.py
you can also use the @discord.ui.select deco within a view itself
!d discord.ui.select
@discord.ui.select(*, cls=discord.ui.select.Select[typing.Any], options=..., channel_types=..., placeholder=None, custom_id=..., min_values=1, max_values=1, disabled=False, default_values=..., row=None)```
A decorator that attaches a select menu to a component.
The function being decorated should have three parameters, `self` representing the [`discord.ui.View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View), the [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction) you receive and the chosen select class.
To obtain the selected values inside the callback, you can use the `values` attribute of the chosen class in the callback. The list of values will depend on the type of select menu used. View the table below for more information.
I need help
I can't for the life of me figure out how bot voice stuff works
I'm using discord.py with discord.client
What do you want to do?
at this point, simply just make the bot join a voice channel
!d discord.VoiceClient
class discord.VoiceClient```
Represents a Discord voice connection.
You do not create these, you typically get them from e.g. [`VoiceChannel.connect()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.VoiceChannel.connect).
Warning
In order to use PCM based AudioSources, you must have the opus library installed on your system and loaded through [`opus.load_opus()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.opus.load_opus). Otherwise, your AudioSources must be opus encoded (e.g. using [`FFmpegOpusAudio`](https://discordpy.readthedocs.io/en/latest/api.html#discord.FFmpegOpusAudio)) or the library will not be able to transmit audio.
I tried reading through that, but I didn't understand what I needed to do
If you want the bot to join the same voice channel as you are in, you could do something like
if message.author.voice:
channel = message.author.voice.channel
await channel.connect()
else:
await message.channel.send('You need to be in a voice channel to use this command.')```
I don't really know what exactly you are trying to do, so you better figure it out first
But here is an example. Play around with it 
ok so, now it's complaining that I don't have PyNaCl despite the fact that I do in fact have it installed
!pypi pynacl
yup
You don't need that to connect to a voice channel
Traceback (most recent call last):
File "/Users/[USER]/Repos/discord-bots/python-bots/squirrelbot.py/bot-env/lib/python3.11/site-packages/discord/client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "/Users/[USER]/Repos/discord-bots/python-bots/squirrelbot.py/main.py", line 252, in on_message
await channel.connect()
File "/Users/[USER]/Repos/discord-bots/python-bots/squirrelbot.py/bot-env/lib/python3.11/site-packages/discord/abc.py", line 1898, in connect
voice: T = cls(client, self)
^^^^^^^^^^^^^^^^^
File "/Users/[USER]/Repos/discord-bots/python-bots/squirrelbot.py/bot-env/lib/python3.11/site-packages/discord/voice_client.py", line 238, in __init__
raise RuntimeError("PyNaCl library needed in order to use voice")
RuntimeError: PyNaCl library needed in order to use voice
it says I need it
Can you post the actual code?
if message.content == 'hey squirrelbot! join vc!':
if message.author.voice:
channel = message.author.voice.channel
await channel.connect()
else:
await message.channel.send('You need to be in a voice channel to use this command.', reference=message)
Is that the entire code?
for joining voice, yes
I need the full code
of the bot?
have you install discord.py with voice? pip install discord.py[voice]
!pastebin
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.
https://paste.pythondiscord.com/52SA
Any1 available to help me with this help menu? For some reason its not organizing the commands into categories and its displaying them all on 1 page .-.
For reference im hosting it on railway.app from github
Pls dm me if u can because i dont want to miss any feedback in case im offline!
this command does not work for me
all good, found python3 -m pip install -U discord.py from the discord.py docs
you need to include [voice]
yeah
did you activate the venv when you were installing the lib
doing this implies you're not using venv
or did not activate it
do pip -V and show me
now pip freeze
then you didnt install it to your venv there
do pip install discord.py[voice] again
probably
this is in linux right
macos
oh nvm macos
do pip install -U "discord.py[voice]"
can you connect now?
yeah
Hello.
Can anyone please tell me how to make all interaction commands not available via bot DM? I want my commands to only be used in servers
!d discord.ext.commands.dm_only
@discord.ext.commands.dm_only()```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check) that indicates this command must only be used in a DM context. Only private messages are allowed when using the command.
This check raises a special exception, [`PrivateMessageOnly`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.PrivateMessageOnly) that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure).
New in version 1.1.
I think they want guild_only actually
!d discord.app_commands.guild_only
@discord.app_commands.guild_only(func=None)```
A decorator that indicates this command can only be used in a guild context.
This is **not** implemented as a [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check), and is instead verified by Discord server side. Therefore, there is no error handler called when a command is used within a private message.
This decorator can be called with or without parentheses.
Due to a Discord limitation, this decorator does nothing in subcommands and is ignored.
Examples...
!django
#bot-commands for that
Hello ! I'm doing a ticket system with my discord bot. Here is my code : https://paste.pythondiscord.com/PY4A
My code works but I want to create a "Close ticket" system. Please help me !
I mean you may attach a button to the message sent in the new channel
You should describe how the "system" is going to look like, what the user is expected to do
Add a close ticket button to the embed on the start of ticket and make it so when user clicks it once it drops a confirm message
Id do it that way atleast
is there anyone using some kind of ocr to extract item names & prices from receipts?
hello guys I have problem with my bot can anyone help me
No, as you haven't asked any questions
how can I make my bot use reaction in .py
what does that mean
like this
!d discord.Message.add_reaction
await add_reaction(emoji, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Adds a reaction to the message.
The emoji may be a unicode emoji or a custom guild [`Emoji`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Emoji).
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history) to do this. If nobody else has reacted to the message using this emoji, [`add_reactions`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.add_reactions) is required.
Changed in version 2.0: `emoji` parameter is now positional-only.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError) instead of `InvalidArgument`.
thanks
how to make my bot send a message once every a fixated time?
in a specific channel?
yes
!d discord.ext.tasks.loop
@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True, name=None)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop).
you can use this
Boo ๐ป
ooh, thanks
oh by any chance is it possible to inject the code into my alt account instead of my bot account ? or it would need a whole different code?
Cool avatar and profile
we can't help with self bots as they break discord tos
oh I didn't knew that, alright tysm
Hello ! I'm doing a ticket system with my discord bot. Here is my code : https://paste.pythondiscord.com/SOIQ
My code works but when a member creates a ticket, i want the name of the name of ticket with the reason. Exemple : if clyde opens a ticket by clicking "question" section, the name will be "ticket-clyde-question". And I want to add a message with the reason too. Please help me !
I don't receive any direct messages and the channel isn't deleted ```py
@discord.ui.button(label="Close", style=discord.ButtonStyle.blurple, emoji="๐", row=1, custom_id="close_ticket")
async def close_ticket(self, button, interaction):
server_id = interaction.guild.id
team_role_id = await db.get_teamrole(interaction.guild.id)
if team_role_id in [role.id for role in interaction.user.roles]:
server_name = await db.get_server_name(server_id)
if server_name:
channel_id = await db.get_log_channel(server_id)
if channel_id:
channel = await db.get_log_channel(interaction.guild.id)
if channel:
ticket_opener = await db.get_ticket_opener(channel_id)
embed = discord.Embed(
title="Close Ticket",
description="Deleting Ticket in less than `5 Seconds`... โณ\n\n"
"_If not, you can do it manually!_",
color=discord.Color.dark_red()
)
await interaction.response.edit_message(view=self)
await interaction.followup.send(embed=embed)
transcript = await chat_exporter.export(interaction.channel)
if transcript is None:
return
transcript_file = discord.File(
io.BytesIO(transcript.encode()),
filename=f"transcript-{interaction.channel.name}.html",
)
log_channel_id = await db.get_log_channel(server_id)
log_channel = interaction.client.get_channel(log_channel_id)
message = await log_channel.send(file=transcript_file)
link = await chat_exporter.link(message)
userembed = discord.Embed(
title="Your Ticket has been Closed",
description=f"Your ticket at {server_name} has been closed.\n"
f"```{interaction.channel.name}```\n"
f"You can find the transcript [here]({link}).",
color=discord.Color.blue(),
)
print("1")
if ticket_opener:
user = interaction.guild.get_member(ticket_opener)
if user:
try:
await interaction.user.send(embed=userembed)
await asyncio.sleep(5)
print("Deleting channel...")
await interaction.channel.delete()
except discord.errors.Forbidden:
print("Failed to send message to user (Forbidden)")
except discord.errors.HTTPException:
print("Failed to send message to user (HTTPException)")
else:
await interaction.response.send_message("The ticket channel was not found.", ephemeral=True)
else:
await interaction.response.send_message("The channel ID was not found in the database.", ephemeral=True)
else:
await interaction.response.send_message("The server name was not found in the database.", ephemeral=True)
else:
await interaction.response.send_message("You do not have permission to close this ticket.", ephemeral=True)```
what? i don't understand
my bot does not work?
That doesn't look like a response to you, but rather a different issue the user is facing..
Error: AttributeError: module 'discord' has no attribute 'Intents'
My Code: ```
import discord
intents = discord.Intents.default()
intents.members = True
client = discord.Client(intents=intents)
Event handler for when the bot is ready
@client.event
async def on_ready():
print(f'Logged in as {client.user.name} ({client.user.id})')
client.run("my token is here")```
anything I do nothing seems to work literally
What discord.py version have you installed
1.5.0
There's the issue
its way too low
!pypi discord.py
I tried the newest version aswell
I just downgraded but I can retry
Install 2.3.2 and then it works
ok lemme see
Ok it works I just had to completely uninstall everything and reinstall only 2.3.2
okay so we have
@commands.has_guild_permissions
@commands.has_permissions
If they have the guild permission, is there a way to restrict the channel permission too? Because I might have to do a check for both possibly?
i don't really know how channel perms work, so thats why I am asking, even tho its a dumb question.
@discord.ext.commands.has_permissions(**perms)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#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).
This check raises a special exception, [`MissingPermissions`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingPermissions) that is inherited from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure).
Note that this check operates on the current channel permissions, not the guild wide permissions.
@discord.ext.commands.has_guild_permissions(**perms)```
Similar to [`has_permissions()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.has_permissions), but operates on guild wide permissions instead of the current channel permissions.
If this check is called in a DM context, it will raise an exception, [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage).
New in version 1.3.
Similar to has_permissions(), but operates on guild wide permissions instead of the current channel permissions.
You miss understood, or I explained bad.
what im asking is, in discord, if I have the guild permission to manage messages, aka delete messages, is there a way to restrict that perm from my role for a certain channel.
Well yes, that's the overwrites?
so then, its best to do a check for both correct?
pls help
I would check both, unless you just care if they have a permission in that specific channel
e.g. users can create channels with the bot and then delete them as well, and your bot gives them the permission to manage channels only for that channel rather than the entire guild
Well, im just wondering what would be best. Just checking if they have the perm in the guild, or if they have the perm in the guild + channel.
Mostly depends on the use case
yep
alr, thank you.
For running a discord bot with docker
better as root, nonroot and then how do I keep file access and commands whatnot in there?
Except the webserver?
Boo ๐ป
.
.
if by checking both you mean applying both decorators you linked earlier, the @commands.has_permission() decorator automatically applies "guild permissions" (owner/administrator/roles) + overwrites for you, so mixing it with has_guild_permissions() is usually not necessary
It only checks channel tho I thought?
So its best to just use commands.has_permission?
internally it uses ctx.permissions, which uses channel.permissions_for(), which takes into account guild + channel perms
https://github.com/Rapptz/discord.py/blob/v2.3.2/discord/abc.py#L672-L677
discord/ext/commands/core.py line 2203
permissions = ctx.permissions```
`discord/ext/commands/context.py` line 479
```py
return self.channel.permissions_for(self.author) # type: ignore```
`discord/abc.py` lines 672 to 677
```py
- Guild owner
- Guild roles
- Channel overrides
- Member overrides
- Implicit permissions
- Member timeout```
so is it better to use has_permission or has_guild_permission?
use the former if you want it to take into account the current channel they invoked the command from
I think I will stick with guild, because idk many servers who use the channel perms. Maybe I am wrong.
Just confused on whats the best way of taking care of perms
consider a purge command that deletes N messages in the current channel, should that command take into account overwrites or not? in other words, if someone is only allowed to manage messages in one channel but not in others, should they be allowed to use the command in that channel? (the reverse can also happen, i.e. someone whose roles allow them to manage messages except in one channel)
Alr, I see what you mean
okay then
how can I improve my error handling to where it will handle if its a guild perm, or a channel perm.
I currently only have BotMissingPermissions and MissingPermissions, how can I make it to where the user knows where to change the permissions, because most people will think its just a role issue, instead of a channel issues in reality it was a channel issue.
hmm, i guess you'd have to manually figure out why a permission isnt allowed, but its a bit complicated by has_guild_permissions() raising the same exception type as has_permissions(), plus the exception can contain multiple permissions that are missing
well to make it easier, in the error, I should probably just tell them to check channel + guild permissions?
Because currently, this is how it would work, it just says the bot doesn't have permissions.
This is an example of only the bot not having permissions.
But I could enhance it by saying something like
Reminder, make sure to check the channel permissions and the server permissions or something along those lines, making sure the user checks both?
though it would be inaccurate to bring up channel permissions if the decorator was has_guild_permissions()...
i would probably wrap has_guild_permissions to raise an inherited exception so its easier to tell them apart
Hm, you would be right about that. I forgot to think abt that.
Error handling is complicated when you think about it, even tho its easy to do xD
for example: ```py
class MissingGuildPermissions(commands.MissingPermissions):
"""The user lacks guild-wide permissions to run a command."""
def has_guild_permissions(**perms):
predicate = commands.has_guild_permissions(**perms).predicate
async def wrapped(ctx):
try:
return await predicate(ctx)
except commands.MissingPermissions as e:
missing = e.missing_permissions
raise MissingGuildPermissions(missing) from None
return commands.check(wrapped)``` references:
https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#checks
https://discordpy.readthedocs.io/en/stable/ext/commands/api.html#discord.ext.commands.MissingPermissions
kinda feels like dpy should have had this exception type already, but i guess its not a frequent use case
They should still have it imo
Show your code
so... i need a tad bit of help...
if i get this result
<member 'user' of 'Interaction' objects> has requested to remove their Birthday from the server logs.
but i have this as the line of code...
optout_request_message = f"{discord.Interaction.user} has requested to remove their Birthday from the server logs. " \
my end function is to have the mention of the user that requested the command
also, imma yeoink this if you dont mind :>
bro typing up a storm... 0_o
Heh
ya im having a tough time writing a decent explanation for your question
it helps to learn more about object-oriented programming for this, but basically there's a difference between "classes" and "objects/instances" - Take petting cats for example: Cat would be called a class, and Walter would be an instance of that class. You can pet Walter because he is a physical being, but you can't pet Cat because it's merely a conceptual idea. The same goes for discord.Interaction, you can't write discord.Interaction.user because "Interaction" is merely a concept not associated with any command.
to clarify the distinction, here's a code snippet: py @bot.tree.command() async def greet(interaction: discord.Interaction): await interaction.response.send_message(f"Hello, {interaction.user.mention}!") discord.Interaction is a "class", and the variable interaction holds the actual interaction that has the user to be mentioned
right, so If i wanted to use get the user mention, i had discord.Member, but had the same result.
most of the things you see in dpy's documentation assume that you have an instance of that class
cause i have this atm.
async def optout(ctx: discord.Member=None):
and im trying to use the discord.Member=None result as the member that used the command
You usually never access (or instantiate) the discord.Xxxxx classes that represent discord API models. But get them from discord.py by either means of command arguments, or methods that you call on the bot/client, or on other objects. like bot.get_guild, guild.get_role, etc
in this case, discord.py doesn't care what you write there because it will always give you a Context object as the first parameter (or Interaction if its a slash command)
(huh I can't react to this person's messages... Blocked I guess? Wasted effort typing sadge)
yea, its an interaction.
well i did have it before, but removed it cause it was having troubles as well...
ooo, ok wait, i got somewhere
its just not an @ anymore
ctx.user
is what kinda fixed it, but i wonder if its ctx.user.mention?
yeah, that should be valid
AHHH
there we go, yep that did it...
so i was being funky in the head and dident do brain right
tyty!
sounds good :>
straight forward ```py
intents = discord.Intents.default()
intents.message_content = True
and then just pass this intents into the commands.Bot constructor, and enable message content in the developer page
how do i enable it?? i don't see it in my dev app page
in the bot tab,
oh in there i thought in the check box, sorry. and thank you
what is the plugin called?
I'm not sure
working code
error code
what's different with it? i can't see anything wrong with it
and it doesn't even work??? ๐ญ
can anyone help
@client.event
async def on_message(message):
if message.content.startswith('+ping'):
ping = message.content.replace("+ping ","")
user_id = int(ping[2:-1]) # convert to int
dm_member = await message.guild.get_member(user_id) # this function accepts an int
pinger = message.author
await dm_member.send('You got pinged by:')
await dm_member.send(pinger)```
dm_member await = ...
Also, please send code as texts instead of screenshots
yeah this
it doesn't have error code anymore
but
it doesn't work
is there anything different from
intents = discord.Intents.default()
intents.message_content = True```
and
```python
intents = Intents.default()
intents.message_content = True```?
if you dont really see the syntax error there, i recommend going back to the fundamentals for python async/await syntax. discord.py isn't for beginners unfortunately, and also get_member isn't a coroutine btw.

from enum import member
import discord
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = discord.Intents.default()
intents.message_content = True
client = commands.Bot(command_prefix="!", intents=intents)
@client.event
async def on_ready():
print("Is logged in")
@client.command()
async def hello(ctx):
await ctx.send("Hello!")
@client.command()
async def ping(ctx):
await ctx.send("Pong")
@client.command()
async def shutdown(ctx):
await ctx.send('Shutting Down The Bot')
await client.close()
@client.event
async def on_message(message):
if client.user.id != message.author.id:
if 'burn' in message.content:
await message.channel.send('them')
await client.process_commands(message)
@client.event
async def on_message(message):
if client.user.id != message.author.id:
if 'who' in message.content:
await message.channel.send('asked')
await client.process_commands(message)
@client.event
async def on_message(message):
if message.content.startswith('+ping'):
mentioned_users = message.mentions
if mentioned_users:
user_id = mentioned_users[0].id
dm_member = await message.guild.get_member(user_id)
if dm_member:
pinger = message.author
await dm_member.send('You got pinged by:')
await dm_member.send(pinger)
else:
await message.channel.send('User not found in the server.')
else:
await message.channel.send('Please mention a user to ping.')```
my bot broke after i add another `@client.event`, why?
You're overriding the previous events ๐ซ
Consider using the command extension or listeners instead
what's that
Which
The command extension is a convenient module of discord.py that makes creating prefix commands easier
And listeners are basically events, but you can have multiple of them
!d discord.ext.commands.Bot.listen
@listen(name=None)```
A decorator that registers another function as an external event listener. Basically this allows you to listen to multiple events from different places e.g. such as [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready)
The functions being listened to must be a [coroutine](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Example...

anyone know why this isnt letting me select my dir Ive tried using ai I tried looking for help on stack overflow nothing seems to help
@bot.tree.command(name="cd", description="Change directory.")
async def change_directory(interaction: discord.Interaction, directory: str = None):
try:
if directory is None:
current_directory = os.getcwd()
directories = [d for d in os.listdir() if os.path.isdir(d)]
options = [discord.SelectOption(label=d, value=os.path.abspath(d)) for d in directories]
print(options)
select = discord.ui.Select(
placeholder='Select a directory',
options=options,
)
print("hi")
view = discord.ui.View()
view.add_item(select)
print("hi2")
await interaction.response.send_message("Please select a directory:", view=view)
else:
print("hi3")
current_directory = os.getcwd()
os.chdir(directory)
new_directory = os.getcwd()
files = os.listdir()
file_list = "\n".join(files)
response = f"Changed directory from '{current_directory}' to '{new_directory}'\n"
response += f"Current directory files:\n{file_list}"
print("hi4")
await interaction.response.send_message(content=response)
except FileNotFoundError:
await interaction.response.send_message(content=f"Directory '{directory}' not found.")
except Exception as e:
await interaction.response.send_message(content=f"An error occurred: {e}")
why would you ever want to do this?
anyone can use this command and do things to your machine
Its in a private server im trying to make commands so I can use them from my phone for fun
what does it look like after you used the command
you can't see the options?
there isn't a callback so nothing happens after you select
it's probably a discord timestamp
!d discord.utils.format_dt
discord.utils.format_dt(dt, /, style=None)```
A helper function to format a [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime) for presentation within Discord.
This allows for a locale-independent way of presenting data using Discord specific Markdown...
it's just a string that discord recognize as a timestamp, so you can use this to convert your datetime
Oooh I have that I just can't figure out how can it have a hover popup
it automatically have it
wait what lemme check my code
<t:1709443285:F> = <t:1709443285:F>
Now my last question is how can I do a 5 years ago but still a timestamp
Do you guys have a documentation I can rwad on
I found a documentation thanks @golden portal
What do you mean?
how long does it take for slash commands to register
If you mean that only one of the two slash commands is showing, then it's because their function names are the exact same
i duplicated the working code as a test
That causes one to be overrided
wdym
!e
def func():
print(1)
def func():
print(2)
func()
@naive briar :white_check_mark: Your 3.12 eval job has completed with return code 0.
2
The first function was overrided because the second one overrides its namespace
Idk how to explain more than that
Okay thanks
i think technically both might still be remembered by CommandTree, but either way if it did refresh properly, the second screenshot should have shown ciao2 in there...
assuming the commands were synced like normal, discord has recently been a bit slow with refreshing slash commands client-side, so restarting your discord app might fix it
i have a scaling issue if anyone wants to be a gentleman and assist,
im at 18k servers and like 1.1m members, the bot main purpose is litening to presence event. i.e status updates, etc. so you could imagine the workload the bot is handling. i had a cache setup to cache data from DB on initial call for that server but it seems to be dogshit and after about 5-10 mins of bot being up everything gets blocked and it's impossible to figure out as when i test on a local server everything works fine but soon as i go to prod gg.
dont name your file as discord.py, it overwrites discord.py's namespace
changed bro
but showing that only
show the error again?
you still have a file named discord.py there inside python codes folder
hmmm, maybe consider redis as cache at this scale? unless you already do that
i've tried to use redis
it legit takes the server offline
lmao
did you use an async redis library?
i see
i guess without code can't really suggest anythin
you're using sharding right
async def on_presence_update(before: disnake.Member, after: disnake.Member):
settings = await get_or_create_settings(after.guild)
_embed = await get_or_create_embed(before.guild)
async def get_or_create_settings(guild: disnake.Guild):
return await db_cache.get(f"guild_settings{guild.id}") or await guild_settings(guild)
async def get_or_create_embed(guild: disnake.Guild):
return await db_cache.get(f"guild_embed{guild.id}") or await guild_embed(guild)
@cache(ttl=21600, key="guild_embed{guild.id}")
async def guild_embed(guild: disnake.Guild):
data = await embed_model.get_or_none(guildid=str(guild.id))
if not data:
return
return data
@cache(ttl=21600, key="guild_settings{guild.id}")
async def guild_settings(guild: disnake.Guild):
data = await guild_model.get_or_none(id=guild.id)
if not data:
return
return data
and yes
im sharding w clusters
now just imagine on_presence_update being spammed and ungodly amount of times
do you get the "can't keep up" warning logged?
nah and just to be safe incase logs were broke, cause they typically do break and not show shit. i've upped the shards/clusters multiple times
rn its at 10 shards a cluster with 7 clusters
and im pretty sure thats overkill tbh
i've had it at 7 clusters 5 shards for a while, then one day the main feature which adds a role to a user when they add a specific status stopped working
hmm, since this is disnake i'm not entirely sure if they did an adequate performance test, maybe you can ask in their server or something
also presence events are typically the most demanding besides typing events
especially at scale, cause there's just so much
imagine how many people are changing their profiles across 1m+ people per second
yeah ik it's cancer, was doing good for awhile and i've finally hit a wall
I am using a webiste api and it worked for me fine till now. They added human verification to it so I cant scrape info using a VPS but it works on my local pc. Any solutions ? This is for my discord bot
!rule 5
5. Do not provide or request help on projects that may violate terms of service, or that may be deemed inappropriate, malicious, or illegal.
Scraping likely violates the terms of services of said website, like many others, and isn't an actual API for bots to be used, otherwise they wouldn't add a human verification to that "API", doesn't make sense.
We won't help
is it possible to create a coundown on discord.py without using Datetime.now() or discord.utils
datetime.now() or datetime.utcnow() shows different timestamps for each individual, for some users they see 2 minutes and for other 4-8 hours its unexplainably inconsistent
did you even use aware datetime ones? discord.utils.utcnow() because you're supposed to use this with format_dt to show it correctly, the whole point of discord timestamp is to show time according to user's locale timezone
hmmm
discord.py doesnt recognize discord.utils.utcnow()
!d discord.utils.utcnow
discord.utils.utcnow()```
A helper function to return an aware UTC datetime representing the current time.
This should be preferred to [`datetime.datetime.utcnow()`](https://docs.python.org/3/library/datetime.html#datetime.datetime.utcnow) since it is an aware datetime, compared to the naive datetime in the standard library.
New in version 2.0.
thanks
i realised Ive written discord.utils.format_dt.utc() and not discord.utils.utcnow()
Societys needs come before the individuals, stop changing your profile!!!
still doesnt work
it still says 4 hrs for others but i see 1m
how can i have an argument in an app command have a list that will change to show results based on whatever i type in?
its a very large dataset
and i want to perform the lookups on disk with my sqldatabase which holds all the info
@commands.is_owner()
@bot.tree.command(name="give", description="Gives roles")
async def add_role(interaction:discord.Interaction,ctx: commands.Context, role:discord.Role, member: discord.Member):
await member.add_roles(role)
embed = discord.Embed
embed(title="Success!",
description=f"Added {role} to {member}.",
color=GREEN_COLOR_Sucess)
await ctx.send(embed=embed)```
is this correct?
An application command doesn't have a context and an interaction, just has an interaction
alright thank you
oh fr?
Nevermind, doesn't seem to
Just know it checks if the user is the owner of bot, not server
What does TypeError: issubclass() arg 1 must be a class mean in slash subcommands?
@parent_roles.sub_command(name="add-parent-role", description="Add a new parent role")
@guild_exists()
async def add_parent_role(self, inter, role: disnake.Role, *, roles: list[disnake.Role]):
await new_parent_role(inter.guild.id, role, roles)
await inter.send(f"**{role.name}** has been set as a parent role to roles:\n{', '.join(role.name for role in roles)}")
what is the full error?
(aka, include the traceback, not only the error text)
if you're not using issubclass yourself, this may be a problem with the library you're using, 'disnake', but I am unfamiliar with it.
cogs.ranks is failed to load:
Ignoring exception in on_ready
Traceback (most recent call last):
...
File "D:\dbots\rankmaster\cogs\ranks.py", line 7, in <module>
class Ranks(commands.Cog):
File "D:\dbots\rankmaster\cogs\ranks.py", line 32, in Ranks
async def add_parent_role(self, inter, role: disnake.Role, *, roles: list[disnake.Role]):
...
TypeError: issubclass() arg 1 must be a class
That's pretty much the only useful info from the traceback, the other is just the roots of the error
it's a fork of dpy, shouldn't be different really
the problem is ... that comes from ... because you passed ... to ...
!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.
thanks
np
it appears that only the subcommand add_parent_role is the only one raising that error. I have other subcommands, however, they don't raise it.
Probably cuz it's a subcommand group?
https://paste.pythondiscord.com/I57Q that's my cog's code
the error appears to be that disnake is failing to parse the annotation of the parameters of the function, and internally, it is passing an instance to issubclass rather than a type. (?)
I'm not sure if it has to do with this annotation: https://leo.might-be.gay/ZXRA6X.png discord.py's slash commands do not support it, and maybe the bug is from the handling of that? I am honestly unsure because this codebase varies wildly from the discord.py one which I am familiar with
I found the issue. I tried removing roles: list[disnake.Role] from the function's parameters, and it doesn't raise the error anymore.
lol, well what's a way to give multiple values to the same parameter in slash commands?
yeah lmao
maybe i can make it as one argument, but provide instructions for the user to separate them with a comma, and in the code I'd just use split()?
that would probably be the only way. variadic arguments are not a thing that discord supports
though I guess *, usually means single varying-length parameter, not multiple.
ddev is just testing my patience at this point lmao
also, lol, that's one hell of an error to give out when passing an unsupported annotation lol
this is what I get https://leo.might-be.gay/JWQK0J.png (then again, libraries differ a bunch)
real. discord's new changes are a mess
love the domain

https://paste.pythondiscord.com/L3BA
Help, for some reason the menu is printing to chat twice instead of once and idk why ๐ฎ
I feel like its a symple fix but idk
.-.
you mean that this replies twice?
yes
possible reasons,
- you have two instances of the bot running
- you are calling
Bot.process_commandsmore than once
does this occur with all commands, perchance?
no just that one
intents = discord.Intents().all()
bot = commands.Bot(command_prefix="Echo_", intents=intents, case_insensitive=True)
status = variables = [
discord.Game(name='StarMade'),
discord.Activity(type=discord.ActivityType.listening, name='Spotify'),
]
@bot.event
async def on_ready():
create_database()
print('Successfully logged in as {0.user}'.format(bot))
bot.add_cog(messageModule(bot))
bot.add_cog(memberModule(bot))
bot.add_cog(weatherModule(bot))
bot.add_cog(channelModule(bot))
bot.add_cog(HelpModule(bot))
bot.add_cog(ModerationModule(bot))
bot.add_cog(reminderModule(bot))
await bot.change_presence(status=discord.Status.online, activity=discord.Game('Starting...'))
await asyncio.sleep(5)
status_cycle = cycle(variables)
while True:
current_status = next(status_cycle)
await bot.change_presence(status=discord.Status.online, activity=current_status)
random_delay = random.uniform(30, 600)
await asyncio.sleep(random_delay)
bot_token = os.environ.get('TOKEN')
bot.run(bot_token)
thats the main file
oh my god
this is what extensions are for:
https://discordpy.readthedocs.io/en/stable/ext/commands/extensions.html
and you shouldn't do any of this in on_ready- see the warning here:
https://discordpy.readthedocs.io/en/stable/api.html#discord.on_ready
you should use setup_hook instead, by subclassing Client and overwriting that method
https://discordpy.readthedocs.io/en/stable/api.html#discord.Client.setup_hook
how come it works for every other command
honestly, I couldn't tell you
I assume you have two instances of the bot (two scripts running at the same time)
a while true will not work in the setup hook, you could use a task for that instead, though. For the rest, you use setup_hook.
for your issue, can you try resetting your bot token from the panel, and using the new token when running the bot?
then this was the reason.
but why did it do that
unsure why it only bugged for that one
probably just to confuse me
consider implementing the rest of the above things that were pointed out, (extensions, using setup_hook)
i will... now i just have to get the menu to display the command briefs and names under the categories...
good thing about extensions is that you can use bot.(load/reload/unload)_extension to not have to restart the whole script every time you modify a Cog
๐
(example of Cog+extension https://gist.github.com/EvieePy/d78c061a4798ae81be9825468fe146be)
by the way, if you want a help command, consider subclassing the commands.HelpCommand class instead of doing this
i will be implementing that in the next major bot update tysm
(yes my brain is just a conglomerate of random URLs of helpful(ish) things
)
๐
How do I hosted my bot 24/7
purchase a cheap VPS, for example https://hetzner.com/cloud
Cloud servers starting at โฌ 3.79. A little money gets you lots of cloud. Our flexible billing model and clever interface make it easy to use our cloud servers for all your IT needs.
you will need knowledge of the linux command line but yeah
its free ๐
Hmm
(im using it rn)
And I only need the code?
If the repository on github is private will it still work?
i think so, you might just need a security key
Okay, since the token is in the code it can't be public
also, there are variables enabled to put sensitive information like tokens etc
i have mine public but the token is in a variable that only i can access
btw if your bot uses imports you'll need to make a requirements.txt file
Idk how to do that, yes it does
biggest meme lol
async def extract(interaction: discord.Interaction, channel: discord.TextChannel) -> None:
if channel is not None:
history = [message.content async for message in channel.history(limit=None)]
print(len(history))
else:
await interaction.response.send_message("**Ensure you specify a channel!**")
Only returning 100 messages, anyone know the issue?
Because there is a maximum limit of 100 messages that can be retrieved at once iirc
So how could I retrieve all of them?
yes
unless you redacted some code, i also can't repro that
is there some sort of limitation from when the message was sent?
LIke how you can't delete messages older then 14 days? I thought you'd still be able to read them
there isnt a limit tbh, i've gathered up to 14mil messages on a textchannel that goes back to 2018
soo am I doing it wrong or
Ok LOL wtf
discord must've been broken the last time I wrote that code
Cause now it's working fine ๐ญ
!e
code
!eval [python_version] <code, ...>
Can also use: e
Run Python code and get the results.
This command supports multiple lines of code, including formatted code blocks. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.
The starting working directory /home, is a writeable temporary file system. Files created, excluding names with leading underscores, will be uploaded in the response.
If multiple codeblocks are in a message, all of them will be joined and evaluated, ignoring the text outside them.
Currently only 3.12 version is supported.
We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!
!e print("")
@lyric solar :warning: Your 3.12 eval job has completed with return code 0.
[No output]
!e
import requests
e = requests.get("google.com")
print(e.text)
@lyric solar :x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | import requests
004 | ModuleNotFoundError: No module named 'requests'
@lyric solar :x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 2, in <module>
003 | subprocess.check_call("python3 -m pip install requests")
004 | File "/lang/python/default/lib/python3.12/subprocess.py", line 408, in check_call
005 | retcode = call(*popenargs, **kwargs)
006 | ^^^^^^^^^^^^^^^^^^^^^^^^^^
007 | File "/lang/python/default/lib/python3.12/subprocess.py", line 389, in call
008 | with Popen(*popenargs, **kwargs) as p:
009 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^
010 | File "/lang/python/default/lib/python3.12/subprocess.py", line 1026, in __init__
011 | self._execute_child(args, executable, preexec_fn, close_fds,
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/I6PR23BF2ELK4MCO4FAA2MBJ5A
๐
Ive a query regarding my discord bot, It works as follows
- Gets a message with image
- Sends it to my tensorflow api and recognizes it
- Sends the name to the channel
Now the issue comes when various channels spam it at the same time, I would like it so it goes
Processes 1 image, sends the name
waits 0.3 seconds
Processes 2nd Image, sends the name
waits 0.4 seconds
But it goes
Processes all 20 images, sends all 20 names at once. Which results in ratelimit. Can someone help?
Either combine those 20 names into one message (why not do that actually) or make some queue task processor
cuz The channels are all different my friend, and making one message would not result in what i want it to, but damn queue maybe thats it
yep thankyou
Could someone link that gist guide on slash commands in dpy
A hands-on guide to Discord.py
Bro worked super hard on this ๐
I want to create a hidden secrets command that will not shows to anyone and only for owner command. That CMDs shows the list of all server that is bot currently is
Ping me is someone help
@pale zenith
Is your command app_command or discord.ext command ?
Yup ty I forgot asher made it

It's hybrid command
Idk the decorators for hybrid commands
!d discord.ext.commands.is_owner defo works for message commands, no idea whether it works for hybrids
@discord.ext.commands.is_owner()```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check) that checks if the person invoking this command is the owner of the bot.
This is powered by [`Bot.is_owner()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Bot.is_owner).
This check raises a special exception, [`NotOwner`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NotOwner) that is derived from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure).
Dpy is bad โบ๏ธ
Integrations permissions or per guild sync
permissions can still be changed
yeah that's the unfortunate reality
The is_owner check pointed above should work for hybrid commands, but this will only make it raise an error in-code, and not hide it in the discord UI. Unfortunately due to how discord slash commands work, you can only restrtict slash commands through permissions (or through NSFW/[guild/dm]_only). If you want a command that can only be seen by a person you will need to
- make it a guild command
- go into server settings and change the permissions from within the integrations tab
And even then, people with administrator permissions will bypass those permission restrictions
having an owner-only command globally does not make sense in the context of a slash command. It's better to stick with prefix commands for those
@pine veldt ^
Hmm
I switched back to Ubuntu since I wanted to try out Docker. So now all my Discord bots have been running on Docker for a couple of days with no issues whatsoever, everything is running just fine. Thanks for the help!
Docker is the best
Docker based
yeah I have been hosting 2 Bots on the same VPS (Vultr) on Debian for over a month and they did not face any issues
Are you using Docker as well?
Nope straight up fresh not even a Docker
How do i fix that i want it to @ a user
Remove the &
^
& is used to ping Roles
Hello guys, i need help with permission overwrite for a voice channel
overwrite.view_channel = True
overwrite.connect = False
await channel.set_permissions(ctx.guild.default_role, overwrite=overwrite)```
Idk why everyone can connect to the channel
whatever tutorial you are following is outdated and you shouldn't follow it
okay thanks
can you show the overwrite variable
Its fixed now, i have just put the overwrite in the create_voice_channel
I just need to rewrite all my bot for try to understand and use the await database
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.
Ok its not fixed
overwrite = discord.PermissionOverwrite()
overwrite = discord.PermissionOverwrite()
overwrite.view_channel = True
overwrite.connect = False
channel = await ctx.guild.create_voice_channel(name = f"๐ฅ Member Total : {len(ctx.guild.members)}", position = 0)
await channel.set_permissions(ctx.guild.default_role, overwrite=overwrite)```
Im currently running my own dedicated minecraft server, would it be too much of a resource hog to also run a discord bot on the same machine?
How come I have to reinvite my discord bot to my server each time I add a new slash command?
No?
Someone can help me a bit?
ask away
await edit(*, reason=None, **options)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the channel.
You must have [`manage_channels`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_channels) to do this.
Changed in version 1.3: The `overwrites` keyword-only parameter was added.
Changed in version 2.0: Edits are no longer in-place, the newly edited channel is returned instead.
Changed in version 2.0: The `region` parameter now accepts [`str`](https://docs.python.org/3/library/stdtypes.html#str) instead of an enum...
ah interesting ill try thanks
No, but you might have to restart discord client since it often doesn't update commands list even tho it is updated on their servers
Uhm why I got error when I try adding Boolean annotation as params??
!traceback show the error
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.
https://paste.pythondiscord.com/KQ2A
Prior to this code being excuted it players use !q to que for a lobby, once the lobby reaches 4 people it will create a Lobby voice channel with there que id matching. (THIS IS WORKING)
However the code I am showing you is not, it should
- Once all 4 members join the lobby VC
- Annouce the random reason Team 1 & Team 2
- Create team 1 and team 2 voice channels
- Move the players to their teams voice channel
- Delete the lobby voice channel
any ideas?
what actually happens then
this is a python server, not javascript
you want to ask how you should go about it or what?
!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) for non-interaction contexts.
For interaction based contexts this does one of the following...
to the send method just add your view as a kwarg
and also make ephemeral kwarg True
oh
could you possibly give a simple example?
class YourView(discord.ui.View):
def __init__(self):
super().__init__()
# Create your buttons there
@commands.command()
async def foo(context: commands.Context):
await context.send("hello!", view=YourView(), ephemeral=True)
but you should really use slash commands
if you want the message to be visible only
for the author
A hands-on guide to Discord.py
ok so it wouldnt work for message commands?
I don't think it will be visible only for
the author in this case but you might
ask someone more experienced
Yeah prefix commands can't be ephemeral
ah crap
This will give error

Context.send doesn't have ephemeral param
oh darn
it has, but only in specific cases
for security, it is better to use it only with app_commands
Interaction type context
Idk last time i did i got the error unless i used hybrid_command deco
I'd have to try that later
Yeah do tell me what happens
Hi, gotta start my discord bot for automatic1111.
Where do I start? Any leads?
how do i invite my bot to the server? under oauth2 when i select bot > administrator it then states that i require a redriect url - how od i do this?
i solved it, i just created a new application
Dude where do I even start?
to make a bot?
go to like discord.com/developers or something like that and create a new application, then go to the bots section
enable the required intents and stuff
then go to oAuth2 and select bot and then the permissions before adding it to ur server
from there you can go back to bot and copy the token id
from here start coding using that to do "stuff" with your code

Hi, sorry to bother you but i try to use mysql async on my bot but i'm really lost in the doc of mysql with that
I don't understand how to do it, and the white website burns my eyes lol
can you show all the stuff you have selected
it won't ask for redirect URL if the only thing you have selected is "bot"
why is line 3 and 10 red
if you hover over it it tells you
line 3
you dont have the envrioment module being used, and line 10 is telling you that that value is invalid.
SERVER_ID is where you put your guild ID. (how you have it right now, the brackets are trying to take an Int numerical value, instead of a string value. for a string value, do debug_guilds=["MYGUILD"] and that would be a string value instead.)
you also dont specify a .env file to load on start. so it would be pointless to have those lines in there :>
you need a line before or after any events called
load_dotenv()
i would put that around line 7 or so
so it would look a little like
load_dotenv()
TOKEN = os.getenv('token')
You also need a file in the same directory called ".env" and have it formatted correctly for your bot to see it
The .env file would include the following line
token= "YOUR_BOT_TOKEN"
and thats about it.
I'm pretty sure the params have to be lowercase
what's the error otherwise?
just screenshot it?
good morning
because those to examples are to differnt words for python
Wha?
I am saying why I got error when I use parameter name with caps
And why it's a thing
'word' and 'Word' are two different strings, the same rules for strings are in place for keyword argument names
"parameter name"
yes, those are strings
Eh
So variable name is a string?
under the hood yes
Also I talk here cus it's about discord bot
I am saying why I can't use parameter name with caps on it
because that would mean it is a different name compared to what is expected
arg and ARG would be two different arguments
This will error faulting to the parameter
Hmmm
What argument with cap will mean?
I mean what's the difference of parameter with cal and without
means nothing, its just a different name.
Bru
Ofc n != N
well im glad we understand each other, if you wonder about something else i do not understand you, maybe you could explain it more clear
I am saying when I use parameter without caps it works good but it didn't when I use with caps@copper quartz
yes, that is as expected, you should not write keywords differently
i dont know the function signarture your using
but you must follow the signature
maybe you could share what your doing so it is more clear to me
def a(arg):
pass
```this works
```py
def a(Arg):
pass
``` this didn't work
Discord bot ofc this is #discord-bots
I am using treecommand
But using argument with caps don't like to register
I want something like sendDm
But the error faulting that
did you change the case_insensitive part first?
does that make a difference? isn't it only for text commands?
not sure if it works the same for tree command or not.
pretty sure it doesn't
Am too confused to this as I know logically param with caps on its var name has no difference with one without
What did you mean about this?
we use this in our bot, i just assumed that all types of commands had this feature, Ash said it did not.
without it you have to use lowercase
idts that discord provides upper case params anyways
What feature ๐ฅฒ
case insensitive
What it does?
Whether the commands should be case insensitive. Defaults to False. This attribute does not carry over to groups. You must set it to every group if you require group commands to be case insensitive as well.
No much details
So am stuck on lowercase huh ? ๐ฅฒ
yes, discord.py overwrites a lot of python behaviour with their framework, without this feature you are stuck
awkwardly this does not apply to slash commands but its not clear what the error was, if anything i would assume that it was from the discord API telling them uppercase characters aren't allowed:
https://discord.com/developers/docs/interactions/application-commands#application-command-object
CHAT_INPUTcommand names and command option names must match the following regex^[-_\p{L}\p{N}\p{sc=Deva}\p{sc=Thai}]{1,32}$with the unicode flag set. If there is a lowercase variant of any letters used, you must use those. Characters with no lowercase variants and/or uncased letters are still allowed.USERandMESSAGEcommands may be mixed case and can include spaces.
thanks for the clearification, was not aware it was on the API side, thought it was handled by inspecting the co varnames with a regex
oh sure enough it is validated client side
https://github.com/Rapptz/discord.py/blob/v2.3.2/discord/app_commands/commands.py#L190-L194
discord/app_commands/commands.py lines 190 to 194
match = VALID_SLASH_COMMAND_NAME.match(name)
if match is None:
raise ValueError(
f'{name!r} must be between 1-32 characters and contain only lower-case letters, numbers, hyphens, or underscores.'
)```
Sadly i have 0 knowlage on regex
๐ญ
So I'm creating a text to image bot.
So far it works.
I want these height width field to be optional and model to be selected from a drop down. How do I do that?
For the optional options, you can give them their default values in the parameters, and Discord will make them optional, like so:
@tree.command()
async def command(inter, height: int = 720, width: int = 720):
ย ย ...
And for the model drop-down, a simple way is to use the typing.Literal, like so:
from typing import Literal
@tree.command()
async def command(inter, model: Literal["Model-One", "Model-Two"]):
ย ย ...
You can see other ways in the example file
We can also use the Optional from typing module for that right?
Probably, never tried it
Thanks. I will try it today.
Also,How do I learn this stuff?
I come from a non CS background.
for working with discord bots you should first have at least intermediate level understanding of python especially OOPs then you can refer to the documentations or watch vid tutorials online
learning OOPs will make the journey on dbots a lot easier
otherwise you will get stuck when you venture deep into it
How I'll add premade options?? Like I want the user to only use those options for treecommand?
read this @hard kite
What literal and optional does?
Wait I remember them from the documentation of the discord.ext
Or discord.py I don't remember
Well this didn't work
I used a discord.option decorator.
If you would like to see how, let me know.
And BTW, any good resource to learn python OOPs, I know the basics but I have never built anything from scratch. I have always modified existing codes.
i am facing unknown interaction error, what are the possible reasons
i checked and the command is synced and it was working fine yesterday
the only thing i can think of is
maybe the code in command is taking a while to execute so the interaction expires or something? idk if something like that exists
yeah that is the issue
ah
so after how long the interaction expires?
^^
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Check the material provided here 
you can use choices
I had a quick question! Could I add micro-transactions into my discord bot?
I have a server with a currency and I want to sell it for real money, but is there a way to make a page where users can buy it and when the money comes trough the bot gives them the currency?
find a payment gateway service, like RazorPay, etc and then find a wrapper lib for it so you can use it with your bot
or work with raw api if you can
When using the discord.py slash commands how can you add a description for a parameter?
!d discord.app_commands.describe
@discord.app_commands.describe(**parameters)```
Describes the given parameters by their name using the key of the keyword argument as the name.
Example:
```py
@app_commands.command(description='Bans a member')
@app_commands.describe(member='the member to ban')
async def ban(interaction: discord.Interaction, member: discord.Member):
await interaction.response.send_message(f'Banned {member}')
``` Alternatively, you can describe parameters using Google, Sphinx, or Numpy style docstrings...
What is that ๐ฎ
I'll check that out
API = Application Programming Interface
tysm
Hi, sorry to bother you but i try to use mysql async on my bot but i'm really lost in the doc of mysql with that
I don't understand how to do it, and the white website burns my eyes lol
@tree.command(description="Send a dm to a member")
async def say(interaction: discord.Interaction, recipient: discord.Member, content: str) -> None:
await recipient.send(content)
await interaction.response.send_message("Command succeeded!", ephemeral=True)
@say.error
async def say_err(interaction: discord.Interaction, error: discord.app_commands.AppCommandError) -> None:
...
)```
Hey, I was curious if there was a better way to handle errors than using the `command_name.error` decorator. It just seems like a really verbose way of doing it. Also curious while I'm here if I can do something similar to `commands.Cogs` while just using `discord.Client`? I want to separate my bot into multiple files to make it easier to organize
Oh wait, could I just use multiple ComandTrees?
One for each file, but then import them and then sync them all in my on_ready?
why would you need multiple CommandTree's
Well, I'm asking if I could modularize the bot
Specifically discord.Client
seeing as cogs are apart of discord.ext.commands
About the cogs with discord.Client, im pretty sure that you can't do that
That's what I said
thats why most people consider using commands.Bot
It feels like you're avoiding answering my question, and just telling me to use something different
I'm going to try the approach with multiple command trees and get back to you
client does not support multiple client trees afaik
the best option you'd have is to import a single client tree around
it depends on the exact kind of error you want to handle. is it specific to just this command (that is, is this command the only one that will raise this error?) or is it an error that all commands can raise?
Also syncing in on_ready is not the best way
as it can be called multiple times
In this case, it'd be a couple commands. I have a few that could potentially raise discord.Forbidden because of a user's private messages settings @sick birch
So what's the best way?
in this case you would put discord.Forbidden in a global handler
you'd make a command for syncing typically
Should I be using commands.Bot instead? I was trying to avoid using prefix commands
Ah okay thank you
you don't need to use prefix commands with commands.Bot
also if you don't use any prefix commands at all you can just disable the messages intents
so that way you don't have to process messages at all
as far as discord.py is concerned nobody is sending any messages
Ah, but I'd still need the messages intent if I wanted to do anything with reactions though I'd assume
good question. not entirely sure, i haven't tested it
One more question actually
If I need to create a command to sync, but I need to sync have access to all my commands, how does that work?
I must be misunderstanding something about that
for a sync command you just need to sync it once initially
sync commands don't change all that much
or a prefix command
Ah okay thank you very much
Anyone is willing to begin a new discord bot project (I don't have anything in my mind we can create anything)
this ought to be pinned <3
good on you for actually using the search feature
most people don't
async def serverinfo(ctx, interaction: discord.Interaction):
server = ctx.guild
embed = discord.Embed(title=f"Server Information - {server.name}", color=0x3498db)
embed.set_thumbnail(url=server.icon_url)
embed.add_field(name="Server ID", value=server.id, inline=False)
embed.add_field(name="Owner", value=server.owner.mention, inline=False)
embed.add_field(name="Member Count", value=server.member_count, inline=False)
embed.add_field(name="Text Channels", value=len(server.text_channels), inline=True)
embed.add_field(name="Voice Channels", value=len(server.voice_channels), inline=True)
await interaction.send(embed=embed)```
Why doesnt this work
because interaction doesn't have a send() method
so interaction.send() isn't gonna work
sorry if i sound a bit gross, I'm super sick and I'm on the verge of coughing after every word
@slate swift
@app_commands.describe(thing_to_say = "What will you suggest?")
async def suggest(interaction: discord.Interaction):
if ctx.channel_id != allowed_channel_id:
embed = discord.Embed(title=f"{interaction.user.name} Suggested!", description="They suggested {thing_to_say}")
await interaction.response.send_message(embed=embed)```
i have this code now but you said i shouldnt use ctx now my `if ctx.channel_id` is a error
interaction.channel_id
@bot.tree.command(name='suggest', description='test some')
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\dynam\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\discord\app_commands\tree.py", line 887, in decorator
command = Command(
^^^^^^^^
File "C:\Users\dynam\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\discord\app_commands\commands.py", line 666, in __init__
self._params: Dict[str, CommandParameter] = _extract_parameters_from_callback(callback, callback.__globals__)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\dynam\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\discord\app_commands\commands.py", line 389, in _extract_parameters_from_callback
_populate_descriptions(result, descriptions)
File "C:\Users\dynam\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.12_qbz5n2kfra8p0\LocalCache\local-packages\Python312\site-packages\discord\app_commands\commands.py", line 277, in _populate_descriptions
raise TypeError(f'unknown parameter given: {first}')
TypeError: unknown parameter given: thing_to_say```
the error is this
but why doesnt it work though
What app_commands.describe do?
interaction.channel.id
.
ah sorry
you are saying that thing_to_say argument will have description "What will you suggest?" but you dont have such argument in your command
btw for future reference i advise you reading this guide, it covers most of the topics you need to know
https://fallendeity.github.io/discord.py-masterclass/slash-commands/
A hands-on guide to Discord.py
holy it is my number two fan
So how do you guys add time out for discord functions?
I am making a txt2img bot now and will add more functions to it. That may take about a minute to respond.
You can add cooldowns for that
!d discord.ext.commands.cooldown
@discord.ext.commands.cooldown(rate, per, type=discord.ext.commands.BucketType.default)```
A decorator that adds a cooldown to a [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command)
A cooldown allows a command to only be used a specific amount of times in a specific time frame. These cooldowns can be based either on a per-guild, per-channel, per-user, per-role or global basis. Denoted by the third argument of `type` which must be of enum type [`BucketType`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.BucketType).
If a cooldown is triggered, then [`CommandOnCooldown`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandOnCooldown) is triggered in [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error) and the local error handler.
A command can only have a single cooldown.
Isn't cooldown for limiting users to send messages?
That's great too.
But I guess it has to be something about time-out. No?
Not just user
This is something I found
Alright. Let me read up the documentation
Using this is just to avoid an error that occurs during command that take long time to complete
Here's my function
I see!!
There is a 3 sec time window in which u have to respond to a interaction and defer is a response so that solves the issue and then within the next 15 min u can send your actual output using interaction.followup.send()
Yes you will need to defer it
Since image gen takes more than 3 sec
Yes that's what I was talking about.
And I'd say also implement a cooldown so that not too many prompts are given to be generated at same time
Does discord bot handle concurrent requests and queue them? Or should I be coding it myself?
Yeah I will add that. That will help limit the number of requests by users
Perfect. Thanks man. You have been a great help
This is a prefix command right?
Then it won't need defer
@turbid condor what do you mean prefix command?
No, it's a slash command
Deferring is for hybrid or slash only
Which Library are you using?
Pycord
Ahh i see
It's just ctx is confusing as it's mostly thought of as context instead of interaction
Yeah then you will gonna be need to defer it
Or you can do it by sending an initial response with a message like "Generating Image. Please wait..."
And then send followup or edit the original response when image is completed
That's a cool idea.
Let me try it.
So it's fixed. Thank you man.
Can I DM you if I need any further help?
Well u can but i say just ask here u will get a better response then what i alone can give you
Hi, I've been using pycord's ApplicationContext for my bot. Is it possible to migrate to discord.py without much changes? Also i would like to know if there are major performance deficits between these libs. or if there is another alternative
They have different ways to create app commands, so you'll need to rewrite a considerable amount
Don't know about performance difference though
The easiest way to migrate is to use discord.py's hybrid_commands (docs), which take a commands.Context and register an app command and a message command at the same time
if you don't want the message commands part, you'd simply not enable the message content intent.
the one disadvantage of this, though, is that since they are hybrid, some interaction-only features are not to be found in the Context class. Like interaction.response.send_modal, or interaction.response.edit_messages, there is only ctx.defer
else, yeah, completely migrate to app commands. (here's a guide)
well performance deficit is the sole reason why i'm considering migration tbh
thank you for the answers
bro windows + shift + s and snip
my vision after my tears act up:
Is discordpy still how most bots are made today? I've been out of the loop for making discord bots for a bit, so just wanted to ask.
discord.py and discord.js are probably the most popular discord bot libraries across all languages
Alright, thank you.
It shouldn't matter tho
why do i get this error with embed color?
0000FF is an invalid decimal literal (๐คฏ)
thx, what did it change?
@naive briar :white_check_mark: Your 3.12 eval job has completed with return code 0.
255
I'm playing around with @tree commands. Haven't tried those before but seem super nifty.
@tree.command(
name="hello",
description="will make the bot send a greeting",
guild=discord.Object(id=<guild id>)
)
async def _hello(interaction):
await interaction.response.send_message("Hello!")
Is there a way to remove this part of a bot's response though?
You can make the message ephemeral to not show the response at all
Or you can simply do a normal channel.send
I would like to show a response, just don't care to have the "user used" part
if you don't care about it I'd say just leave it
I do care that it's there. I don't want that part to be there.
thats just how slash commands work
Given this code, if I only do the first line, then the command hangs in Discord until it tells me the application fails, despite the message being sent to my channel.
If I do both or the second line then it seems to finish and does not tell me that the Application failed. Why is that?
async def _test(interaction):
await interaction.channel.send("test")
await interaction.response.send_message("test")
You need to defer before using response.defer
I see. Defer what exactly? The interaction object?
interaction.response.defer
Yes. Doing that makes the bot seem stuck on "thinking".
You might have to pass thinking=False into the method
The website got DDOS attacked so the server enabled the human verification lol
This error is always cause of the internet right ?
You gotta change the response to followup and then try again
I tried to add optional values, but now the command doesn't work at all.
It just tries to submit and then fails.
async def _alarm(interaction, hour: int = -1, min: int = -1):
I wanna be able to give the user the ability to call /alarm and /alarm hour: min:
https://discord.com/developers/docs/interactions/receiving-and-responding#responding-to-an-interaction
https://discordpy.readthedocs.io/en/stable/interactions/api.html#discord.InteractionResponse.defer
unfortunately discord's API requires slash command interactions to use "thinking" defers since the silent kind, DEFERRED_UPDATE_MESSAGE, is "only valid for component-based interactions"
Send the error message
So it's not possible?
afaik nope, you'll probably just have to send an ephemeral message saying your command was successful or something
The error message on the editor
There is none in the terminal
Alright, thank you
uhh can you send the code a bit more then ? You sure the bot is running lol ?
Im pretty sure it throws that when the bot is not running, try it and lmk
Or when it takes more that 3 seconds to respond but in your case thereis no error in the terminal
When I add this to the top of my function call, the bot stops working.
print(f'{interaction.message.created_at}')
Can you send the entire code of that function if its not that big
async def _alarm(interaction, hour: int = -1, min: int = -1):
print(f'{interaction.message.created_at}')
its not running cause there is no output im guessing
No output? What do you mean?
are you not getting the output for that print one as well on the terminal ?
It's not printing to terminal, no
Which is odd, because this:
@client.event
async def on_ready():
await tree.sync(guild=discord.Object(id=<guild id>))
print(f'We have logged in as {client.user}')
Does print to terminal
Okay. Found the issue.
The "message" object is "None"
shouldnt this be interaction.created at ?
ye try this ^
Yeah I see that now. I thought the message was needed but the interaction gives the time as well.
Thank you for the help.
wlcm : )
does anyone know why my reaction remove event is not working as expected?
https://paste.pythondiscord.com/D54Q
basically a starboard reaction remove event, so when it gets to a number lower than the set star count, it should edit the msg, and if the count goes to 0, bot should delete the posted star embed
Perfect.
to do this, im storing these values:
star config table
guild_id | channel_id | self star | star count
star info table
guild_id | bot msg id | user msg id
seems mostly fine, can you try adding print statements to see what's going on? for example one at the start so you know the event is firing, one before each return statement, and one to see what reactions are listed on the message
oh wait, message.reactions is going to be empty if the reaction count is 0
yeah
well empty if there aren't other reactions, but for robustness i would only check the star reaction's count, i.e. discord.utils.get(message.reactions, emoji="โญ")
so like if message.reactions edit it, else delete msg?
well, either the reaction object won't exist, or it will exist and will have some count of 1 or higher