#discord-bots
1 messages · Page 220 of 1
If that's the case then you can register the view as a persistent view.
!d discord.ext.commands.Bot.add_view
add_view(view, *, message_id=None)```
Registers a [`View`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View "discord.ui.View") for persistent listening.
This method should be used for when a view is comprised of components that last longer than the lifecycle of the program.
New in version 2.0.
Try this out, though I'm not sure what else could be causing your view to fail other than the bot restarting or an unhandled exception
@sick birch u available now?
!ytdl
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTube’s robots.txt file; (b) with YouTube’s prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
got it!
whats ur question
alr so I run this code locally and it works ```py
@commands.group()
async def help(self, ctx):
if ctx.invoked_subcommand is None:
embed = discord.Embed(
colour=0x2F3136
)
embed.add_field(name="Main", value=">help (shows this command)\n>crypto\n>music help\n>changelog", inline=False)
embed.add_field(name="Fun", value=">fun help\n>quote\n>cmds", inline=False)
embed.add_field(name="Admin", value=">admin help\n>media help", inline=False)
embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/949733110050857051/964831939989209138/tmgmidvitelogonowords.png")
await ctx.send(embed=embed)
but as soon as I put it on my hoster, all commands in this group just isn't found when called
I use something.host and I made sure the environment has everything pip installed correctly
here is an example of a command in this group py @help.command() async def admin(self, ctx): embed = discord.Embed( title=f"Admin Commands", description=f">ban\n>unban\n>mute\n>tempmute\n>unmute\n>banlist", colour=0x2F3136 ) embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/949733110050857051/964831939989209138/tmgmidvitelogonowords.png") await ctx.send(embed=embed)
Why me specifically?
cuz ik ur smart
Debatable
I do remember, yeah.
ye, man has active developer now, man is on another level to you peasants without it

@gusty flax u know why that aint working?
wdym it doesnt work.

CommandNotFoundError
That would do it
alr ty
fixed
bro something host is so slow 💀
@ashen notch
while ur here
do u recommend me duplicating each prefix command to have a slash command version?
@ashen notch?
hybrid commands exist 🤷
can u show me an example of one
!d discord.ext.commands.hybrid_command
@discord.ext.commands.hybrid_command(name=..., *, with_app_command=True, **attrs)```
A decorator that transforms a function into a [`HybridCommand`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.HybridCommand "discord.ext.commands.HybridCommand").
A hybrid command is one that functions both as a regular [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") and one that is also a [`app_commands.Command`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Command "discord.app_commands.Command").
The callback being attached to the command must be representable as an application command callback. Converters are silently converted into a [`Transformer`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.Transformer "discord.app_commands.Transformer") with a [`discord.AppCommandOptionType.string`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.AppCommandOptionType.string "discord.AppCommandOptionType.string") type.
Checks and error handlers are dispatched and called as-if they were commands similar to [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command"). This means that they take [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context") as a parameter rather than [`discord.Interaction`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction "discord.Interaction").
All checks added using the [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") & co. decorators are added into the function. There is no way to supply your own checks through this decorator.
New in version 2.0.
so basically just replace your normal prefix command
@commands.command()
async def mycommand(self, ctx: commands.Context, ...):
...
with a hybrid decorator
@commands.hybrid_command()
async def mycommand(self, ctx: commands.Context, ...):
if ctx.interaction is not None:
# command is being called as a slash command
else:
# command is being called as a prefix command
why do u need that if ctx.interaction
it's not like I care which way they call it
is this good? py @discord.ext.commands.hybrid_command(name="membercount", description="Shows members", with_app_command=True) @commands.command() async def membercount(self, ctx): embed = discord.Embed( title="Member Count", description=f"There are currently ``{ctx.guild.member_count}`` member(s) in ``{ctx.guild.name}``", colour=0x2F3136 ) embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/949733110050857051/964831939989209138/tmgmidvitelogonowords.png") await ctx.send(embed=embed)
🤷 maybe you wanna change a few things here and there, idk
try it and see. Also with_app_command defaults to True, so you don't need to add it
ok
!d await Client.wait_for
6.4. Await expression
Suspend the execution of coroutine on an awaitable object. Can only be used inside a coroutine function.
await_expr ::= "await" primary
``` New in version 3.5.
#bot-commands
how many times do u need to be reminded
obviously again 
hey guys, does anyone have a favourite vps to host their bots? tried searching in the searchbar but didn't seem to be any concrete answers. Looking for something relatively easy to use and wanted some feedback from people who i know'll give it straight rather than a sponsored yt vid lmao <33
i like to use digitalocean personally
I heard that digitalocean can be quite expensive? I'm looking to run about 4-5 bots in servers with around 100 users. Would it cost a fair bit to keep up 24/7?
one server with 100 users per bot you mean?
i meant like i'm gonna be running 5 bots on 5 different discord servers, and there's about 100 potential users that will interact with that bot
hopefully that clarifies it a bit, if not lmk 
discord servers i should add*
i think their plans are pretty cheap, you shouldn't have any problems but keep in mind the rate limiting since you will be on the same ip
ah ok, is there a way to get around the rate-limiting? or is it just buy another machine haha
oh looking into it it doesn't seem like it'll make enough requests to worry about that for now haha
How to install discord components
Are you using discord.py?
Yes
I am
You don't need to install anything then
It's already there for you, in discord.py
import discord
import datetime
from discord.ext import commands
from discord_components import Button, Select, SelectOption, ComponentsBot, interaction
from discord_components.component import ButtonStyle
this does not work
You don't need discord_components
That's a third party library and IIRC deprecated a while ago? (might be confusing it with another package, but still)
So I could just delete it?
Yes
https://github.com/Rapptz/discord.py/blob/master/examples/views/counter.py Here's a pretty simple example of using components with discord.py
Hey guys, I purchased a bot from someone and they just handed me a bunch of files and won’t help me. If someone could help me it would be greatly appreciated!
Can pay dm me@
''' py
`py
import discord
from discord.ext import commands
client = commands.Bot( command_prefix = '.')
.hello
@client.event
async def on_ready():
print( 'Bot connected' )
@client.commands( pass_context = True )
async def hello( ctx ):
await ctx.send('Hello. I am a Bot for discord')
Connect
token = open( 'Token.txt', 'r' ).readline()
client.run( token )`
does not work
why i have no idea
😭
!intents
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
I did not get anything
are you new to python?
Почти
I do not speak that language, sorry
I understand a little
Discord.py is a complex library and you'll need to know python basics before you can use it
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
you can find some free courses and books here
Спасибо
` py
import disnake
from disnake import CommandInteraction
from disnake.ext.commands import Bot
bot = Bot()
@bot.slash_command(
name="hello",
description="A simple hello command."
guild_ids=[...],
)
async def hello(inter: CommandInteraction) -> None:
await intel.send("hello!")
bot.run("2fb5f8a5e1758631227912159fde4c0da7218bfbf67c38b6c3750cbe434fb2e1") ```
did everything according to the instructions
not working again
😑
Ur supposed to put the guild IDs instead of the ellipsis (...)
guild_ids=[100000, 200000] etc
And reset your token
Don't share it with anyone
I know it's impossible
but i'm just tired
I want to make my own unique bot for my gaming clan
and I can't
I just want to see him at least online

something.host
LMAOOOOOO
That's not a token
so sad
It looks like hash tbh
Lightskin stare
^
I believe that's his only code
Ppl already explained what to do
- Use
InteractionBotinstead ofBot - Replace
guild_ids=[...]with list of actual ids - If you are trying to run it with the same "token" it is actually not a token
Oh yea ur right lol
understood nothing
@hasty rain even from here?
This would no longer seem to be true
Mm idk how to explain easier without going spoonfeed
Isn't it?
Why do u say so
A little
probably another digit was added for the user ID ig for that reason i could be wrong tho
iirc somewhere some disnake maintainer said that the timestamp part changed
hence they're removing or deprecating (i forgot) this thing https://github.com/DisnakeDev/disnake/blob/master/disnake/utils.py#L333-L355
!code
Because you are syncing it only with particular server
Then sync it globally 😃
Here comes my complete absence of knowledge about syncing in dpy
Iirc you need to remove copy_global_to line and remove guild kwarg from sync
async def setup_hook(self):
await self.tree.sync()
how do bots like GiveawayBot not have a presence
like not online, offline, or anything, it just shows their pfp
Show me? 🤔
Oh you might mean a webhook
They might be sending the messages from a webhook which wouldn't have a presence
Its a webhook
import discord
import asyncio
# Токен доступа бота
TOKEN = "токен"
# Инициализация клиента Discord
intents = discord.Intents.all()
client = discord.Client(intents=intents)
prefix_vis = "!"
# Функция, которая отправляет сообщения
async def send_message(channel, message_text, time, count, color=None):
paragraphs = message_text.split('\n')
for i in range(count):
await asyncio.sleep(time)
if color:
embed = discord.Embed(title="Отправленное сообщение", color=color)
for paragraph in paragraphs:
embed.add_field(name='\u200b', value=paragraph, inline=False)
await channel.send(embed=embed)
else:
message = '\n'.join(paragraphs)
await channel.send(message)
# Событие подключения бота к Discord
@client.event
async def on_ready():
print("Logged in as {0.user}".format(client))
# Событие при получении сообщения
@client.event
async def on_message(message):
global prefix_vis
# Проверяем, что сообщение написал не бот
if message.author == client.user:
return
# Проверяем, что сообщение начинается с префикса бота
if not message.content.startswith(prefix_vis):
return
# Получаем команду и аргументы из сообщения
command, *args = message.content.split()
# Проверяем, что команда - "!send"
if command == prefix_vis + "send" or command == prefix_vis + "sendemb":
# Проверяем, что переданы все аргументы
if len(args) < 2:
embed = discord.Embed(title="Ошибка", description="Недостаточно аргументов. Использование: !send <время_в_секундах> <количество> <сообщение>", color=0x2f3136)
await message.channel.send(embed=embed)
return
# Парсим аргументы
try:
time = int(args[0])
count = int(args[1])
message_text = ' '.join(args[2:])
except ValueError:
embed = discord.Embed(title="Ошибка", description="Неверные аргументы!", color=0x2f3136)
await message.channel.send(embed=embed)
return
# Создаем сообщение, которое нужно отправить
color = None
if command == prefix_vis + "sendemb":
color = 0x2F3136
send_message_task = asyncio.create_task(send_message(message.channel, message_text, time, count, color))
# Отправляем сообщение с подтверждением
if color:
embed = discord.Embed(title="Отправка сообщений", description=f"Сообщение '{message_text}' будет отправлено {count} раз с интервалом в {time} секунд.", color=color)
else:
embed = discord.Embed(title="Отправка сообщений", description=f"Сообщение '{message_text}' будет отправлено {count} раз с интервалом в {time} секунд.", color=0x2F3136)
await message.channel.send(embed=embed)
# Проверяем, что команда - "!prefix"
elif command == prefix_vis + "prefix":
# Проверяем, что передан аргумент
if len(args) < 1:
await message.channel.send("Usage: !prefix <new_prefix>")
return
# Изменяем префикс бота
prefix_vis = args[0]
await message.channel.send(f"Prefix changed to '{prefix_vis}'")
# Запускаем бота
client.run(TOKEN)
Can you change the code so that the paragraphs in the message argument (!send & !sendemb) are counted in the send_message function?
Example of how it shouldn't be:
Example of how it should be:
What error does it output?
I'll help you now
import discord
from discord import app_commands
MY_GUILD = discord.Object(id=12344)
class MyClient(discord.Client):
def __init__(self, *, intents: discord.Intents):
super().__init__(intents=intents)
# Создаем объект CommandTree и передаем ему клиент Discord
self.tree = app_commands.CommandTree(self)
async def on_ready(self):
# Вызываем метод setup_hook после того, как клиент Discord готов к работе
await self.setup_hook()
print(f"{self.user} has connected to Discord!")
async def setup_hook(self):
# Используем объект CommandTree для создания глобальной команды
self.tree.add_command(ping)
# Копируем глобальную команду в указанную гильдию
await app_commands.CommandTree(self).copy_global_to(guild=MY_GUILD)
# Синхронизируем команды в указанной гильдии
await app_commands.CommandTree(self).sync(guild=MY_GUILD)
# Создаем объект InteractionCommand и указываем название команды
@discord.app_commands.slash_command(name="ping")
async def ping(interaction: discord.Interaction):
# Отправляем сообщение в текстовый канал, в котором была выполнена команда
await interaction.response.send_message("Pong!")
intents = discord.Intents.default()
intents.members = True
client = MyClient(intents=intents)
client.run("TOKEN")
Corrected code
There are several problems in the above code that can lead to errors when executing commands.
copy_global_to and sync are not methods of the Command Tree object, but methods of the app_commands object. In order for these methods to work, you need to create an app_commands.Command Tree object and pass the Discord client to it as an argument.
In the ping method, you return the result of executing the Interaction Response.send_message method, but this method does not return anything. You need to use the Interaction Response.send method and pass the message text or discard object to it.Message as an argument.
copy_global_to and sync are methods of CommandTree
!d discord.app_commands.CommandTree.sync
await sync(*, guild=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Syncs the application commands to Discord.
This also runs the translator to get the translated strings necessary for feeding back into Discord.
This must be called for the application commands to show up.
Idk copying code from ChatGPT isn't a good idea
okey
For prefixed commands there's commands framework
hello, i have question please how to put all of them on the same line ? because I have a lot of bot.command() and I don't like it... I would like to gather them all
If you wanna have 10 commands you need 10 @bot.command()
Mm seems like single message responses, you could just make a dict and check if any of "commands" is in message via on_message. Not much point in using commands indeed
Hey guys, I just wanted to check that i'm doing this in a normal way and if anyone had any feedback.
So i'm sorting a /setup for my bot and rn it's /setup (pickachannel). I'm currently storing that channel inside of a database and then whenever i need to send a log, pulling that channel id back from the DB. Is that the correct way of doing things?
Yes
Though you may want to implement some sort of caching
You mean like storing the data so that I don't have to keep reaching out to the database? I'm not too sure how i'd do that 
Can be as simple as a dict
Or more complex with a redis caching layer
oh yeah I get how to cache it in that respect, but what I mean is i'm unsure how to cache it per-server. Rn I think i'm just a bit confused as to how the bot can keep data internally without other servers accidentally interacting with the wrong data
like if server1 does /setup channel and caches the data, how does server2 not also cache that data, as it's the same bot rather than referencing via a db
guild_id: channel_id dict?
as long as you have the guild id, you can uniquely id the data for each server
yeah I guess i'm just overcomplicating it in my head. i'll go play around with it and hopefully i'll get it haha
thanks though <33
Is your database local
how do i get user object from user display name?
Command argument or just from text?
arg
Typehint it with discord.User, just like this
async def cmd(ctx, user: discord.User)```
However I am not sure if it supports name-only conversion
without mentioning them
!d discord.ext.commands.UserConverter
class discord.ext.commands.UserConverter(*args, **kwargs)```
Converts to a [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User "discord.User").
All lookups are via the global user cache.
The lookup strategy is as follows (in order)...
Yeah 4th strategy is lookup by name, so will work
tyty
It supports name#discriminator
I never said it doesn't
You said you weren't sure, I just confirmed
Display name or just name wont work tho
Wrong
By name works?
As you can see
That doesn't make any sense, there can be multiple people with the same name no?
At least it is documented
We can look at the source
It probably selects the first matching
Sounds like something you shouldn't rely on too much then lol
Agreed
@rocky trench as expected https://github.com/Rapptz/discord.py/blob/master/discord/ext/commands/converter.py#L319-L320
discord/ext/commands/converter.py lines 319 to 320
predicate = lambda u: u.name == arg
result = discord.utils.find(predicate, state._users.values())```
@sick birch
or @vale wing
@discord.ext.commands.hybrid_command(name="giveaway", description="Sets up a giveaway")
async def giveaway(self, ctx, winners, time: TimeConverter = None, prize):
embed = discord.Embed(
title="Giveaway",
description=f"There will be only be {winners} winner(s)",
colour=0x2F3136
)
embed.add_field(name=f"This giveaway is for a prize of {prize}", value=f"Giveaway will last for {time}")
await asyncio.sleep(time)
await ctx.send(embed=embed)```How do I make it so that all the arguments are not optional
What
Remove the default value from time
Yep, you're right
How do I get discord.py 2.0 on replit
why do i get a invalid stynax thing
What are the ^^^ pointing at
Are you currently in the python REPL instead of a command prompt?
Can you send us a screenshot of your whole screen?
What does this error mean
It means that the parameter emoji is missing a typehint in the reactrole function
What is a typehint
Do you see what's different between the emoji parameter and all the other parameters in the reactrole function?
Particularly interaction and role
That's what a typehint is
Discordpy is telling you that you're missing a typehint for that parameter
I don’t know what to put
Ah
discord.Emoji
who is that semaphore?
Thanks
I have never seen this error before
Oh that's a slash command?
There's no emoji type
I think you just need users to enter in the emoji ID and parse it yourself
Yes
Really?
Yes
So I delete the whole emoji thing
You could probably build a custom transformer
I haven't used those yet but there are examples in the GitHub repository
Anyone familiar with this error from discord.py:```
ModuleNotFoundError: path attribute not found on 'src.events.member' while trying to find 'src.events.member.py'
trying to integrate cogs to my bot, here is how my hook function currently looks like:```py
async def setup_hook(self):
for cog_type in ["events", "commands"]:
for module in os.listdir(f"{constants.SRC_PATH}/{cog_type}"):
await self.load_extension(f"src.{cog_type}.{module}")
my directory structure is as follows:```
project-root/
.git/
.vscode/
src/
commands/...
events/...
main.py
bot.py
README.md
LICENSE
for more context, this is how my `src/events/member.py` looks like:```py
from discord.ext import commands
from ..bot import Bot
class MemberEventsCog(commands.Cog):
pass
async def setup(bot: Bot):
await bot.add_cog(MemberEventsCog)
if the running directory is src and running main.py path to cog will be events.member
and not src.events
the running directory is project root, since i do python -m src
tried events.member as well, then it's unable to find the module altogether
oh wait just looked at it
async def setup(bot: Bot):
await bot.add_cog(MemberEventsCog)
async def setup(bot: Bot):
await bot.add_cog(MemberEventsCog(bot))
yeah i solved both the problems, one of them is the one you sent, i forgot to instantiate the cog in the setup functions
but i also forgot to strip the .py extension when loading the module in the setup hook
aight cool
smh when am i gonna stop dealing with these silly bugs in this programming career
Hey guys, i'm trying to use SQL to manage my database but i'm struggling to wrap my head around it, is someone able to help me out rq?
I've got the current structure: uID, guildID, address, key but I want a way of flagging the admin account so my bot knows whether or not the /setup command needs to be ran. Would I just make an additional field called admin and set it to True/False?
If anyone has any other suggestions please lmk <33
Anyone know how to fix this
you cant annotate argument as discord.Emoji
What can I annotate
what's wrong? in back commands
@client.command()
async def afk(ctx, reasons: str):
global afkdict, afkrole, afkuser, member, guild, afkget
guild = client.get_guild(guild_id)
afkdict = {}
afkrole = discord.utils.get(guild.roles, name='AFK')
afkuser = ctx.author.id
afkget = guild.get_member(afkuser)
member = discord.member
if len(reasons) >= 1:
afkdict[afkuser] = reasons
await afkget.add_roles(afkrole)
await ctx.send(f'your **AFK** is now set to: `{reasons}`')
else:
reasons = 'None'
afkdict[afkuser] = reasons
@client.command()
async def back(ctx):
if afkrole in ctx.author.roles:
await afkget.remove_roles(afkrole)
await ctx.send(f'Welcome back! <@{afkuser}>')
afkdict.pop[afkuser]
else:
await ctx.send(f'You need to AFK first to run this command')
I have a strange one. I have a discord bot that I have running a loop, but my asyncio.sleep or time.sleep do not work with a variable inside of them. If I put a straight number, its fine.
await bot.wait_until_ready()
while True:
storage = urlGet('https://api.mozambiquehe.re/maprotation?version=2/')
mapname = storage['battle_royale']['current']['map']
rankedmap = storage['ranked']['current']['map']
ltmmapname = storage['ltm']['current']['map']
ltmmode = storage['ltm']['current']['eventName']
## It may look weird that I don't bother with ranked sec remaining, but since it tends to be so long, it doesn't seem worth comparing.
pubsVC = bot.get_channel(XXXX)
ltmVC = bot.get_channel(XXXX)
rankedVC1 = bot.get_channel(XXXX)
rankedVC2 = bot.get_channel(XXX)
await pubsVC.edit(name="Pubs : " + mapname)
await ltmVC.edit(name=ltmmode + " " + ltmmapname)
await rankedVC1.edit(name="P+ : " + rankedmap)
await rankedVC2.edit(name="G- : " + rankedmap)
secondsRemaining = min((storage['battle_royale']['current']['remainingSecs']),(storage['ltm']['current']['remainingSecs']))
print("Sleeping for " + str(secondsRemaining))
print(datetime.now())
await asyncio.sleep(float(secondsRemaining))```
!d discord.Emoji
class discord.Emoji```
Represents a custom emoji.
Depending on the way this object was created, some of the attributes can have a value of `None`...
Guys which annotation is supported?
If you want to accept an emoji you need to take a string
And either use a transformer or parse it yourself
I believe they are called "converters" tho
How would I parse it myself?
If I string do I use emoji id?
!d discord.Message
class discord.Message```
Represents a message from Discord.
x == y Checks if two messages are equal.
x != y Checks if two messages are not equal.
hash(x) Returns the message’s hash.
prefix = input("Enter The Prefix For The Bot |")
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix=prefix, intents=intents)
warnings = {}
@bot.event
async def on_ready():
print("Setting Status")
time.sleep(2)
activity = discord.Activity(type=discord.ActivityType.watching, name=f"Prefix = {prefix} |invite)
await bot.change_presence(status=discord.Status.online, activity=activity)
print("Bot is Ready!")```
ment to set prefix but doenst
and i realise i have nothing after the with block but even if i add something there it's still
the same error
Error?
Also dont use time.sleep in discord bot
!d asyncio.sleep use this instead
coroutine asyncio.sleep(delay, result=None)```
Block for *delay* seconds.
If *result* is provided, it is returned to the caller when the coroutine completes.
`sleep()` always suspends the current task, allowing other tasks to run.
Setting the delay to 0 provides an optimized path to allow other tasks to run. This can be used by long-running functions to avoid blocking the event loop for the full duration of the function call.
Example of coroutine displaying the current date every second for 5 seconds:
not error
its ment to set the prefix to what gets chosen at the start
but doesnt and just sets the prefix to !
Show full code
I actually found out a little later on the error was occurring before the sleep. I was using a min() function, but piping in strings absentmindedly, which led to junk for the sleep command itself. I am back to using asyncio sleep. I moved away from it for testing.
code?
Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "astro.py", line 268, in serverinfo
em.add_field(name="Region", value=str(guild.region.name).capitalize(), inline=False)
AttributeError: 'Guild' object has no attribute 'region'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Guild' object has no attribute 'region'
i trying to make a serverinfo command
my code
there is no region in Guild @slate swan
dont know what that means
remove the line that has region
guild object does not have a region attribute you can use, doubt it exists at all
The preferred locale for the guild. Used when filtering Server Discovery results to a specific language.
Changed in version 2.0: This field is now an enum instead of a str.
lowercase @discord.ui.button
also don't use asterisk import that's how you get conflicts
for example
from discord.ui import *
from discord import *
# error, there is both discord.ui.Button
# and discord.Button attributes
how will python know which one to use?
yeah, you're going to get an error eventually 🫠
you shouldn't really use asterisk imports at all
you never know what you are going to import
did you see this
you can just import it normally instead
why
sure
what's your code
what's your code right now
you didn't lowercase button though
class Menu(discord.ui.View):
@discord.ui.button(label="my_menu", style= discord.ButtonStyle.green)
async def my_menu(self, interaction: discord.Interaction, button: discord.ui.Button) -> None:
await interaction.response.send_message("hello you clicked me")
whats wrong with my code this is it
# Create a client object
client = discord.Client()
# Define a function to handle messages
@client.event
async def on_message(message):
# Check if the message was sent by the bot
if message.author == client.user:
return
# Check if the message starts with the word "hello"
if message.content.startswith('hello'):
# Respond with "Hello, {username}!"
await message.channel.send(f'Hello, {message.author.name}!')
# Run the bot
client.run('TOKEN')
/help
TypeError: Invalid class <class 'discord.message.Attachment'> used as an input type for an Option
Using a hosting service to host this website but keep getting this error
you don't have intents
your code is very outdated btw
Oh i used chatgpt
Oh
actually only for helping i guess
just use the discord.py documentation, chatgpt can't know about anything after 2021
k
maybe not with the new plugins lol
what is self in cogs used for?
it’s a class
When calling a method from a class instance (ie. instance.method()), the instance itself will automatically be passed as the first argument implicitly. By convention, we call this self, but it could technically be called any valid variable name.
class Foo:
def bar(self):
print('bar')
def spam(self, eggs):
print(eggs)
foo = Foo()
If we call foo.bar(), it is equivalent to doing Foo.bar(foo). Our instance foo is passed for us to the bar function, so while we initially gave zero arguments, it is actually called with one.
Similarly if we call foo.spam('ham'), it is equivalent to
doing Foo.spam(foo, 'ham').
Why is this useful?
Methods do not inherently have access to attributes defined in the class. In order for any one method to be able to access other methods or variables defined in the class, it must have access to the instance.
Consider if outside the class, we tried to do this: spam(foo, 'ham'). This would give an error, because we don't have access to the spam method directly, we have to call it by doing foo.spam('ham'). This is also the case inside of the class. If we wanted to call the bar method inside the spam method, we'd have to do self.bar(), just doing bar() would give an error.
.
If you have installed Python but forgot to check the Add Python to PATH option during the installation, you may still be able to access your installation with ease.
If you did not uncheck the option to install the py launcher, then you'll instead have a py command which can be used in the same way. If you want to be able to access your Python installation via the python command, then your best option is to re-install Python (remembering to tick the Add Python to PATH checkbox).
You can pass any options to the Python interpreter, e.g. to install the [numpy](https://pypi.org/project/numpy/) module from PyPI you can run py -3 -m pip install numpy or python -m pip install numpy.
You can also access different versions of Python using the version flag of the py command, like so:
C:\Users\Username> py -3.7
... Python 3.7 starts ...
C:\Users\Username> py -3.6
... Python 3.6 starts ...
C:\Users\Username> py -2
... Python 2 (any version installed) starts ...
I have a batch of bots to host. I'm wondering if there any other efficient way than specified in https://www.pythondiscord.com/pages/guides/python-guides/docker-hosting-guide/ to setup CI for hosting?
This guide shows how to host a bot with Docker and GitHub Actions on Ubuntu VPS
It should already, unless your initial command is blocking.
What about this guide doesn't work for you?
Seems to me like you can just spin up a bunch of containers for your bots
It does. I just want to know if there are alternatives to learn.
Whats the code for this command?
Are you using requests?
Don't use requests, use an async alternative like aiohttp
Docker is pretty much the most efficient and common way here
Show your code.
I see
please use formatting
I believe* that openai SDK is synchronous. Which means it's blocking.
or interact with their API directly
Oops that's the wrong lib
how do people get hacked when they join discord servers?
They scan QR codes
Which is something you should only do if it is the official discord login page
Hello, I have a problem with the reaction roles, when I want to create a reaction role and I click on the reaction it does not work... we all tried... please help me
How exactly can a QR grab person's credentials? I am not a web security expert, but logically discord authorisation QRs shouldn't point to some random URLs and app should check that
It approves your login, if someone else is sending / creating the QR to scan they are the ones getting your account logged in.
I'd rather not discuss the details on how this happens in a public channel as well, but the bottom line is don't scan any QR code if you aren't logging in to discord
Reaction roles are kinda an outdated mechanism
You should consider using UI components for this
Like Button/Select Menus
@meager chasm ok but I don't know how to do it...
Here is an example of a simple counter button
In essence, you have an instance of discord.ui.View which contains ui components, which you then pass to the view kwarg of Messageable.send
Usually it's recommended you subclass View and add the components using the decorators as shown in the example
So make sure you properly understand how classes work before this
when you go to discord's login page it gives you a QR code to scan to login faster using your phone
each QR code is specific to a session and the hackers generate it and get you to scan it to approve the session login
So key thing is not only discord can "register" those QRs
what do you mean? discord generates them and the hackers just send it to you
IIRC QR code skips 2fa entirely for the sake of convenience
And, of course, in the world of security, convenience is often a trade off to security
Yup
r u using discord py , pycord or nextcord
It’s ok thank you all 😉
Oh I was just overthinking
Discord displays a noticeable warning and disables the button for a couple seconds how can people even fall for such a thing 🤔
Nobody reads those
unfortunately
hi how can i get ctx.author activity?
i tried with ctx.author.activities[0].name, and it dont work
there's author.activity too
any errors when you try and fetch through activities though?
Command 'twitch' raised an exception: IndexError: tuple index out of range
@commands.hybrid_command(name="twitch", description="montrer aux membres que vous êtes en live sur Twitch!")
async def twitch(self, ctx, pseudo):
user= f"{pseudo}".capitalize()
url = "https://www.twitch.tv/"
await ctx.send ( ":arrow_right:" f"""**{user}** est en direct sur twitch et joue à "**{ctx.author.activities[0].name}**!"
{url}{pseudo}""")```
@fading marlin
however I do have an activity in progress on my profile i playing russian fishing 4
intents = discord.Intents.all()
bot = commands.Bot (command_prefix="!", intents=intents)
I call Discord issue
?
Any free discord bot hosting servers?
those are all very very sus
Using free hosting options like repl.it or Heroku for continuous 24/7 bot hosting is strongly discouraged.
Instead, opt for a virtual private server (VPS) or use your own spare hardware if you'd rather not pay for hosting.
See our Discord Bot Hosting Guide on our website that compares many hosting providers, both free and paid.
You may also use #965291480992321536 to discuss different discord bot hosting options.
Is this good code
import discord
class MyClient(discord.Client):
async def on_ready(self):
print('Logged on as', self.user)
async def on_message(self, message):
# don't respond to ourselves
if message.author == self.user:
return
if message.content.lower() == 'hello':
await message.channel.send('Hello!')
intents = discord.Intents.default()
intents.message_content = True
client = MyClient(intents=intents)
client.run('TOKEN')
hello
how i do install opus to use discord.opus.load_opus('opus')?
it should work but you have to identate await message.channel.send('Hello!')
are you on windows?
yup
it should be loaded for you automatically
OH MY GOD WE HAVE REACTION PERMS NOW
we have had them for a couple weeks now
I haven't been around much lately, I just noticed 😅
anyone know which discord libs currently support voice receive?
i know pycord does 🥴
there's a pr for that in dpy, but it doesn't seem like it's getting anywhere 😔
rip
Anyone able to help with my discord bot Q in help section. No rush but would love some professional insight
how do i get an delete all the emotes from a message?
what do you mean delete all emotes from a message
!d discord.Message.clear_reactions
await clear_reactions()```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Removes all the reactions from the message.
You must have [`manage_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_messages "discord.Permissions.manage_messages") to do this.
well yeah, but how would i get all the emotes on that message?
!d discord.Message.reactions
Reactions to a message. Reactions can be either custom emoji or standard unicode emoji.
ok cant seem to figure it out
@remove.group(
name='all',
description='Remove all reaction roles from a message',
brief='message',
usage=
'Syntax: (message link)\n'
'Example: https://discord.com/../',
extras={'perms': 'Manage Roles'}
)
@commands.has_permissions(manage_roles=True)
async def remove_all(self, ctx, message_link: str):
message = message_link.strip("/").split("/")[-1]
data = await self.bot.db.fetchval('SELECT message FROM reactionroles WHERE guild = $1', ctx.guild.id)
if data:
await message.clear_reactions()
await self.bot.db.execute('DELETE FROM reactionroles WHERE message = $1', message)
await ctx.send('deleted all the rrs')
this is what i got rn
how does it not work
no idea
it gives errors, sec, ill show u inna moment
Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "/home/void/cogs/Configuration.py", line 269, in remove_all
await message.clear_reactions()
AttributeError: 'str' object has no attribute 'clear_reactions'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/jishaku/features/invocation.py", line 168, in jsk_debug
await alt_ctx.command.invoke(alt_ctx)
File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/core.py", line 1642, in invoke
await ctx.invoked_subcommand.invoke(ctx)
File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/core.py", line 1642, in invoke
await ctx.invoked_subcommand.invoke(ctx)
File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/core.py", line 1636, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'str' object has no attribute 'clear_reactions'
@smoky sinew
looks like you are not fetching the message from the message link at all
you should use the Message converter instead
so message = await ctx.channel.fetch_message(message)?
no
async def remove_all(self, ctx, message: discord.Message):
data = ...
if data:
await message.clear_reactions()
...
well im not using message: discord.message
cus i can use id's and message links
hence why im doing message = message_link.strip("/").split("/")[-1]
and hence why message_link = str
yes... that's what the converter does for you
The lookup strategy is as follows (in order):
- Lookup by “{channel ID}-{message ID}” (retrieved by shift-clicking on “Copy ID”)
- Lookup by message ID (the message must be in the context channel)
- Lookup by message URL
and now my whole command is broken lol
how so
sec might just be my database
cus it keeps saying its expecting a str but got an int, and when i make it a string it just errors again
what is your code
hence why i was doing it with the split/strip method cus that worked
@reactionrole.group(
name='add',
description='Add a reaction role to a message',
brief='message, emote, role',
usage=
'Syntax: (message link) (emote) (role)\n'
'Example: https://discord.com/../ 🤍 White',
aliases=['create'],
extras={'perms':'Manage Roles'}
)
@commands.has_permissions(manage_roles=True)
async def add(self, ctx, message: discord.Message, emote: str, role: discord.Role):
await self.bot.db.execute('INSERT INTO reactionroles (message, role, emote, guild) VALUES ($1, $2, $3, $4)', message.id, str(role.id), emote, ctx.guild.id)
message = await ctx.channel.fetch_message(message)
await message.add_reaction(emote)
await ctx.success("You now successfully added a reaction role")
@reactionrole.group(
invoke_without_command=True,
name='remove',
description='Remove a reaction role from a message',
brief='message, emote',
usage=
'Syntax: (message link) (emote)\n'
'Example: https://discord.com/../ 🤍',
aliases=['delete', 'del'],
extras={'perms': 'Manage Roles'}
)
@commands.has_permissions(manage_roles=True)
async def remove(self, ctx, message: discord.Message, emote: str):
data = await self.bot.db.fetch('SELECT * FROM reactionroles WHERE message = $1 AND emote = $2 AND guild = $3', message.id, emote, ctx.guild.id)
if data:
await self.bot.db.execute('DELETE FROM reactionroles WHERE message = $1 AND emote = $2 AND guild = $3', message.id, emote, ctx.guild.id)
await message.clear_reaction(emote)
await ctx.success("You now successfully removed a reaction role")
@remove.group(
name='all',
description='Remove all reaction roles from a message',
brief='message',
usage=
'Syntax: (message link)\n'
'Example: https://discord.com/../',
extras={'perms': 'Manage Roles'}
)
@commands.has_permissions(manage_roles=True)
async def remove_all(self, ctx, message: discord.Message):
data = await self.bot.db.fetchval('SELECT message FROM reactionroles WHERE guild = $1', ctx.guild.id)
if data:
await message.clear_reactions()
await self.bot.db.execute('DELETE FROM reactionroles WHERE message = $1', message.id)
await ctx.send('deleted all the rrs')
what is the error message?
Traceback (most recent call last):
File "asyncpg/protocol/protocol.pyx", line 168, in prepare
File "asyncpg/protocol/codecs/base.pyx", line 206, in asyncpg.protocol.protocol.Codec.encode
File "asyncpg/protocol/codecs/base.pyx", line 111, in asyncpg.protocol.protocol.Codec.encode_scalar
File "asyncpg/pgproto/./codecs/text.pyx", line 29, in asyncpg.pgproto.pgproto.text_encode
File "asyncpg/pgproto/./codecs/text.pyx", line 12, in asyncpg.pgproto.pgproto.as_pg_string_and_size
TypeError: expected str, got int
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/discord/ext/commands/core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "/home/void/cogs/Configuration.py", line 228, in add
await self.bot.db.execute('INSERT INTO reactionroles (message, role, emote, guild) VALUES ($1, $2, $3, $4)', message.id, str(role.id), emote, ctx.guild.id)
File "/usr/local/lib/python3.8/dist-packages/asyncpg/pool.py", line 560, in execute
return await con.execute(query, *args, timeout=timeout)
File "/usr/local/lib/python3.8/dist-packages/asyncpg/connection.py", line 319, in execute
_, status, _ = await self._execute(
File "/usr/local/lib/python3.8/dist-packages/asyncpg/connection.py", line 1658, in _execute
result, _ = await self.__execute(
File "/usr/local/lib/python3.8/dist-packages/asyncpg/connection.py", line 1683, in __execute
return await self._do_execute(
File "/usr/local/lib/python3.8/dist-packages/asyncpg/connection.py", line 1730, in _do_execute
result = await executor(stmt, None)
File "asyncpg/protocol/protocol.pyx", line 183, in bind_execute
asyncpg.exceptions.DataError: invalid input for query argument $1: 1090814952253698059 (expected str, got int)
thats for reactionrole add
The attribute is a string type but u r giving int
because your column is a string
it isnt
CREATE TABLE "reactionroles" (
"role" VARCHAR(50),
"message" BIGINT,
"emote" TEXT,
"guild" BIGINT
);
just changed it to BIGINT, to prevent that
and its sending that error, hence why i was using that other method which made it work properly
cus whether if i used a link or an id, it just got the id for me and it worked that way
did you use ALTER and UPDATE to set it to a bigint?
i recreated the table
just to be sure
to make sure i didnt make a mistake
hence why im sticking to that cus that was proper with my db
sure
so this would work then
message = await ctx.channel.fetch_message(message)
if this is my code:
@commands.has_permissions(manage_roles=True)
async def remove_all(self, ctx, message_link: str):
message = message_link.strip("/").split("/")[-1]
data = await self.bot.db.fetchval('SELECT message FROM reactionroles WHERE guild = $1', ctx.guild.id)
if data:
message = await ctx.channel.fetch_message(message)
await message.clear_reactions(message)
await self.bot.db.execute('DELETE FROM reactionroles WHERE message = $1', message)
await ctx.send('deleted all the rrs')
Hey guys can anyone tell me why this code is not working
import discord
import openai
import os
openai.api_key = 'Api KEy'
def get_gpt_response(prompt):
response = openai.Completion.create(
engine="text-davinci-003",
prompt=prompt,
max_tokens=1024,
n=1,
stop=None,
temperature=0.5,
)
return response.choices[0].text.strip()
client = discord.Client(intents=discord.Intents.default())
@client.event
async def on_message(message):
if message.author == client.user:
return
if message.content.startswith('!gpt'):
prompt = message.content[4:]
response = get_gpt_response(prompt)
await message.channel.send(response)
client.run("Hello")
please ping me
Your message content intents aren't enabled
!intents
Intents are a feature of Discord that tells the gateway exactly which events to send your bot. Various features of discord.py rely on having particular intents enabled, further detailed in its documentation. Since discord.py v2.0.0, it has become mandatory for developers to explicitly define the values of these intents in their code.
There are standard and privileged intents. To use privileged intents like Presences, Server Members, and Message Content, you have to first enable them in the Discord Developer Portal. In there, go to the Bot page of your application, scroll down to the Privileged Gateway Intents section, and enable the privileged intents that you need. Standard intents can be used without any changes in the developer portal.
Afterwards in your code, you need to set the intents you want to connect with in the bot's constructor using the intents keyword argument, like this:
from discord import Intents
from discord.ext import commands
# Enable all standard intents and message content
# (prefix commands generally require message content)
intents = Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)
For more info about using intents, see discord.py's related guide, and for general information about them, see the Discord developer documentation on intents.
Or you can do it like that ^
Create an instance of Intents with the default() factorymethod and then set intents.message_content to True
Guys, how can I make the bot at least online?
!d discord
In order to work with the library and the Discord API in general, we must first create a Discord Bot account.
Creating a Bot account is a pretty straightforward process.
Чтобы работать с библиотекой и Discord API в целом, мы должны сначала создать учетную запись Discord Bot. Создание учетной записи бота — довольно простой процесс.
so he is
i mean code
he is always offline
we don't spoon feed here
I am not understanding what do you want to do
OK
Thanks a lot
🤣🤣🤣
File "<stdin>", line 1
even with a ready-made template does not work
either I'm the dumbest or the most unlucky
🤣🤣🤣
you should learn how to code first
doesn't work even with the template
now it’s clear why nothing works, I want to learn python
you should send the full traceback next time or we can't help
so i can code
i have a script
but it doesn't start
$ py -3 example_bot.py
File "<stdin>", line 1
$ py -3 example_bot.py
^
SyntaxError: invalid syntax
🤣🤣🤣🤣🤣
$ py -3 example_bot.py do you have this line in your code??
lol
maybe its a sign
funny
do you guys start and stop your program every time you tweak something
if not how do you debug ?
wdym
А разве можно изменять код когда приложение всключено?
logs can help you to understand what's happening
or if you're in development you can run the Bot with a debugger
i mean in debugging sometimes you gotta check how a certain line of code is working
its annoying to keep running and destroying code again and again
wdym destroying
I personally just add a print per variable
and check when a variable doesn't have a value that I want
mb i meant destroying running application(my bot's code)
you gotta do that I think
I personally recommend having a production bot and a testing bot
yeah but still don't you think it would be much easier if it can respond to commands with the realtime code
so like we can see the changes as soon as code changes
In order to work with the library and the Discord API in general, we must first create a Discord Bot account.
Creating a Bot account is a pretty straightforward process.
sure
maybe?
but coding directly on your main bot means if there's any bug while coding it people can abuse it
yeah actually i have separate production and testing ones
this seems cool
just running a command will work
I have never tried it, I just restart the bot
you could do something like
@commands.command()
async def reload_cog(self, ctx: commands.Context, cog: str):
if ctx.author.id != yourid: return
await bot.reload_extension(cog)
frick how can i forget, i have the same thing already in my bots code
lmao
actually i have recently started again
again?
is there something wrong in this ?
oh no
it is completely fine, I wast just confused
reload_extension and jishaku
is pretty much all you need
jishaku?
A discord.py extension including useful tools for bot development and debugging.
https://paste.pythondiscord.com/abodakubud
Issue is discord.ext.commands.errors.ExtensionFailed: Extension 'commands.balance' raised an error: AttributeError: 'Command' object has no attribute 'command'
It's happening for the add balance cmd
why don't you just use GroupCog
its fine for the first one, but wrong for the second one, in my other command files its completely okay then why bad here?
You overrided the balance var
it should be checkbalance right
alr, thanks
How to get it ?
!d discord.ui.Modal.on_submit @shrewd vapor
await on_submit(interaction, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Called when the modal is submitted.
simply override this in your modal
then use self.text_input (replace with whatever you named it)
He is for discord.py 1.7.3 ?
no
Oh
Bruh...
I can't update my code to change the version
see this page
All my commands are slash commands and I don't understand them in version 2.x.x
I started discord.py with 1.7.3 but tried to migrate to 2.0 3 months ago but failed after 1 weeks of trying
!d discord.app_commands.CommandTree
class discord.app_commands.CommandTree(client, *, fallback_to_global=True)```
Represents a container that holds application command information.
^
I have already looked, but I find it incomprehensible
the basic principle is:
- define slash command
- add command to tree
- synchronize tree to discord some time after your bot logs in ```py
bot = commands.Bot(...)
@bot.tree.command() # tree.command() does 1 and 2 at the same time
async def my_command(interaction: discord.Interaction):
await interaction.response.send_message("Hello world!")
@bot.event
async def setup_hook():
await bot.tree.sync() # running step 3 on login
bot.run(...)```
I want the slash commands for a whole file that contains all the code but I don't see how to put it and for the slash commands to be on all the servers of the bot
commands are defined as global by default, and sync() without any arguments will sync all your global commands
Is good ? py @bot.tree.command(name="help", description="View all commands")
er sure, but a help slash command is unusual to have
Oh xD
users already see descriptions of your commands, so you'd only need that if you can explain something better than the 100-character limit of each description
param: discord.Role
^^^^^^^^^^^^^^``` they're asking you to give your parameter a typehint
yeah same thing
reason : str ?
yes
its probably also worth renaming ctx to interaction: discord.Interaction so you dont get it confused with normal commands
i like to have one just for aesthetics reasons and to show off all the features since it's hard to scroll through a huge menu of commands
it should be interaction, member: discord.Member, reason: str = None
you will have to annotate everything so discord knows the type of the argument
member is just member#0000
Digit number is authorized in string ?
yes, string is any text
it's str, not string
refer to this
Just channel_id I edit ctx after
it depends on what you were using before, given that you are not using a converter it would be str again as that is the default for prefix commands
it's interaction.user, for the user who started the interaction
again replace all ctx instances with interaction
yes, they are fundamentally different in how they work anyway, so you would have been changing them either way
Hey, I got a Python script but i have no idea how to connect it with a discord bot. Any ideas on how to?
check out the docs for discord.Interaction and discord.InteractionResponse
@bot.event
async def on_message(interaction):
user = interaction.user
if interaction.channel.type is discord.ChannelType.private:
return
if interaction.channel.name != "verification":
return
if user.bot:
if not interaction.embeds:
await interaction.delete()
elif not user.bot:
if interaction.content != ".verif":
if (interaction.user.guild_permissions.ban_members):
return
message = await interaction.reply("Deleting because it's not .verif")
await message.delete(delay = 5)
await interaction.delete()
if ".verif" in interaction.content:
guild_id = interaction.guild.id
role_id = database_verif.get_role_id(guild_id)
role = discord.Object(id=role_id)
await interaction.user.add_roles(role)
embed = discord.Embed(title = "You have passed the verification", description = "Role successfully added")
embed.set_footer(text = f"Added for {interaction.guild.name}")
message = await interaction.reply(embed=embed)
await message.delete(delay = 2)
await interaction.delete(delay = 2)
if database_verif_channel.get_channel(guild_id) is None:
return
channel_send = database_verif_channel.get_channel(guild_id)
embed_verif = discord.Embed(title = "Verification Successful Passed", description = f"Verification Successful Passed for:\n<@{interaction.user.id}> | {interaction.user}")
embed_verif.set_footer(text = f"By {interaction.guild.name}")
message = await channel_send.send(embed=embed_verif)```Is my on_message 💀
on_messages do not have interactions though
it would be async def on_message(message):
@bot.event
async def on_message(message):
user = message.user
if message.channel.type is discord.ChannelType.private:
return
if message.channel.name != "verification":
return
if user.bot:
if not message.embeds:
await message.delete()
elif not user.bot:
if message.content != ".verif":
if (message.user.guild_permissions.ban_members):
return
message = await message.reply("Deleting because it's not .verif")
await message.delete(delay = 5)
await message.delete()
if ".verif" in message.content:
guild_id = message.guild.id
role_id = database_verif.get_role_id(guild_id)
role = discord.Object(id=role_id)
await message.user.add_roles(role)
embed = discord.Embed(title = "You have passed the verification", description = "Role successfully added")
embed.set_footer(text = f"Added for {message.guild.name}")
message = await message.reply(embed=embed)
await message.delete(delay = 2)
await message.delete(delay = 2)
if database_verif_channel.get_channel(guild_id) is None:
return
channel_send = database_verif_channel.get_channel(guild_id)
embed_verif = discord.Embed(title = "Verification Successful Passed", description = f"Verification Successful Passed for:\n<@{message.user.id}> | {message.user}")
embed_verif.set_footer(text = f"By {message.guild.name}")
message = await channel_send.send(embed=embed_verif)```Is good now ?
interactions only apply to slash commands, right-click commands (e.g. right-click on user or message), button/select interactions, and modals
no there is no such thing as Message.user
Where cani find project’s working?
message.author ?
what kind of script?
yes
python, can i send it here?
send it using https://paste.pythondiscord.com preferrably
oki
it's better to integrate the script into the discord bot, or use the script as a module that you can import in your bot code
Never used it, but I think I got it right
https://paste.pythondiscord.com/raw/ucanuceqef
you could probably just integrate this into your bot
though there is probably a way to simplify this script by a lot
!d discord.InteractionResponse @shrewd vapor a bot can have different responses to the command
class discord.InteractionResponse```
Represents a Discord interaction response.
This type can be accessed through [`Interaction.response`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.Interaction.response "discord.Interaction.response").
New in version 2.0.
the one you are probably looking for is InteractionResponse.send_message, you can also send things like modals
for starters, put all the NPCs into a dictionary, that way your main code will only be a few lines long
if you use a loop
Will it make it any better, or is it just to have less lines?
it's interaction.response.send_message
if you want to change an npc's stats or add a new npc, it will only be one line of code that you are changing
and having less lines is usually better in terms of code readability
for example:
npc_list = {
"Kaioken Student": 700,
"Krillin": 1000,
...
}
def view_npc_stats():
for npc_name, npc_stats in npc_list.items():
print(f"{npc_name} - {npc_stats}") # Kaioken Student - 700, ...
def get_npc_name_from_stats(stats):
for npc_name, npc_stats in npc_list.items():
if npc_stats == stats:
return npc_name
@slate swan
you can then easily import this code, or include it in your main bot file
So basically continue on adding the NPCS on the npc_list, then add them on npc_stats like you did with kaioken student?
My bot enter in a new generation
no, the kaioken student was just an example
it would print all of them out if you looped over npc_list
hence why i included "..."
My log functions no longer work 💀
npc_list = {
"Kaioken Student": 700,
"Krillin": 1000,
"Kid Gohan": 1400,
}
could this work?
sure
and just continue on adding the NPCs into the list
yup
that finna take long ahh time 😭
Can I just integrate it into my bot as it is rn?
ive watched YT vids on how to intergrate a code into a bot, and nun of them worked
on_message_delete
And
on_message_edit doesn't work
I don't have error just he not send the message
That sounds like average YouTube tutorials
i just wrote the whole thing, took 3 minutes 
Do you have message_content intent
cuz i had to get the npc names etc
i sent it in your dms to not flood chat
Appreciate it alot 🙏
@bot.event
async def on_message_delete(message):
guild_id = message.guild.id
if database_log_message.get_channel(guild_id) is None:
return
channel_send = database_log_message.get_channel(guild_id)
if message.author == message.author.bot:
return
if message.content == ".verif":
return
if message.embeds:
if message.content is None:
await channel_send.send(message.embeds)
return
embed=discord.Embed(title = f"Message deleted in {message.channel}", description = f"{message.author.name} Message deleted", color=discord.Color.dark_purple())
embed.add_field(name="Message :",value=message.content, inline=False)
embed.add_field(name = "Account created :", value = message.author.created_at.strftime('%d %B %Y at %H:%M'))
await channel_send.send(embed=embed)
@bot.event
async def on_message_edit(message_before, message_after):
guild_id = message_before.guild.id
if database_log_message.get_channel(guild_id) is None:
return
channel_send = database_log_message.get_channel(guild_id)
if message_before.embeds:
if message_before.content is None:
await channel_send.send(message_before.embeds)
return
embed = discord.Embed(title = f"Message edited in {message_before.channel}", description = f"{message_before.author.name} message edited", color = discord.Color.dark_purple())
embed.add_field(name = "Message Before :", value = message_before.content, inline = False)
embed.add_field(name = "Message After :", value = message_after.content, inline = False)
await channel_send.send(embed=embed)```
I have this for the logs
what does this mean?
It means the process finished with no errors
Why didnt my bot go online then
💀
You should send your code when there's something wrong with it
good idea
How are you running the script?
i pressed on "run"
And you're sure you are running main.py and not responses.py right?
Oh that helped
Now i got hella errors
@vocal snow any idea how i can get the file back?
least confusing pycharm error message
I aint good with python
i don't use pycharm or venvs, so i would recommend re-creating your project with the same files
is this enough to make the bot go online?https://paste.pythondiscord.com/raw/uhelasanuq
npc_list: = {
this is not valid syntax, and it would also never run while your bot is running becauseclient.run won't stop
instead you should just import responses
and use responses.function_name wherever you need it
so change this out with import responses ?
how bout this error, i copied what u wrote in dms
📸muddy caught spoonfeeding
Ohhhhh
@slate swan does it work?
Rn im just trying diff things, and nun of it is working 💀
why not?
I have no Idea, I think the issue is whats in "main.py"
it wont get the bot online
in dms?
no just here
like this?
this sum i did with a YT tut 😭
sure
Python way too difficult
you will get better with practice
ima give up on it, ive tried 5 vids now
nun of them helped, each time a new error came
🤔 how can I improve the looks of this? loll
Too much scrolling. and idk if I want to put 'pages' in
Only issue is that I need to integrate this into a bot, and add a prefix. Nothing else
it works on replit, but not on python
Hey @slate swan!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
Is it possible to force an embed to be 2 columns? not 3 or 4?
why are you using that code though
yeah, just set it to inline
That’s the only code I could see working, it also worked in replit
column 1 (inline = False)
column 2 (inline = True)
column 3 (inline = False)
column 4 (inline = True)
I don’t see anything else working better
the other one worked fine? you still haven't explained what was wrong with the other one
i could have still helped
The issue is, idk myself what’s wrong with it. It didn’t want to work
The one I sent now works too, I just need to integrate it into a bot
what do you mean by "didn't want to work"
what is the error message or how did it not work
The bot didn’t go online
No matter what
async def leave(ctx):
voice_client = ctx.message.guild.voice_client
if voice_client.is_connected():
await voice_client.disconnect()
await ctx.send('Bot left the voice channel')
else:
await ctx.send("The bot is not connected to a voice channel.")```
can someone help me, my bot can't leave voice channel when the voice channel name contain emoji
what was your code? were you running the main.py file?
I was I think ghe ss if the code in here lemme find it
You can help me please my logs doesn't work
maybe if the old thing worked in replit, try running the new code in replit
Should I combine those 2 codes and put it in replit, or make their own tab
make what
Replit
make replit? i don't understand
Should I put the new code in replit and see if it’s gonna work
ok
What does this mean?
don't make the tree manually
So what do I do
remove it?
Thanks
I need help please he don't work with discord.py 2.2, he work with discord.py 1.7.3
@bot.tree.command(description="Kicks a member")
@bot.event
async def on_message_delete(message):
guild_id = message.guild.id
if database_log_message.get_channel(guild_id) is None:
return
channel_send = database_log_message.get_channel(guild_id)
if message.author == message.author.bot:
return
if message.content == ".verif":
return
if message.embeds:
if message.content is None:
await channel_send.send(message.embeds)
return
embed=discord.Embed(title = f"Message deleted in {message.channel}", description = f"{message.author.name} Message deleted", color=discord.Color.dark_purple())
embed.add_field(name="Message :",value=message.content, inline=False)
embed.add_field(name = "Account created :", value = message.author.created_at.strftime('%d %B %Y at %H:%M'))
await channel_send.send(embed=embed)
@bot.event
async def on_message_edit(message_before, message_after):
guild_id = message_before.guild.id
if database_log_message.get_channel(guild_id) is None:
return
channel_send = database_log_message.get_channel(guild_id)
if message_before.embeds:
if message_before.content is None:
await channel_send.send(message_before.embeds)
return
embed = discord.Embed(title = f"Message edited in {message_before.channel}", description = f"{message_before.author.name} message edited", color = discord.Color.dark_purple())
embed.add_field(name = "Message Before :", value = message_before.content, inline = False)
embed.add_field(name = "Message After :", value = message_after.content, inline = False)
await channel_send.send(embed=embed)```
I really need help please, he don't work with discord.py 2.2.2
what do you mean doesn't work
"not working" is a pretty vague explanation but it seems you said earlier it didnt send any message, so i would suggest using print statements to figure out how far its getting into your event handler
also make sure you have the message_content intent enabled since that's new to 2.0
did u enable intents on dev portal?
Yes all is activate
No error
@bot.event
async def on_message_edit(message_before, message_after):
is thhis such a thing?
!d discord.on_message_edit
discord.on_message_edit(before, after)```
Called when a [`Message`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Message "discord.Message") receives an update event. If the message is not found in the internal message cache, then these events will not be called. Messages might not be in cache if the message is too old or the client is participating in high traffic guilds.
If this occurs increase the [`max_messages`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client "discord.Client") parameter or use the [`on_raw_message_edit()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_raw_message_edit "discord.on_raw_message_edit") event instead.
The following non-exhaustive cases trigger this event...
ok it is
Yes
i was just confused on event name lol
xD
try printing message content
i would suggest using print statements to figure out how far its getting into your event handler
right now we don't know why its not sending a message, there's too many reasons for that
if database_log_message.get_channel(guild_id) is None: returnif message.author == message.author.bot: returnif message.content == ".verif": return- the event handlers never ran because your bot was restarted after the messages were already sent
...
He work now
My database is empty for channel log, I have defined and he work
How to use discord.ui.Modal.on_submit ?
you simply override it
that's not related to that error at least
it's an async iterator, you will have to loop over it
async for ban_entry in interaction.guild.bans():
Its related to question how to overrite on_submit
@bot.tree.command(name="unban", description="Unban a member")
async def unban(interaction, *, member : str, reason : str):
if (not interaction.user.guild_permissions.ban_members):
await interaction.response.send_message(f"You are not authorized to use this command {interaction.user.mention}")
return
banned_users = await interaction.guild.bans()
member_name, member_discriminator = member.split("#")
for ban_entry in banned_users:
user = ban_entry.user
if (user.name, user.discriminator) == (member_name, member_discriminator):
await interaction.guild.unban(user)
embed=discord.Embed(title=f"{user} as been unban", inline=False)
embed.add_field(name="Reason :", value=f"{reason}")
embed.set_footer(text=f"{interaction.user} | ID : {interaction.user.id}")
await interaction.reply(embed=embed)```
see the code i sent above
remove banned_users
actually you might not need to add paranthesis at all
@bot.tree.command(name="ban", description="Ban member from guild")
async def ban(interaction, member : discord.Member, *, reason : str):
if (not interaction.user.guild_permissions.ban_members):
await interaction.response.send_message(f"You are not authorized to use this command {interaction.user.mention}")
return
await member.send(f"You have been banned by {interaction.user} from {interaction.guild.name}.\nReason : {reason}.")
await member.ban (reason = reason)
await interaction.response.send_message(f"{member.id} has been banned !")```
And for ban ?
what about it
Unknown interaction means your command didnt respond in time, discord only gives you three seconds
if you need more time, defer and followup: py await interaction.response.defer() ... # do whatever in between await interaction.followup.send("a message")
How I can ban by id ?
create a discord.Object with the given ID and pass it to Guild.ban()
@bot.tree.command(name="ban", description="Ban member from guild")
async def ban(interaction, member_id : discord.Object, *, reason : str):
if (not interaction.user.guild_permissions.ban_members):
await interaction.response.send_message(f"You are not authorized to use this command {interaction.user.mention}")
return
await member_id.send(f"You have been banned by {interaction.user} from {interaction.guild.name}.\nReason : {reason}.")
await interaction.guild.ban (member_id, reason = reason)
await interaction.response.send_message(f"{member_id.id} has been banned !")
Is good ?
or since all User objects implement abc.Snowflake, you can just typehint it as discord.User and pass that instead
What ?
@bot.tree.command(name="ban", description="Ban member from guild")
async def ban(interaction, member_id : discord.User, *, reason : str):
if (not interaction.user.guild_permissions.ban_members):
await interaction.response.send_message(f"You are not authorized to use this command {interaction.user.mention}")
return
await member_id.send(f"You have been banned by {interaction.user} from {interaction.guild.name}.\nReason : {reason}.")
await interaction.guild.ban (member_id, reason = reason)
await interaction.response.send_message(f"{member_id.id} has been banned !")```
Is good for you ?
@bot.tree.command()
async def unban(interaction: discord.Interaction, user: discord.User) -> None:
await interaction.guild.unban(user)
this should be all you need for an unban command
@smoky sinew yooo
hi
any ideas on how to make this better https://paste.pythondiscord.com/raw/iropuritum
bruh
?
that wouldnt work
did you test it on replit?
i wrote it fully, and it wouldnt load in on repit
its cuz thats a rebirth calculkator
this was already my idea on how to make it better
Yea but I couldnt get it to wrok cuz it was missing the actual calculator
did you add it?
This all I got
I tried to yea
how did it not work?
It just wouldnt load, I think the issue is I couldnt get this to play all together
everything after that
Why?
did u look at the full code?
discord.Interaction.response.send_message()```
and
```py
discord.Interaction.followup.send()
aren't working
you need an instance
use your interaction variable
I did
async def clear(interaction: discord.Interaction, messages:Optional[int]=None, member:Optional[discord.Member]=None):
discord.app_commands.errors.CommandInvokeError: Command 'clear' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
what is your 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 floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
did u have to ping me for that
you probably want to do InteractionResponse.defer and Interaction.followup.send
discord bots can be programmed with python? I had no idea lmao haha
what else except python tho
pretty much every language
That's cool dude thanks
https://discord.com/developers/docs/topics/community-resources#libraries
this is official list of libraries that have valid rate limit implementations
ay thanks
How do I make my bot only listen for commands/events/etc in one server?
Hey there, im trying to use an emoji in a button but it throws Invalid emoji error. This is my code
button = Button(label=f"{ticketpanelconf['button_text']}", style=discord.ButtonStyle.green, emoji=f":{ticketpanelconf['button_emoji']}:")
and this is the data of button_emoji:
button_emoji: incoming_envelope
Anybody knows how to fix it? The format of the emoji looks good to me
it has to be the unicode character
sorry, so what i should use?
thats not how to use emojis via bot
you need to get form like this: !this
to get such form you need to place \ before emoji in discord
This a discord emoji so its :emoji_name:
🤦
No you use it Like this inside discord application
If you want a bot to use Emoji you need to give him this format i provided
@commands.command()
async def embed(self, ctx):
def check(message):
return message.author == ctx.author and message.channel == ctx.channel
await ctx.send('Waiting for a title')
title = await self.bot.wait_for('message', check=check)
await ctx.send('Waiting for a description')
desc = await self.bot.wait_for('message', check=check)
await ctx.send('What channel should I send this in? (please respond with channel id)')
destination = await self.bot.wait_for('message', check=check)
embed = discord.Embed(title=title.content, description=desc.content, color=0x1ABC9C)
embed.set_author(name="SC News Team", icon_url="https://i.imgur.com/MJnM3LU.png")
channel = self.bot.get_channel(destination)
await channel.send(embed=embed)
trying to get a bit of help with some code.
trying to get it so the user can input the channel id in response to the "await.ctx.send(what channel) prompt but having some trouble getting it to use that channel id
any ideas maybe?
destination is a string
you will have to convert it to an integer
Oh interesting, not something I have encountered before
well yes, that is because IDs on discords are stored as integers
whereas the text of a message can contain anything, therefore it is a string
you cannot compare the two (cough cough javascript)
Looking at it online but a bit confused how I would use int() in this setting
it would be int(destination.content) as destination is a Message
you will probably want to add isnumeric or isdigit to the check too
like this?
Obviously missing something
a second closing paranthesis?

that would probably help huh
sometimes its the simple things
@smoky sinew getting this now
Is there something I need to change with
I tried followup.send and it did not work but I'll try defer
you can't use it alone
you hyave to use it in combination with defer
did you do .content?
I did not
provide an example
that goes here right
no
wait_for.content?
wait_for returns Message and you use .content on it
so int(dest.content)
await interaction.response.defer()
# do something that takes a while
await interaction.followup.send("done")
with that it doesn't send any error codes but it sends it back to the same channel, not the channel whose ID was sent.
can you show your full code
wait maybe I reverted something one sec
yup that was the case, I had switched channel.send back with ctx.send to test something, i put it to channel.send and it did it right
@smoky sinew or anyone who is around to look
here is the entire code
@commands.command()
async def embed(self, ctx):
def check(message):
return message.author == ctx.author and message.channel == ctx.channel
await ctx.send('Waiting for a title')
title = await self.bot.wait_for('message', check=check)
await ctx.send('Waiting for a description')
desc = await self.bot.wait_for('message', check=check)
await ctx.send('Please provide me with the image link for this post, if no image is needed just say none.')
newsimage = await self.bot.wait_for(ctx.message.attachments, check=check)
await ctx.send('What channel should I send this in? (please respond with channel id)')
dest = await self.bot.wait_for('message', check=check)
await ctx.send('Who should I tag?')
whototag = await self.bot.wait_for('message', check=check)
await ctx.send('What is the tag preview?')
tagpreview = await self.bot.wait_for('message', check=check)
embed = discord.Embed(title=title.content, description=desc.content, color=0x1ABC9C)
embed.set_author(name="SC News Team", icon_url="https://i.imgur.com/MJnM3LU.png")
embed.set_image(url= newsimage)
channel = self.bot.get_channel(int(dest.content))
await channel.send(embed=embed)
await channel.send(f"@", whototag, " ", tagpreview)
I am running into two issues.
For the image portion where it asks
await ctx.send('Please provide me with the image link for this post, if no image is needed just say none.')
newsimage = await self.bot.wait_for(ctx.message.attachments, check=check)
and throws it into the embed like this
embed.set_image(url= newsimage)
it returns this error
Traceback (most recent call last):
File "C:\Users\SCNewsBotCore\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\SCNewsBotCore\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\SCNewsBotCore\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'list' object has no attribute 'lower'
I guess I will start with the first issue
I have a feeling the issue lies in how I am using ctx.message.attachments inside of self.bot.wait_for() but I am unsure of how to proceed
await self.bot.wait_for(ctx.message.attachments)
this is the part that's wrong, you must pass an event to wait_for
e.g. like wait_for("message") or wait_for("member_join"), things like that
got it, so then how would I get it to capture the attachment?
or would it theoretically just do it?
if an image is attached, you can just wait for the message event and add a check so that an image must be present
then use Message.attachments to access it
And that would go into where the embed is supposed to access the image right? here
embed.set_image(url= newsimage)
what is newsimage though
await ctx.send('Please provide me with the image link for this post, if no image is needed just say none.')
newsimage = await self.bot.wait_for('message', check=check)
@smoky sinew just the identifier name for what goes in the embed
no you would need newsimage.content
it just didn't pull it
it posted the embed with no image
it seems like you're not posting the actual link, but an attachment
so the message content in empty
yeah I would like to be able to pull it off the attachment
Is that even possible?
chosen_image = await self.bot.wait_for("message", check=lambda m: all([
m.author == ctx.author,
m.channel == ctx.channel,
len(m.attachments) == 1
])
embed.set_image(url=chosen_image.attachments[0].url)
try this
on it
Wait, I would retain the await ctx.send so it has a prompt correct?
duh ignore me
@smoky sinew worked 
u have achieved god status in my eyes for all the help you've provided btw
nice, glad it works
im trying to make a command using the discord.Member.timeout function, but I need to make it so I can use different times of the timeout, up to 28 days
anyone got an idea how, cus it uses datetime.timedelta
so for instance, if i do ,timeout (user) 1d spamming (third warning), it would time the user out for 1 day and then put the "spamming (third warning) as the reason
bot/utils/time.py lines 16 to 24
_DURATION_REGEX = re.compile(
r"((?P<years>\d+?) ?(years|year|Y|y) ?)?"
r"((?P<months>\d+?) ?(months|month|m) ?)?"
r"((?P<weeks>\d+?) ?(weeks|week|W|w) ?)?"
r"((?P<days>\d+?) ?(days|day|D|d) ?)?"
r"((?P<hours>\d+?) ?(hours|hour|H|h) ?)?"
r"((?P<minutes>\d+?) ?(minutes|minute|M) ?)?"
r"((?P<seconds>\d+?) ?(seconds|second|S|s))?"
)```
this especially is useful
uh
checking if a user is timed out?
I also have another unrelated question and was wondering how I can change the status of my bot
*presence
Can somone put a bot on my@server if they click on my@invite
!d disnake.ext.commands.Bot.change_presence
await change_presence(*, activity=None, status=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Changes the client’s presence.
Changed in version 2.6: Raises [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.11)") instead of `InvalidArgument`.
Example
```py
game = disnake.Game("with the API")
await client.change_presence(status=disnake.Status.idle, activity=game)
```...
but don't do this on on_ready events


