#discord-bots
1 messages · Page 398 of 1
I do?
yes, you use requests to make an api request to retrieve the information and then parse it
the issue here is that u need to find a free riddles api
or u can just hard code the riddles into a list? into a file? or whatever
https://www.riddle.com/help/api you can use this maybe
Riddle.com - Help Center
I want alot of riddles so it can send 1 daily for along time without a limit like that
also use aiohttp not requests
This is confusing
confusing now, you just have to put in the effort
read https://docs.aiohttp.org/en/stable/ (we don't use requests in this case because with a discord bot its async; if u use requests, it'll be blocking meaning you'll be halting other processes)
Would this work? Mind you I am using ChatGPT to help me as I don't know much py yet
https://paste.pythondiscord.com/XCTA
Looks like it works
surprised it gave u an actual working api
omg 😂
"nsfw": false,
"religious": true,
"political": false,
"racist": false,
"sexist": false,
"explicit": true
},
looks like they give these settings that u can change; i guess put false for explicit
I just figured true or false would be the same for most other things
I'll test it and have it send a riddle every time the command is sent so i can do it faster
alright, but u didn't fix the actual problem; you kinda just walked around it
you still don't know what ur actually doing
Yeahh that is true
play around with the aiohttp module and the examples they have
Alright, I'll have to do that tomorrow. It's getting pretty late and it's freezing so I want to get under the covers.
have a good night
You too, or have a good day, whichever fits
Quick thing, how do I have it were the bot can be in 2 servers and both using the riddle-start command, cuz I have it in one of my buddies and when he did it, it said
The daily riddles are already running in Bot testing > the-riddler!
that's what u get for copying chatgpt code without understanding it
check riddle_start function
this part?```python
send_daily_riddle.start()
else:
await interaction.response.send_message(f"The daily riddles are already running in <#{riddle_channel_id}>!")
And I won't be able to understand it for a bit until I learn python, which I'm trying to do while using ChatGPT
async def join(ctx):
if (ctx.author.voice):
channel = ctx.message.author.voice.channel
voice = await channel.connect()
source = FFmpegAudio('The Weeknd.mp3')
player = voice.play(source)``` when i run i get error anything wrong?
python for me was a lot easier than c#, c or cpp
Yeah, definitly. I started learning a couple months ago for a bit on my raspberry pi and was able to learn some things very quickly. But for bots its definitly alot more complicated
Yeah I can't help you there, the bit of code I did learn wasn't related to bots at all and the small bit I have learned isn't related to that
is there a way to fix that like i want the bot to only send the embed not the !report https://paste.pythondiscord.com/FKUA
the code is in the link
just fix that in general loll ive been trying to find for hrs and i cant
Send
i fixed it but now im trying to make it play different audio
@client.command(pass_context = True)
async def play(ctx, arg):
voice = ctx.guild.voice_client
source = FFmpegPCMAudio('The Weeknd.mp3')
player = voice.play(source)
i have another audio im trying to make there be different audio and want it so that someone can choose a different one
use choices
aight
here
Do you use only the old prefix or also /cmds
im only using prefix
aight
ill learn later maybe slash cmds
Fwiw it's against tos to play music you don't have copyrights to
Which again is against tos if you don't have rights to it
@client.command(pass_context=True)
async def play(ctx: commands.Context, song: str):
voice = ctx.guild.voice_client
if not song:
return await ctx.send(f"Enter a Song.")
if song == "The Weeknd.mp3".lower():
source = FFmpegPCMAudio(songs[0])
player = voice.play(source)
elif song == "Cozy.mp3".lower():
source = FFmpegPCMAudio('Cozy.mp3')
player = voice.play(song[1])
await ctx.send(f"I´m playing {song}")```
yes
thanks so much
yo
@client.command(pass_context = True)
async def join(ctx):
if (ctx.author.voice):
channel = ctx.message.author.voice.channel
voice = await channel.connect()
source = FFmpegPCMAudio('The Weeknd.mp3')
player = voice.play(source)
i also have this code but it doesnt switch to the song im trying to switch it to
Use Buttons or something
k
Or do you mean you execute the /play command?
when i choose to play my other song it stays on the weeknd
You can, but it will break tos
and it is against the rules of this server to help people break tos
ight
You can play songs that you have the copyright for or that you have purchased or been given the rights to stream.
Unless you're purchasing commercial rights, you've only purchased a limited license for personal use
i said ight im not playing it
File "c:\Users\onyob\OneDrive\Documents\Fortnite\Fortnite.py", line 110, in <module>
@has_permissions(kick_members=True)
^^^^^^^^^^^^^^^
NameError: name 'has_permissions' is not defined
has_permissions isn't something python knows natively
You need to import it or reference it from an imported module
!d discord.ext.commands.has_permissions
@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)...
You want to use @discord.ext.commands.has_permissions(**perms)
guys
theres anyone who knows how to host for free 24/7
becuase I hosted it 24/7 but when visual code is closed then commands stop working
!hosting
Using free hosting options like repl.it 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.
tl:dr is no, these things cost money to run and if you think you're getting it for free someone is scamming you
i mean
ig ot it from botghost to run python but it only run it commands
so i cant make it for free 24/7???
Not without getting scammed. Think about it.
This costs money. Who is going to spend their money to run your stuff for you
Thankfully there is a process where you can exchange your time for currency that can be then be used to rent a reliable host
That is largely a matter of opinion and preference, and also varies based on your needs

I have very good experiences with Hetzner, but there's a bunch of reliable offerings out there
I'll check it out, thanks.
np i fixed it already thanks
from discord.ext.commands import has_permissions
``` this is what i did to fix it
Is it risky hosting discord bot on local network
what do you mean by that?
Your bot only communicates with discord (unless you tell it to communicate with other things)
So if you are worried about a user of your bot getting access to your bots IP or something that is not possible by interacting with your bot
chat, i made this bot that y'all can use in dm or servers. whatever. i made sum commands, fun, informative and yeah...now..i got no ideas for the bot, i mean i made a lot of cmds and i ran out of ideas, i'll put a small list of commands:
-# /instagram, /userinfo, /tiktoks(this one it's made by me for fun, posting tiktoks uploaded on catbox.moe), /roblox
give me some ideas please 😭
Someone here a good discord bot developer?
Just ask your question if you have one
If you search for a developer, it's not the place for that - use Fiverr, Upwork or something like that
Alright
what are all the commands? 
my god, they are like 21, i dont remember them all...
i'll tell you soon
-# /streaming - set the status for the bot (only dev)
-# /say - say something trough bot (only dev)
-# /urban - urban dictionary finder
-# /kiss, /hug, /lick, /f**k, /blowj-, /slap, /ana-
-# /tiktoks - choose from a list of tiktoks set by the dev
-# /fakenitro - fake gift nitro parnk
-# /botinfo - info about the bot
-# /website - bot's website
-# /instagram - show an instagram profile
-# /tiktok - show an tiktok profile
-# /roblox - show a roblox profile
-# /avatar - show user avatar
-# /banner - show user banner
-# /membercount - show member count of a server
-# /userinfo -show the last server the user was seen, his id, creation date etc.
i wanna learn more
after my learning shit, i wanna make a discord bot 4 people who want to use it
so, it s for fun
alright, here's one: make a discord game, make a leaderboard
leaderboard? by what?
i would like to make a economy system but i got no idea with the databases
i mean im still trying to make a family cog with /marry, /family and /adopt
do research into databases then
(if you use /marry it will marry with yourself)
i will
but in the first place, i would like to know python very well
and after that i will start using databases and other things
what aspect of python?
i think im gonna go with game development
but i have a low end pc so i cant code any good game
the pre-req problem is 🥶
yes.
#pyweek-game-jam on here has some fun games, nothing crazy
yeah idk
if your objective is to produce basic games you don't really need a powerful pc, if your objective is to produce epic 3d A games then you have 2 problems: python is not the correct language for that and the pc
so i have to learn c++?
I mean, it depends what you want to do... every language can do almost everything but that doesn't mean that they're good at everything
so it depends if it's to get into the game industry for real or if it's just a small thing that you want to make, not really supposed to be published or you don't have high hopes for
nah, i wanna learn it and then get a job from it or at least make money
so i want it to be published
🗿
Does anyone know how to make a bot that can complete hw for me Sparx Maths, one of my friends has one using gauth math and gpt 4
Using AI and other problem solving tools like you described are often considered cheating. Additionally, not doing the homework will not allow you to learn the topic so you will probably end up failing exams. This also violates
!rule 8
8. Do not help with ongoing exams. When helping with homework, help people learn how to do the assignment without doing it for them.
When using interactions, such as buttons, how do I make my bot detect the interaction if the bot has to reconnect to discord?
What library are you using?
discordpy
If you go to the repo, under the examples/views folder there is a persistent.py example which gives you two approaches
ty
🤔 https://github.com/Rapptz/discord.py/blob/master/examples/views/persistent.py
I do this, and sorta understand it. I need to dynamic button stuff. But if I understood it correctly, I have to create a new class for each button? I can't just have 1 class with like 5 buttons?
One class represents one pattern of button
If all 5 do the same thing with one value different, you could put the value in the custom id and parse that out in the same class
intents = discord.Intents.default()
intents.members = True
class Greetings(commands.Cog):
self.client = client
@client.command()
async def hello(ctx):
await ctx.send("Hello, I am the Fortnite bot!")
ive been searching on how to define self everywhere i cant find a solution ive problem solved the others with importing but cant seem to understand this one
its prob a simple fix anyone help
its fine i fixed it
does any1 know what is this ive been stuck for hours with that
Nobody knows, you're sending a random picture of logs without code nor what you goal is
its when i try to start my server where my bot is hosted thats literally the only error i have
wherever you may be using the aiohttp lib, you forgot to close the connection and comes out as warning
it could even be from one of your libraries you're using
the same thing happend to me once when i tried integrating stripe's lib to my bot and i had to manually pass in an async http client either from aiohttp, httpx or some other. Initially i tried using aiohttp but i ended up getting the same output you got and seemed like stripe doesn't have good support on aiohttp so i just passed in a httpx client to the stripe instance instead
yk by anychance where this is?
idk your code
but seems like it has to do with code thats being executed on start up, check every task object that youre running on start up and any related code to that
wait also i just realized you're using dpy v2.3.2
its really outdated
the latest is 2.4.0
@topaz stratus Guess what riddle showed up today😂
lmao
if u go to the website of that free api https://v2.jokeapi.dev: they have a form for customizing the request and provide a query parameter:
blacklistFlags=explicit for the flags
I don't mind what riddles it gives, just thought it was funny that one showed up this early
Although nice to know how to do that
also these aren't even riddles: they are just bad jokes
Yeah, I noticed that. Might have to rename the bot or find a different api
But I mean I did use the joke api so it makes sense that there just jokes
It happens to me too
I get "Unclosed Client Session" warning
PS C:\Users\deutchHD\Desktop\github\BasketPlus> python test.py
Traceback (most recent call last): ges\discord\app_commands\models.py", line 44, in
File "C:\Users\deutchHD\Desktop\github\BasketPlus\test.py", line 1, in <module>
import discord ges\discord\member.py", line 33, in <module>
File "C:\Users\deutchHD\AppData\Local\Programs\Python\Python313\Lib\site-packages\discord\__init__.py", line 23, in <module> ges\discord\abc.py", line 59, in <module>
from .client import *
File "C:\Users\deutchHD\AppData\Local\Programs\Python\Python313\Lib\site-packages\discord\voice_client.py", line 35, in <modulges\discord\client.py", line 51, in <module>
from .sku import SKU, Entitlement
File "C:\Users\deutchHD\AppData\Local\Programs\Python\Python313\Lib\site-packages\discord\player.py", line 29, in <module> ges\discord\sku.py", line 31, in <module>
from .app_commands import MissingApplicationID
File "C:\Users\deutchHD\AppData\Local\Programs\Python\Python313\Lib\site-packages\discord\app_commands\__init__.py", line 12,
in <module>
from .commands import *
File "C:\Users\deutchHD\AppData\Local\Programs\Python\Python313\Lib\site-packages\discord\app_commands\commands.py", line 53,
in <module>
from .models import Choice
File "C:\Users\deutchHD\AppData\Local\Programs\Python\Python313\Lib\site-packages\discord\app_commands\models.py", line 44, in <module>
from ..member import Member
File "C:\Users\deutchHD\AppData\Local\Programs\Python\Python313\Lib\site-packages\discord\member.py", line 33, in <module>
import discord.abc
File "C:\Users\deutchHD\AppData\Local\Programs\Python\Python313\Lib\site-packages\discord\abc.py", line 59, in <module>
from .voice_client import VoiceClient, VoiceProtocol
File "C:\Users\deutchHD\AppData\Local\Programs\Python\Python313\Lib\site-packages\discord\voice_client.py", line 35, in <module>
from .player import AudioPlayer, AudioSource
File "C:\Users\deutchHD\AppData\Local\Programs\Python\Python313\Lib\site-packages\discord\player.py", line 29, in <module>
import audioop
ModuleNotFoundError: No module named 'audioop'
interesting.
import discord
class Client(discord.client):
async def on_ready(self):
print(f"Logged,{self.user}!")
intents = discord.Intents.all()
client = Client(intents=intents)
client.run('TOKEN_IS_PRESENT')
Anyone hows the fix?
Or downgrade python
Ideally you'd downgrade, as 3.13 is not officially supported by discord.py and you may face some other issues later on
any similar bots offering functionalities of the python forum based help system?
What is the most efficient way to create a Voice XP System?
track the minutes users were in vc unmuted and use the minutes to calculate the xp
you could do this in a pretty way by using math (not the module)
Could anyone help me fix this problem?
Traceback (most recent call last):
File "C:\Users\kille\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\app_commands\commands.py", line 858, in _do_call
return await self._callback(interaction, **params) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\kille\Downloads\Trader.py", line 162, in trader_prices_command
price_view = PriceView(categories)
^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\kille\Downloads\Trader.py", line 114, in __init__
self.update_buttons()
File "C:\Users\kille\Downloads\Trader.py", line 119, in update_buttons
self.next_button.disabled = self.current_page == len(self.pages) - 1
^^^^^^^^^^
AttributeError: 'PriceView' object has no attribute 'pages'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\kille\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\app_commands\tree.py", line 1310, in _call
await command._invoke_with_namespace(interaction, namespace)
File "C:\Users\kille\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\app_commands\commands.py", line 883, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\kille\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\app_commands\commands.py", line 876, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'trader-prices' raised an exception: AttributeError: 'PriceView' object has no attribute 'pages'```
https://paste.pythondiscord.com/4HJQ
You've never defined the pages attribute in your class, error says it all
I may need help figuring out how to do that, for the meantime I got a class so ill have to do that later
I mean, you do it in create_pages
But the issue is that you already try to use the pages attribute when initializing the class, which doesn't exist
So in the init you should set the attribute and pass the pages as argument when initializing the class, not later at some random point
I'll learn how to do that after my class
Discord bots while in class?!
No i wasn't working on them while I was in class
Was alittle late to class because I was working on them for a bit
um guys ....so figured out cogs but im still lacking ....
how would i go about using variables between cogs ?
Cogs are just objects, you can set attributes on them. bot.get_cog('abc') can get whatever cog you want
Can anyone send me a @bot.command? Im struggling with my commands and it would be nice to get a example
why.
no
Hello! Can someone help me on why my slash command only allows me one argument (member) even though I have put several more?
u can have only pass singular arguments in slash commands, they dont allow collections or lists of arguments
!d discord.ui.UserSelect you can use a select to pick multiple options at a time
class discord.ui.UserSelect(*, custom_id=..., placeholder=None, min_values=1, max_values=1, disabled=False, row=None, default_values=...)```
Represents a UI select menu with a list of predefined options with the current members of the guild.
If this is sent a private message, it will only allow the user to select the client or themselves. Every selected option in a private message will resolve to a [`discord.User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User).
New in version 2.1.
Okay. setup is a coroutine ?
which setup?
In Cogs
yeah it is supposed to be async
Okay. Thankss
!! 🙂
Good!!
Oh dang, what all does it do?
It's a ticket bot
:D
Similar to those you might find in gaming servers. Where you click a button, fill in some information. and badabing.badaboom. Tikcet
This one is tailored specifically for my friends discord server so you'd have to remove some things to make it work as a general bot.
Ah, yeah I have a ticket bot in my DayZ server, tomorrow after I get done with my classes I'll take a look a your bot. See how it is
Always find it interesting to see other people's creations
Sometimes it's fun to see other peoples solutions to the same problem as well
Yeah, with how new I am I haven't really been able to check out anyone's creations but would like to start. Get some ideas for my own or to genuinely use the bot
Not necessarily an idea from a bot but one of the servers I used to be in for a game had a price list and with how cluttered it looked I didn't like it. Once I had made my own server for the game I decided to make a bot that displays a price list so it didn't look as cluttered. Wanna make it look better but as of right know I think it looks decent
Just wondering what I can do to fix this goofy bug in discord, if you mention the @ everyone role, it shows as @@everyone . How can I fix that in code to only do @everyone?
show code
cod
buddy
role.mention
if you do <@roleID> on the @everyone it does it twice
go try it 
oops, I had @ everyone in message 😭
inline=False```
this should possibly fix it, cuz if you type `@everyone` it shows up highlighted as if it was pinged/mentioned. But if it doesn't then I suck 
crazy
bro so smarg
you could also not show it
since well... everyone have it
oh wait that's not a Role info command
nvm then
yeah lol
What py versión can I use for creating a bot?
Depends on the library, discord.py supports up to 3.12
I think it is because the actual role name of @ everyone contains an @ symbol so when you mention he role it is @+role name so it has 2 @
how to install python on vs code
vs code is a text editor. You don't install anything on it. It has extensions for highlighting and debugging, but python itself is a separate program/installation on your machine
you install python
you set the python interpreter setting in vscode to your installation path
how to install discord module on vs code
pip install it? like literally any other package?
the fact that you dont know this is kinda worrying
also werent you just told this?
Bro don't be that guy, he's obv new, help him and don't be a dick about it
i'm not being a dick - i'm noting aloud that trying to make a discord bot, something that requires a somewhat extensive knowledge of python to have, shouldn't be a journey embarked upon by someone who isn't have of python's package manager
Is there any way of checking a message count for a user faster?
I mean yeah its a advanced project, but maybe explain it to op? and what should be his approach instead?
I dont think so there is any direct method
- using channel history
- using
on_messageevent to maintain your own counter in your database per user
Thanks. I was thinking of storing the count in a database but wanted to see if there's an easier way. And for channel history - how do you do that? channel.history?
!d discord.TextChannel.history
async for ... in history(*, limit=100, before=None, after=None, around=None, oldest_first=None)```
Returns an [asynchronous iterator](https://docs.python.org/3/glossary.html#term-asynchronous-iterator) that enables receiving the destination’s message history.
You must have [`read_message_history`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.read_message_history) to do this.
Examples...
thanks
this is still slow so db is def needed
well yeah because you're pretty much fetching lots of data from discord (the endpoint is paginated)
and the endpoint has a max of 100 messages per page
so depending on the amount of messages in the channel, it makes lots of http requests to discord
fetching up to 100 messages should be fast as it's a single request
So nobody should learn anything new until they already know stuff'
Let bro learn, he'll learn about the necesities along the way
not really - it's that you'll most likely have a very difficult time learning that "anything new" if you don't already know whatever the knowledge builds off of. algebra would be extremely difficult if you didn't know the four operations - while that doesn't stop you from trying, you'll probably not get far 🤷🏽♂️
OP just asked the exact same question word for word 20 minutes after his original question was answered
also the guy isn't even responding so i'd never get the chance for it
Ok bro, leave it
!user
You are not allowed to use that command here. Please use the #bot-commands channel instead.
you playing up again ? try not to damage too many cars now lol
??
No module named 'audioop'
Not even using audioop
Someone help, please?
My code
import discord
from discord import app_commands
import asyncio
MY_GUILD = discord.Object(id=1325342160442228758)
class MyClient(discord.Client):
def __init__(self, *, intents: discord.Intents):
super().__init__(intents=intents)
self.tree = app_commands.CommandTree(self)
async def setup_hook(self):
self.tree.copy_global_to(guild=MY_GUILD)
await self.tree.sync(guild=MY_GUILD)
intents = discord.Intents.default()
client = MyClient(intents=intents)
@client.event
async def on_ready():
print(f'Logged in as {client.user} (ID: {client.user.id})')
print('------')
stream_activity = discord.Streaming(
name="test",
url="https://www.twitch.tv/RoExclusive"
)
await client.change_presence(activity=stream_activity)
@client.event
async def on_guild_channel_create(channel):
if "ticket" in channel.name.lower():
await asyncio.sleep(5)
dark_mode_color = discord.Color.from_rgb(31, 33, 38)
embed1 = discord.Embed(
title="Welcome to Your Ticket",
description="Please describe what you need and ping @vxry once done.",
color=dark_mode_color
)
await channel.send(embeds=[embed1])
client.run('')```
Downgrade python to 3.12 or lower
What OS are you on
Can just install 3.12 (or lower) parallel and then use that to run your code
No idea on how to check that
Operating System, like Windows or Linux or Mac
Windows 11
Can you just tell me how to downgrade I dont understand what you're telling me to do
This is also googleable
However you installed python 3.13, use that to install 3.12 instead. Then run your code with the 3.12 installation
I don't know how to degrade I looked it up and still confuses me
^
i see that, but how would I do it???
Which part
However you installed python 3.13, use that to install 3.12 instead
This part
How did you install 3.13
Python website
Then download any 3.12.x version from there
Any 3.12 version?
<@&831776746206265384>
Yeah any should be fine
!cban 1264563127106797579 scammer
:ok_hand: applied ban to @solemn swan permanently.
I installed 3.12, but wouldn't it just be overrided by 3.12 and not work at all?
On windows, python versions get installed in separate directories. You have to choose which one when you run your code
How do I choose which one will run the code ?
If this is in an ide like vsc, you should have a dropdown selector for python installations. If you're running from command line, you would either type in the full path to the python exe you wanted or use something like the py launcher
Is the only stuff I see, I don't see a dropdown
Bottom right, there's a version number
Now I'm getting this:
It's a new environment. You'll need to install packages on it
Did that, still showing.
You either didn't, or the ide is lying to you (they often do)
never trust what vsc shows, always run your code and get an error
Traceback (most recent call last):
File "c:\Users\dynam\OneDrive\Documents\RoExclusive Bot\main.py", line 3, in <module>
import discord
^^^^^^^^^^^^^^
ModuleNotFoundError: No module named 'discord'
I did pip install discord
Yeah but pip, written literally, is ambiguous
that's probably still installing into your 3.13 installation
So what should I do then?
Several options
- You can set up a virtual environment instead
- You can use
py -3.12 -m pip install ...if you installed python with thepy launcheroption - You can use
<full path to your 3.12 python .exe> -m pip install ...
Thank you very much! One last thing, do you know why when I do my suggest slash command my bot doesn't send the message content to the suggestion channel once the user sends it. My bot sends the embed to the channel, but no content.
async def suggest(interaction: discord.Interaction):
await interaction.response.send_message(
"Please type your suggestion below:", ephemeral=True
)
def check(msg):
return msg.author == interaction.user and msg.channel == interaction.channel
try:
msg = await client.wait_for("message", check=check, timeout=60)
except asyncio.TimeoutError:
await interaction.followup.send(
"You took too long to respond. Please try again.", ephemeral=True
)
return
suggestion_channel = client.get_channel(SUGGESTION_CHANNEL_ID)
if not suggestion_channel:
await interaction.followup.send(
"Suggestion channel not found. Please contact the server administrator.",
ephemeral=True,
)
return
embed = discord.Embed(
title="New Suggestion",
description=msg.content,
color=discord.Color.blue()
)
embed.set_author(name=interaction.user.display_name, icon_url=interaction.user.avatar.url)
embed.timestamp = discord.utils.utcnow()
suggestion_message = await suggestion_channel.send(embed=embed)
await suggestion_message.add_reaction(":white_check_mark:")
await suggestion_message.add_reaction(":x:")
await interaction.followup.send(
"Thank you for your suggestion! It has been sent to the server team.", ephemeral=True
)```
Example:
You aren't asking for message content in your intents. Either way, I suggest you don't use wait_for waiting for the user to send a message, that's pretty bad ux. You can instead use a modal (pop up) where the user can input what they want and it gets sent directly to your bot rather than a message on the channel
https://discordpy.readthedocs.io/en/stable/intents.html if you want to receive message content
https://github.com/Rapptz/discord.py/blob/master/examples/modals/basic.py if you want to use a modal instead
If I were to make a suggestions bot, I'd have a singular button attached to an embed. The embed is basic "Hey, wanna make a suggestion?"
and the button simple opens a modal, same as what @fast osprey said.
Then the suggestions can either be public or private. It's no matter. It gets sent to a channel of my choosing. I'd make it look fancy with an embed. " @drifting arrow suggested this thing!" kinda deal.
I want to make a modal, but it's to confusing to me
The "wait_for" is fun and all. I've done it before with some bots, however it's so annoying to do and it's just shit in general. Coz you have to basically put all your validation in the single function because you're waiting for a response each time and if the response could be something different you got a bunch of issues lol
Modals are simple once you get use to them
The example of a basic modal provided by solstice is pretty good. It's what I do.
The short of it is:
- make a class that subclasses Modal
- in that class declare whatever TextInput(s) you want the user to see in the popup
- implement the on_submit method to do whatever you'd like with those inputs when the user submits the modal (send to your other channel), plus respond to the submit interaction
- in your initial command, use interaction.response.send_modal(YourModalClass())
note that textinputs need to be classvars (i believe) which might make it tricky to populate with data passed into arguments. i recall having some issues with this
if they're classvars they get added when the modal is initiated, but you can manually add them using Modal.add_item too
Was wondering how to fix this simple issue. After response (defer) and following up to a dropdown select, it still keeps the thing selected even though I don't want that. I am using discord.py though
Edit the message with the view and make sure none of the select options are set to default
I Have this simple on/off duty command, that gives and removes roles. Is it possible for the bot to contain in the embed the time that the user has been on duty?
You could store the time in a database
Keep track of the time when they last executed the command, in a database, and then do some small math
i need help
anybody can help?
Help with?
that's what this channel is for, ask what u need help with and if someone can, they will
help with storing the time in the database and then showing the user the time elapsed
Do you have a database?
no
The find some websites or videos quickly explaining a database, e.g. SQLite
Then you can use the aiosqlite module in python to interact with an SQLite database
!pypi aiosqlite
!pypi asqlite - i find rapptz wrapper to be very easy to use as well
What would be the most efficient way to create a Voice XP system?
As i see this going, You could track entry vc time + leave vc time, to get the time they've spent in voice, to ensure your system won't fail, in case there's join time, and no leave time, set a time of the application's startup, There's a chance that users will be in voice, so entry time won't exist, when adding leave time ensure there's a field of entry time.
Create a setup that would give certain XP for minutes or hours, that can be configured thru setup
And you'll be adding the XP during leave time, you'll add the xp from there
and also having a task running hourly to ensure xp is proper for every user
This is a small idea, can surely be improved... but to get a base logic....
You should install psql, this will allow you to create a database on your machine
And to facilitate the usage of database, you could use an ORM, as example tortoise ORM, they allow you to create a datetime field and auto add time
using auto_add_now=True would add the time automatically
in order to push changes to commands globally without using GUILD_ID i just run a bot and wait 1 hour?
sync globally then restart your discord client by doing ctrl + r
how do I do that exactly
what do I need to add
I have no clue how to use this bot
it's best to make a command that syncs and then use that
Can bots access guild vanity url with manage_guild?
Only read, ik it cannot be modified
nvm
If I get a NAS for raspberry pi's, could I use it to run multiple bots without it being on my main computer?
Nvm, just looked more into NAS and don't plan on using it
why would you need a NAS?
I would say, also set a timestamp on when you bot last restart
So you can assume that, if your system don't have track on their join time, and assume you store entry time just in memory, you can assume that they enter before the bot start
I was thinking of something else, just got the names mixed up
hey! im new to coding and trying to work on a bot, tips?
Biggest tip I can give you is to build solid fundamentals by doing focused projects before tackling something advanced that touches on several concepts simultaneously
yeah take this advice^^^
https://paste.pythondiscord.com/AGTA any1 know how to fix that the bot dont create a new category for modmail everytime a user dm it cuz rn everytime someone dm the bot its creating a new category
how to get a users about me?
you cannot
but ive see a bot do it?
not legally or without violating discord terms of service
discord dosent provide an official api returning user bio
i dont think thats illegal
How does Discord send notifications to a bot about new messages? Is it possible to receive messages using an HTTP server?
Through the web socket gateway only, it's not possible to receive them via HTTP, that's only for interactions and a couple of other select events, the volume of messages sent makes it less reasonable to make individual requests for each one
Okay, then I'll try running the Discord bot and the aiohttp server in the same process

Any manual or documentations on databases and how to implement them?
I've made a command that let people make custom role's by themselves but they can do it multiple times and flood the roles
figured the only way to deal with that is to store info who made what and each time someone tries to make another one it checks the list of user ids
If anyone have any better ideas let me know 
What is a custom role?
basically it's a slash command that let you create a role in a server and choosing a color
bot makes a role and assign it to you
should've worded that better mb
Roles aren't made for that, and in any reasonably large sized server you're going to run into issue
yeah it's not for a large server at all
looking at 300 people at best
and how many of those will figure out how to even use the command, who knows
also that command is locked behind a level that you gain by being active
That is above the number of available roles. People don't need only their own role
after a certain level the command appears and you're able to use it
The way I see this handled is to make a set of discrete roles and let people opt into them rather than making their own
That's not a "custom role" anymore though
Roles aren't made to be custom.
Also I do have that already so
They are permissioning units with limitations, not arbitrary flair
They're already very limited
As a matter of fact, nobody even abused that loophole I just wanted to get it fixed for fun
Just telling you what discord wants you to use roles for and that this is a misuse of them
Ok I understand that but that's besides the point
It's not
For database setup/design, that's independent of making a discord bot and better served in #databases
You'll want to lay out the schema for any data you want to store and then make an informed decision about which db engine to use
The first step you need to take is to choose a database. I personally use postgreSQL but for smaller projects and quicker/easier setup I have heard that sqlite works well. You can have a column for the user ID and a column for the role ID (and potentially guild ID as well just in case at some point this bot is on multiple servers). Then you would just need to check if a "row" exists with that user ID. You can probably find some help for how to set it up in #databases I am not experienced enough to confidently guide you.
Also, you can use the API for whatever you want if it falls within discord TOS. And allowing users to create roles 100% falls within discord TOS.
What does OPPWST 11 mean?
in what context?
can somone help me with this?
there is no such file at that location
ModuleNotFoundError: No module named 'audioop' how can i fix that?
Downgrade python to 3.12
oki
@sick birch Sorry for the ping. Here is my solution:
https://paste.pythondiscord.com/V2UQ
- periodically write it to the database
hello, i've asked about this issue before but i'm still encountering the same problems and could use some more insights. i finished my app system, and it worked perfectly in my test server after thoroughly testing on my local environment using vscode. however, when i deployed it to my VPS, it stopped working as expected.
here's the situation:
- using the
*samplecommand, it displays the sample embed with the dropdown and select menu (screenshot) - but when i select an option, it doesn't trigger the modal. instead, it shows the content from the above image
- the video recording is how the system works as expected (in the test server, it triggers the modal with the messages)
i put some debug statements and deployed it to my VPS, but this was the only output:
Select menu triggered with value: ['Event Assistant']
Selected role: Event Assistant
this differs from the expected output screenshot, which should include logs indicating that the modal interaction was triggered and processed.
relevant files:
additionally, sample.py isn't supposed to send modals; it only displays the select menu and embed while app.py handles the modal interaction and the logic. i've also removed all blocking code and tried assigning a different custom id to SampleSelect in sample.py compared to AppRoles in app.py. however, this caused the entire system to stop working.
i still don't understand how the system works on my vscode but not my VPS, so help is greatly appreciated.
no need, install my copy of audioop if you want it for 3.13/3.14 (cpython main branch). It works perfectly too if you don’t care about free threaded GIL-free python.
haven't any experience with Hikari but I'd assume its working on your vsc but not on your VPS because of the custom IDs.
Second, if it doesnt work when you change custom IDs is because in SampleSelect you aren't initating the Modal (like you are in AppRoles). You're just printing something @outer violet
Oh I see. Okay that makes sense, I’ll give it a try when I’m back home
So I have to initiate the modal in SampleSelect as well just like in AppRoles?
yep, worth a shot (also change the IDs)
Hello, i am dealing with a really weird issue in my code due to lavalink, if anyone here knows how to use lavalink i wonder what could possibly be wrong in my code.
In this image, it's a quick test setup to test the bot, SADLY the voice DOES NOT work, which is really weird.
Here, i have a really simple connector towards lavalink
This is the application.yml (copied example i doubt this issues)
And this is lavalink server
The server DOES startup properly, and bot connects well to it.
I've also added that intent in order to hope it would work, but sadly IT DOES NOT
The bot successfully retrieve the track, the name, etc, player does not play the track even tho IT IS found.
This is quite tricky, but if anyone knows by bot's voice doesn't play the track, please let me know!
!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.
So much code
Right.
- commands -> https://paste.pythondiscord.com/37AA
- lavalink connector -> https://paste.pythondiscord.com/M4NQ
- main file -> https://paste.pythondiscord.com/WZ5A
- compose.yaml -> https://paste.pythondiscord.com/VHDA
- application.yml -> https://paste.pythondiscord.com/5QQQ
logs are visible in the pictures, there is literally no issue, so if anyone that's familiar with lavalink would know why the player is not playering 😂
this exists https://pypi.org/project/audioop-lts/
Think twice, there's a reason it got deprecated and removed from the stdlib..
think thrice, what i mean is there is an already supported library and is actively maintained and probably much better than that
actively maintained
Is exactly where you're wrong
Give it a few months and it won't work anymore
These eternal libraries are here to make sure it is maintained and will keep working with future Python versions.
youre missing my point
what i mean is it's better to use the library i mentioned that what mage made
PEP 594 proposed removing 19 modules from the standard library, colloquially referred to as ‘dead batteries’ due to their historic, obsolete, or insecure status. All of the following modules were deprecated in Python 3.11, and are now removed:
You're sure you want to use it..?
and ik that
it is a better temporary fix until dpy updates to a better alternative for audioop
Those libraries exactly are made for that purpose, so yes I'd rather use a "random" other library that is kept up to date
im not saying to use the library itself
No, downgrading to 3.12 is
yeah, but to the ones who dont want to downgrade
d.py doesn't officially support 3.13 either, so you may face other issues in the future and not just that
im not saying to use the library itself
Kinda
@slate swan
any ideas?
Playing music is against TOS unless you hold copyrights to that music and aren't violating a streaming service's TOS, which it's pretty clear your code is not doing
has anyone got a example of using variables between cogs trying to work it out but coming up with error ( like i know how to make classes and all that but i donno what im doing wrong )
If you're using discord.py, there's an example of this on the docs page on cogs
pycord but close enough that will do thanks
not everyone can possibly downgrade to 3.12 though 💀.
plus 3.14 (cpython main) works just fine for me.
then you're not using any voice func.
yeah, to avoid TOS problems with the voice stuffs.
it still works fine on 3.13 and 3.14 though.
"it works" is not a sign you should do it, or that you should encourage others to do it
when the library owners are telling you not to do it
they actually are saying it's ok tho.
as next version they will default to installing audioop.
yes, in which case they will update the supported versions
Hi, this is my library
I plan to maintain this so long as discord.py needs it
I should also add that whilst MagicMage simply took the existing code from the last 3.12.7 tag, mines is also from the same tag but I have also compiled it for use within the modern (3.13 + for now) ABI as well as added support for free-threaded builds.
I also release pre-compiled wheels for numerous architectures so it's very simple to use - even on raspberry pis :)
You'll see that this is already depended on extensively, even the @unkempt canyon bot uses it
I have no intention to pull the rug from anyone that uses this - I will maintain this so long as I am physically capable, and in the event that I am not, I would ask some TRUSTED contributors to take over, I know what it's like losing a critical piece of support, that's not fun for anyone.
EDIT: upon further reading it seems that @slate swan seems to have mistaken the pypi link sent for some sort of shim, not a maintained project. They were supportive of @opal vortex's repo link thinking it was alternatively a maintained project versus the pypi link. Looks like an easy misunderstanding :)
3.12.4*
Ah my apologies, it hasn't changed in several minor versions so it doesn't matter too much for that point
ye
Hi
I made this with discord.py in mind - I spoke with Danny and he was happy to use my version - he onboarded it as soon as I got it working and ready for 3.13+.
Currently there are no plans to make/switch to an alternative. This is a VERY hot codepath in voice related code so alternatives must be faster than Python.
(think Zig, Rust or C, still).
This means that for the foreseeable future, d.py (and the forks of it, surprisingly) won't be switching away.
Hopefully that clears any concerns up <:
btw did you by chance consider switching it to the limited API whenever the core devs allow free threading along with it?
Note: would require using the Heap type of creating types method where they are created via a PyType_Spec variable and passed to PyType_FromSpec().
My Discord bot's core uses pyawaitable and uses heap types already so 😂.
I don't believe that change is even necessary? Outside of edge use cases like yours lol
(just because I wanted to implement the core of my bot in C like database stuff to eliminate asqlite3)
i am
I need help with this, im trying to run my bot but this keeps happening (Fixed it)
Is there a way to set the dropdown menu to always be on the default after a person selects something?
I want it to always reset
Currently I am just editing the message to update the view
await interaction.message.edit(view=dropdown_menu_view(config=self.config, tokens=self.tokens,options=options)) basically this
why is this in a channel about discord bots?

doesn't it normally do that?
No
show me your code. i wanna see this feature
Hi, nextcord maintainer here - don't be surprised the forks use it, good software is good software, our goal isn't to be different from discord.py it's to be good in our view (which sometimes means differences), but if there's something good like your library that's the better option we want to use it because that's the sensible engineering decision
Thanks for making the LTS package and maintaining it :)
Almost missed this - just want to say I didn't add my "surpisingly" as a slight by any means, I just meant I was genuinely surprised!
Thank you for the comment though, it's much appreciated 💜
Would it be recommended to asyncio.gather when updating multiple users roles? My correct code:
reward_roles = set(roles.values())
member_roles = set(member.roles)
roles_to_remove = [role for role in member_roles if role != role_to_assign
and role in reward_roles]
if roles_to_remove:
await member.remove_roles(*roles_to_remove)
if role_to_assign and role_to_assign not in member_roles:
await member.add_roles(role_to_assign)
Was thinking of
role_tasks = []
if roles_to_remove:
role_tasks.append(member.remove_roles(*roles_to_remove))
if role_to_assign and role_to_assign not in member_roles:
role_tasks.append(member.add_roles(role_to_assign))
if role_tasks:
await asyncio.gather(*role_tasks)
So there is no need for asyncio.gather?
"need" is a strong word. It really depends what behavior you want
If you have multiple coroutines that are independent of each other and you care about when all of them are finished rather than individual ones, yes gather probably does what you need
afaik even if you fire these coros all at the same time, the library's internal semaphore will keep you from shooting yourself in the foot to rate limits
It will loop through members who have gained XP, assign them role rewards, and remove previous rewards (users will only retain the highest role reward). What would you recommend for my situation?
Whatever tips would be appreciated 🙂
I mean it depends on what "XP" means, and if you could do it locally when that happens rather than in a big ol loop over everyone
guys how could i make an automation bot
im new to coding and dont know where to get started
That doesn't suggest anything, what do you mean automation?
like auto response and auto sending
well
auto respond to what?
ppls dms
No reason to receive help in DMs. It is 100% allowed to receive help in the ... well ... help channels
In general depending on what you mean by new to coding, I would strongly suggest you don't start with something as complex as this. Chat bots and the like layer several different concepts together, and trying to learn them all at the same time is going to leave you and people trying to help you frustrated. It's up to you how to learn, but I've been at this for a long time and people who do this are far, far less likely to succeed in the long run than if they do smaller, focused, simpler projects first to build up those concepts
What's this a response to? 
#discord-bots message Unless I misunderstood the abbreviations
why am i getting "The application did not respond"
but then it sends?
ah i see, guessing you read that as "please dms" rather than "people's dms"
which is fair
Probably because you're not responding to the interaction itself
Does a before_loop indicate that a task is running or not?
self.xp_task.is_running() would return True or False?
is there any way to record discord voice channels
self.xp_task.is_running() will return True or False depending on whether the task is running or not
in what way are you trying to record?
bot joins talk and records the voice
@spiral plank I was referring to this question
some github repos use .start_recording() but function doesnt exist
sorry, didnt see that
Can you post the repo?
Are you using py-cord or are you using something else like discord.py?
I am using discord.py

Well you cant use pycord functions in discord.py.
Last I checked discord.py does not support audio recording
which should I use
Well, if you want to use voice recording you will have to use a library that supports it (such as py-cord) or implment it yourself.
for discord.py, you would have to use https://github.com/imayhaveborkedit/discord-ext-voice-recv instead
Voice receive extension package for discord.py. Contribute to imayhaveborkedit/discord-ext-voice-recv development by creating an account on GitHub.
Recording voice is incredibly sketchy, especially if you haven't considered all of the data privacy policies and laws you are now opening yourself up to
hello all. i am attempting to create a discord bot just to mess around with python coding. currently i am on my first step. while my code comes back with no errors.. it is supposed to say:
The bot is ready.
This is supposed to happen in the terminal when executed, however it doesnt. as aforementioned, the response i get in Pycharm is "Process finished with exit code 0" so i dont have any errors. any advice?
Without code, can't help much
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.message_content = True
intents.guilds = True
client = commands.Bot(command_prefix = '!', intents = intents)
@client.event
async def on_ready():
print("The bot is ready.")
print("---------------------")
@client.command()
async def hello(ctx):
await ctx.send('PINECONES')
client.run
at the end is my bot's token, which is why it is blank
client.run should not be indented
You should also
- Rename your
clientvariable tobot, it's a bot and not a client - Remove
intents.guilds = True, it's already included indiscord.Intents.default()
👍
i am very new-- so when you say rename client variable to bot. what do you mean specifically?
Instead of doing
client = commands.Bot(...)
you should do
bot = commands.Bot(...)
ahhh
i did that, and it comes back with
Traceback (most recent call last):
File "C:\Users\User\Desktop\main.py", line 8, in <module>
@client.event
^^^^^^
NameError: name 'client' is not defined
Then obviously you gotta edit all the @client.command() to @bot.command() etc.
Same for @client.event and client.run
youre a capital letter G my friend
any good resources for learning python other than here?
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
Has some neat resources to learn :)
ty ty
Member.edit has a roles= kwarg that can replace all roles with one call fwiw
new_roles ÷ set(([r for r if not r.is_managed() or r.is_default()]).union(*roles_to_add) - set(roles_to_remove)
await member.edit(roles=new_roles)
÷ is not a valid Python operator?
probably meant = but made a typo
the for loop is missing an in ... tho
Would this be correct?
role_to_assign = next(
(role for threshold, role in role_thresholds if updated_total_seconds >= threshold),
None
)
reward_roles = set(roles.values())
member_roles = set(member.roles)
new_roles = (
{r for r in member_roles if
not r.is_managed() or r.is_default()}
- {role for role in member_roles if
role in reward_roles and role != role_to_assign}
| ({role_to_assign} if role_to_assign else set())
)
await member.edit(roles=list(new_roles))
I don't know what your goal is so I can't say, but I see multiple logic errors
not r.is_managed() or r.is_default(), should not both
My goal is to assign the role from role_to_assign and remove any roles from reward_roles that are not in role_to_assign
wait
new_roles = [role for role in member.roles if not (role.is_managed() or role.is_default() or role in reward_roles)] + [role_to_assign]
this solution expects that role_to_assign is a role and not None, I think if it's None you should just return
Whoops
What about
new_roles = [role for role in member.roles if not (role.is_managed() or role.is_default() or role in reward_roles)] + ([role_to_assign] if role_to_assign else [])```
You can do that, but are you sure that you want to edit the member's roles if role_to_assign is None?
My full code
role_thresholds = sorted(
[
(172800, roles["ultimate"]), # 48 hours
(57600, roles["mythic"]), # 16 hours
(28800, roles["legendary"]), # 8 hours
(14400, roles["epic"]) # 4 hours
],
key=lambda x: x[0], reverse=True
)
role_to_assign = next(
(role for threshold, role in role_thresholds if updated_total_seconds >= threshold),
None
)
member = guild.get_member(member_id)
if member:
reward_roles = set(roles.values())
member_roles = set(member.roles)
new_roles = (
{role for role in member_roles if
not (role.is_managed() or role.is_default() or role in reward_roles)}
| ({role_to_assign} if role_to_assign else set())
)
if role_to_assign:
await member.edit(roles=new_roles)
Is this in an event or task?
there's a chance role_to_assign might already be one of the user's roles?
#bot-commands
Not really, role_to_assign checks if updated_total_seconds indicates that there is a new role reward available, assigns the new role to the member and removes the old one
(member will only retain the highest role reward)
how is updated_total_seconds calculated? Is there no chance that it'd be below the next milestone multiple times
Seconds being in voice. That would be possible of course
Maybe I should add
if member and role_to_assign:
...
then that would mean role_to_assign can be already in the user's roles
if role_to_assign in member.roles
True
Would that be a problem?
realistically not, but it's still an unnecessary api request
Any idea how to solve that?
^
return if the role is one of the member roles or if the role is None
i don't think you'd want to ignore managed/default roles here: py new_roles = ( {role for role in member_roles if not (role.is_managed() or role.is_default() or role in reward_roles)} | ({role_to_assign} if role_to_assign else set()) ) according to #1293735870528094308 message , the list you're passing should include all roles, even ones that your bot isn't allowed to add/remove
interesting
Any idea what it should look like instead?

Can someone confirm this?
Why not.. try it and see?
Well according to @hushed galleon I should include all roles, even ones that the bot isn't allowed to add/remove
And why don't you try it? To see if that's what you want
You mean if new_roles != member_roles:?
No, I mean exactly what I sent
I just realised shouldn't it be role in reward_roles and role != role_to_assign
Than you didn't read the code clearly
Here is a break down:
role_to_assign = next(
(role for threshold, role in role_thresholds if updated_total_seconds >= threshold),
None
)
member = guild.get_member(member_id)
if member and role_to_assign:
reward_roles = set(roles.values())
member_roles = set(member.roles)
new_roles = (
{role for role in member_roles if
not (role.is_managed() or role.is_default() or role in reward_roles
and role != role_to_assign)} | ({role_to_assign} if role_to_assign else set())
)
if new_roles != member_roles:
await member.edit(roles=new_roles)
Wdym? That if statement checks if the member already has the role that you're trying to give, in which case you should just return?
Well sorry that makes sense. Did you see my logic above? ^
Shouldn't if new_roles != member_roles: avoid an unnecessary api request?
I think new_roles != member_roles will always be True, since the way new_roles is created does disregard some roles
All you need to check for tbh is just if role_to_assign is None or role_to_assign in member.roles:
But this wouldn't remove reward_roles that have been added by mistake by a mod or someone else
What would you say about
manageable_roles = {role for role in member_roles if not (role.is_managed() or role.is_default())}
new_roles = (
{role for role in manageable_roles if role not in reward_roles or role == role_to_assign}
| ({role_to_assign} if role_to_assign else set())
)
# Compare manageable roles with new roles
if new_roles != manageable_roles:
await member.edit(roles=new_roles)
Because it doesn't need to, it already did
If role_to_assign is None, it means there is no higher role to give anymore so it should not be removed. And if role_to_assign is in member.roles then it means it has already removed the other roles when it added role_to_assign before
But if a moderator gives a member a role that is in reward_roles when role_to_assign is None, it wouldn't be removed
(example given mistakenly by a human)
this isn't the place to do cleanup after moderators, otherwise, use an event which checks if a mod added/removed a reward role manually and then fix it
AttributeError: 'Role' object has no attribute 'is_managed'. Did you mean: 'managed'?
!d discord.Role.managed
Indicates if the role is managed by the guild through some form of integrations such as Twitch.
is_bot_managed()```
[`bool`](https://docs.python.org/3/library/functions.html#bool): Whether the role is associated with a bot.
New in version 1.6.
!d discord.Role.is_integration
is_integration()```
[`bool`](https://docs.python.org/3/library/functions.html#bool): Whether the role is managed by an integration.
New in version 1.6.
Why is it necessary to exclude them when using member.edit for roles?
Oh, just figure out that it's not really
Yo yo yo, I'm back again. I have a question for you guys. Is there any lines of code that is a must have with a bot? I understand that you need the import and run blah blah blah and commands in order to interact with the bot. But is there anything else that I should be aware of?
depends on what you're doing. some tasks need more boilerplate than others
for example, if you want to load extensions before runtime, it's better to subclass and override setup_hook, meaning you'll need to write an entire class to achieve that
We can help you here, let us know more
Bruh, open a help section, people will help you there
Then if it's easy, just create a help thread
Asking people to call you or go in your DMs is weird
Yeah
If they are using discord.py
Not really, there are no "lines" that you need to have that dont have any purpose. Every single line in your code changes the behavior of your bot in some way. There is nothing that is required to have. Of course to make your bot functional you have to start it somehow but everything else is optional.
Yo I followed this tutorial and the code for some reason isn't working but in the tutorial the code is working
import discord
class Client(discord.Client):
async def on_ready(self):
print(f'Hello World, {self.user}')
intents = discord.Intents.default()
intents.message_content = True
client = Client(intents=intents)
client.run("token")
I dont see anything wrong
Run the code and see the error
There's a bunch of them
return await self._loop.create_connection(*args, **kwargs, sock=sock)
transport, protocol = await self._create_connection_transport(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^```
and a bunch of others
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.
Bro this stuff has my token
you know you can edit things you copy, right?
Yea but discord is automatically putting it in a txt file that I cant edit
I’ll try that in a bit one sec
Bro it's not letting me send it
File "/Users/computer/PycharmProjects/Valorant_Checker/.venv/lib/python3.12/site-packages/aiohttp/connector.py", line 1122, in _wrap_create_connection
return await self._loop.create_connection(*args, **kwargs, sock=sock)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/asyncio/base_events.py", line 1126, in create_connection
transport, protocol = await self._create_connection_transport(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/asyncio/base_events.py", line 1159, in _create_connection_transport
await waiter
File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/asyncio/sslproto.py", line 575, in _on_handshake_complete
raise handshake_exc
File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/asyncio/sslproto.py", line 557, in _do_handshake
self._sslobj.do_handshake()
File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/ssl.py", line 917, in do_handshake
self._sslobj.do_handshake()
ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1000)```
Traceback (most recent call last):
File "/Users/computer/PycharmProjects/Valorant_Checker/.venv/discord_bot.py", line 13, in <module>
client.run("token")
File "/Users/computer/PycharmProjects/Valorant_Checker/.venv/lib/python3.12/site-packages/discord/client.py", line 869, in run
asyncio.run(runner())
File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/asyncio/runners.py", line 194, in run
return runner.run(main)
^^^^^^^^^^^^^^^^
File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/asyncio/runners.py", line 118, in run
return self._loop.run_until_complete(task)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/asyncio/base_events.py", line 664, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
await self.start(token, reconnect=reconnect)
File "/Users/computer/PycharmProjects/Valorant_Checker/.venv/lib/python3.12/site-packages/discord/client.py", line 786, in start
await self.login(token)
File "/Users/computer/PycharmProjects/Valorant_Checker/.venv/lib/python3.12/site-packages/discord/client.py", line 620, in login
data = await self.http.static_login(token)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/computer/PycharmProjects/Valorant_Checker/.venv/lib/python3.12/site-packages/discord/http.py", line 816, in static_login
data = await self.request(Route('GET', '/users/@me'))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
I think thats all of it
@slate swan
yeah the token is invalid
Oh so just make a new one?
regen and copy the right one
ah nvm you also have an invalid ssl request
A guide on fixing verification of an SSL certificate.
next time really use the pastebin, it's pain to read
how do i recreate this
ty
though do note that if this is the user bio:
the bot is violating discord's tos and can get terminated
so i wouldn't do that
hakuna matata
is have the bot show as on phone against tos too
it's technically allowed, though not officially supported - so your bot may crash one day because of that
How do i restore a db?
how comes
how?
!d discord.Member
class discord.Member```
Represents a Discord member to a [`Guild`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Guild).
This implements a lot of the functionality of [`User`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User)...
wait if bio (or some form) isn't in discord.py, and dpy has basically wrapped all of the API, how did they even get the about me
Most likely a custom bio
wdym
As in, you are able to use a command to set a custom bio in the bot
is this normal for my discord bot to keep reconnecting overtime?
Yes
bios are not exposed to the bot's api, only the user's api, and that's a fact.
automating user accounts is against tos, hence a bot using an automated user account to get the bio is against the tos.
yeah that's changing the bot's activity - that's not what i meant
ohhhh i see. thank you krypton
yeah
it's why it's recommended to not put too much stuff in on_ready
Resuming a session won't trigger on_ready
This is normal afaik
hm, wasn't aware
v0.16.0
You could try it out with
@bot.event
async def on_connect():
print("Connected!")
@bot.event
async def on_ready():
print("Reconnected!")
@bot.event
async def on_resume():
print("Resumed!")
@bot.event
async def on_disconnect():
print("Disconnected!")
Hi
I want to host a discord bot, for one server only, it’s gonna be a complex bot and I want 24/7 uptime, what service should I use? Do yall have any recommendations
This article lists recommended VPS services and covers the disasdvantages of utilising a free hosting service to run a discord bot.
Get a VPS
What is the most reliable one, I can pay
Highly opinionated topic
Free services may not be as reliable and we have complex stuffs
True, I just want opinions from ppl with experience
Nothing in this world is free
Go and do some research on it #965291480992321536
You're not going to get a large enough sample size from here to make an informed decision
I like hetzner, but that's one data point
Personally I use Hostinger
In the end pick someone that seems reasonably stable and trustworthy and go with them, if you're asking who to host with then you don't have a big enough setup that moving is going to be problematic if they turn out to suck, you'll find who works best for you over time
Amazon web services
downsides are expensive and complex
highly reliable, though
there are a plethora of service providers that are just as reliable and are cheaper for the individual
Wait, this is interesting. Could you explain it to me like I'm 5? 😅
You only get access to a users's Bio if you're using the Discord API from a user account, you can't get it if you're using a bot and trying to access said information.
User and bots have access to various things on Discord's API, examples:
- Sending messages both users (e.g. you) and bots (e.g. @unkempt canyon) can do it
- Getting a user's bio only users (e.g. you) have access to it
And we are talking about bios as in the bio that you make on your profile to say whatever you want ?
yeah
And thats bad for a bot to grab and print ?
It's not possible
Bots don't have access to it, so they're violating the ToS by "getting" it
Oh thats wild, I guess i didn't understand it because it sounds simple on the outside without actually knowing what you meant
Discord intentionally does not let bots see bios because of data privacy concerns
Bots are automated, users not
A bot could go through an entire server of hundreds of members in a few hours. It would take a user a lot longer.
What "malicious" things could you do with a bio? If it's a privacy concern?
People put potentially sensitive demographic information in their bio that bots could scrape to target them
I think the reasoning is lots of people put out personal information in their bio like their age and where they are from
anyone aware of how to code a rotating playing status on discord bots?
Changing status is rate limited and I would suggest you use it convey exactly that, a status, which is not something that changes for your bot on a timer but to communicate meaningful changes
snipe_author = {}
snipe_msg = {}
snipe_reply = {}
snipe_time = {}
@bot.event
async def on_message_delete(message: discord.Message):
if message.channel.type == 'private' or message.author.bot: return
snipe_author[message.channel.id] = message.author
snipe_msg[message.channel.id] = message.content
snipe_time[message.channel.id] = 'vt: {int(datetime.datetime.now().timestamp())}:R>'
if message.reference:
snipe_reply[message.channel.id] = message.reference.resolved
else:
try: del snipe_reply[message.channel.id]
except exception:
pass
@bot.command()
async def snipe(ctx, channel: typing.Optional[discord.TextChannel]):
channel = channel or ctx.channel
snipe_content = snipe_msg.get(channel.id)
if snipe_msg is None:
return await ctx.send("No message was deleted.")
snipe_author_mention = snipe_author[channel.id].mention
embed = discord.Embed(
description=f"Message deleted by {snipe_author_mention}\n**Content:**\n{snipe_content}\nTime:** {snipe_time
[channel.id]}"
)
if snipe_reply.get[channel.id]:
embed.add_field(
name="Replied to",
value=f'[{snipe_reply.author}]({snipe_reply[channel.id].jump_url})'
)
await ctx.send(embed=embed)
what is wrong with this code?
sniping commands are privacy invasive and often used to mock or harass someone, people delete messages for a reason. won't get much help
Probably good to review the tos/policy you've agreed to if you haven't
I heard it isn't really rate limited but your bot may get taken action on
There's no rate limit info sent back from what I heard?
Not sure though
ah nevermind they're fixed rate limits (2 per second)
the entire TOS or is there a specific part i can read that relates to bots?
There is a separate developer tos and policy. You've agreed to all of it
ty ty
on a seperate note, why would i sometimes put:
@bot.command(pass_context=True)
and other times:
@bot.command()
whats the difference?
ahh gotcha gotcha
To be fair, I see nothing in the TOS or Policy that restricts you from doing this. Other than this very general term where "third party" is not defined and would mean that many discord bots violate this
You will not share API Data with any third party, except in the following circumstances, subject to compliance with the Terms and applicable laws and regulations: (i) with a Service Provider; (ii) to the extent required under applicable laws or regulations; and (iii) when a user of your Application expressly directs you to share their API Data with the third party (and you will provide us proof thereof upon request).
I think you might even be able to argue that you are sharing API data only with discord
-# Not A lawyer, so not legal advice
Hi I have a question regarding a Discord Bot:
I want to check the channel topic of a voice channel (if that's how it called).
I mean the small text users can set at the top of a voice channel.
How can I read that?
Is there currently a way in the Python module?
And if not, can I do that via the REST Api?
When I edit this, it does appear in the Audit Log so I think it should be possible...
What "python module" are you using? There are multiple python libraries for discord bots
Im studying for my undergrad law degree, and to be honest, I wasnt seeing anything that related to the snipe command. However, like i said undergraduate. Although, i assume they could argue that you cant use the bot to harass or otherwise emotionally/mentally harm others as krypton said earlier
TBH your bot is not doing that, the users of your bot are. Which you could outlaw in your own terms
fair enough
There is a section about not bypassing discord privacy features. Message deletion is a privacy feature.
I don't even see this option in the general discord developers page. Do they really not have this implemented yet? :(
It's strange because if it appears in the audit log, they definitly have this event implemented on their side
I'd think
You mean voice statuses?
yeah
Only thing I could find relating to what you said is this:
You will provide and adhere to a privacy policy for your Application that is compliant with applicable privacy laws and clearly, accurately, and fully describes to users of your Application what data you collect, how you use and share such data with us and third parties, and how users can request deletion of such data
I cant find anything on how to get it but you can listen to the
voice_channel_status_update event (idk if discord.py implemented that)
So it's part of the REST API, just not documented yet?
They dont ever define what "privacy feature" means. Based on the explanation below that sentence it seems like they are explaining a different category of action other then things like message deletion. You could probably argue that this feature is required to have an opt out tho.
Thank you for the effort
It's just not merged yet. (I needed a while to understand what I was seeing 😂 )
brothers have came across something that i didnt know existed.
what are you guys using to write your bot's code? discord.py or Pycord?
im currently using discord.py
would it be better to switch to Pycord?
I use py-cord. It is better to stick with what you are using unless you dont have very much code. The main difference between the 2 is how application commands are handled. Py-cord implements app commands in a very similar way to how prefix commands are implemented (if you are familiar with that) discord.py uses the whole command.tree thing that I dont know much about
In the end it is personal preference
and i am coming up on the command.tree thing because im wanting to implement an autocomplete feature for the slash commands
i have about 90 lines of code rn in discord.py
are you able to check if a discord message contains a sticker / doesnt contain a sticker using discord.py
You can check if this list is empty https://discordpy.readthedocs.io/en/stable/api.html?highlight=stickers#discord.Message.stickers
so i check if StickerItem is empty?
you check if the list message.stickers is empty
ty
It's not in the TOS, it's in section 3 of the developer policy https://support-dev.discord.com/hc/en-us/articles/8563934450327-Discord-Developer-Policy
Oi what’s up losers
Was wondering could someone teach me how to use discord.py im a fast learner fr fr
All the YT vids are outdated smh
A hands-on guide to Discord.py
this makes much more sense!
Anyone here know a tut or how to setup a minecraft server that handles the linking process with a discord account and minecraft account with a code, using a discord.py bot?
You will not find (good) tutorials on how to do niche specific things. The good docs will give you building blocks to the individual systems and its up to you to put them together
just use discordsrv
import discord
from discord.ext import commands
import spotipy
from spotipy.oauth2 import SpotifyOAuth
Replace with your Spotify Client ID, Client Secret and Redirect URI
SPOTIFY_CLIENT_ID = "YOUR_CLIENT_ID"
SPOTIFY_CLIENT_SECRET = "YOUR_CLIENT_SECRET"
SPOTIFY_REDIRECT_URI = "http://localhost:8888/callback"
Initialize Discord Bot
bot = commands.Bot(command_prefix="!")
Spotify Authentication
sp = SpotifyOAuth(
client_id=SPOTIFY_CLIENT_ID,
client_secret=SPOTIFY_CLIENT_SECRET,
redirect_uri=SPOTIFY_REDIRECT_URI,
scope="user-library-read, user-top-artists, user-read-playback-state",
)
@bot.command(name="play")
async def play_spotify_song(ctx, spotify_uri: str):
"""
Plays a Spotify song in the voice channel.
"""
if not ctx.voice_client:
await ctx.join_voice_channel()
track_info = sp.track(spotify_uri)
track_url = track_info["external_urls"]["spotify"]
# Use a library like 'youtube_dl' to download the audio stream from the Spotify URL
# and play it in the voice channel.
# Example:
# audio_source = await discord.FFmpegOpusAudio.from_probe(track_url)
# ctx.voice_client.play(audio_source)
await ctx.send(f"Playing: {track_info['name']} by {track_info['artists'][0]['name']}")
anything wrong with this code?
yes, that it violates their tos
sure, but that doesn't change that it violates tos and by extension cannot receive help here
it was sarcasm
!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, will take a look into that
quick question i have the emoji's in my code but they not sending as emoji's https://paste.pythondiscord.com/P42Q
is the bot in the same server with the emojis?
yes
is there any way to have my bot play music from spotify?
not without violating tos, no
You could try and make a deal with Spotify but that is probably impossible at your scale.
Some relevant parts of the tos:
Do not create any product or service which includes any non-interactive internet webcasting service. For example, you can’t create an application which plays content from a single source to several simultaneous listeners.
Streaming of music sound recordings through the Spotify Platform shall only be made available to subscribers to the Premium Spotify Service.
gotcha gotcha
I try to get active developer badge and I waited for 24 hours so I can't see my server in this case
It shows "No results found"
Add the emoji to the bot in the dev portal that might work idk
Is there any free way to host my discord bot 24/7 im broke lol
!hosting
Using free hosting options like repl.it 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.
Short story, no
What risk?
and its like $80!
Its cheap
so its too expensive to buy a cheap vps but cheap to buy a raspi?
Wait whats the limits of heroku free program
heroku stopped with free stuff
Hmm
Risk being you buy the hardware, if you fry it that's your money gone
Vs if you rent a vps and the hardware gets fried, you don't care and that risk is on them
Rasberry pi cooler😎
It wont become fried chicken
"Fry" here being short for any hardware failure
Yes yes a nothing will happen whit a 100 line python bot
Why would there be a hardware failure
Because hardware fails...?
Never has rasberry failed on me NEVER EVER
Is there any hosting service that supports crypto as payment
Unlikely any that are legitimate
😿
Thats why rasberry pi is better it wont scam you
Your call 
it won't really fry randomly if you don't arbitrarily connect something to the gpio or the other connector inputs
Hardware fails for lots of other reasons than electrical overloading, see what I said
It needs to be a community enabled server
So your argument is don't buy electronic devices? Just rent everything you need because "your toaster might fry" "your cell phone might fry" "your refrigerator might fry"
Hardware also has warranties.
You essentially have a "store" of valid keys. You can have a command give "admins" a key to distribute from the store. Than a redeem command that the user inputs the key. If the key is in the store of valid keys remove the key from the store and give the user the reward.
@stark ingot but how?
Do you have some code you’ve already written up where you have a specific error? Since the above message is how you actually do it
codes = ["JaisidjHaiaisjBb", "oq9wuH99qjsjHhA", ...]
def get_code() -> str:
return random.choice(codes)
def redeem_code(code: str) -> None:
try:
codes.remove(code)
except ValueError:
return "Code invalid!
else:
return "Code invalid!"
code = get_code() # maybe "JaisidjHaiaisjBb"
print(redeem_code("JaisidjHaiaisjBb"))
# Code redeemed!
print(redeem_code("lol"))
# Code invalid!
print(redeem_code("JaisidjHaiaisjBb"))
# Code invalid!
Basically lol
How do you detect channel mentions that doesn't belong to the guild?
u could check url for those mentions and match the guild id present in that url
jump_url afaik
regex probably
I found
if any(message.guild.get_channel(channel_id) is None for channel_id in message.raw_channel_mentions)
oh that’s a thing
this is essentially the same as just channel_mentions afaik
I don’t believe channel_mentions is restricted to the current guild, just ones that are cached (since it’s how channel mentions work in the client as well)
kind of a guess though ^
Do you know if there is any other way to detect server invites to other guilds without using regex?
no
there might be something in auto mod or server settings though not sure
Pretty sure it's just regex on automod yeah
I don't think the auto mod will check whether the invite link is from the same guild or not. I only want to delete invite links to other guilds
Would need to do that with regex
hello
https://paste.pythondiscord.com/Q5VQ can someone help me with making the /joincf into a button ?
What have you tried and where are you stuck?
im stuck on making the enter coinflip command into a button.
like im a big noob in this type of thing lmao.
What have you tried? Do you know how to make buttons at all?
not really.
😭
What library are you using?
@fast osprey could you help me with something

My code:
from discord.ext import commands
intents = discord.Intents.default()
bot = commands.Bot(command_prefix='!', intents=intents)
@bot.event
async def on_ready():
print(f'Logged in as {bot.user}')
@bot.command()
async def separate(ctx, input_string: str):
print(f'Received command: {input_string}')
parts = input_string.split(':')
print(f'Split parts: {parts}')
if len(parts) >= 3:
second_part = parts[1]
third_part = parts[2]
await ctx.send(f"{third_part}:{second_part}")
else:
await ctx.send("The input string is invalid. It must contain at least 3 parts separated by ':'.")```
Im trying to get my bot to seperate a combo into just a 2 part thing
Like if i had example:example123:example@gmail.com:example00
I would want my bot to only get the 2nd part and the 3rd part like the 2nd phrase and the gmail
But I tried doing this and my bot isnt responding+no error in the terminal
and no prints?
correct
!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.
This should raise a warning at minimum in your console
Works now but is there a way where i can do multiple at a time instead of one
like maybe if i upload a message file
and it separates the ones from the msg file?
It's not clear what your desired input and behavior are
i just want to seperate combos
I don't know what a combo is
That doesn't really explain what a combo is
I mean that's what split does
you want to look for these.. "combos" in the file?
i know but i want to know if there is a way i can do multiple at a time
multiple what?
Do you have an example of the input you want, and the behavior you want?
multile combos
i want to input multiple combos aka example:example123:example@gmail.com into the bot and have it distribute the 2nd word and the email only
What is the input you want users to put in
an example is going to be more helpful because you keep using the word "combo" which doesn't mean anything in this context. Is this like multiple lines of strings in this format? Are they typing these out, putting them in a file, something else?
Also if you don't want the first part of that, why are users putting it in? There may be a way to simplify the input to both make your code cleaner and make this easier for users
how would i go about making a slash command that only a specific person can use using discord.py?
Make a normal slash command and slap a custom check on top which returns true if interaction.user.id is ...
wdym?
@tree.command(name="admin", description="admin command, guild=discord.Object(id=GuildID))
async def admin(interaction):
if(interaction.user.id == x):
like that?
i am so confused by this
who can help me make welcome bot
You can either stay with your "if" check or use decorator that discord.py provides to you
@app_commands.check(foo)
the foo coroutine should return a boolean, if it returns True then the command is executed, otherwise the app_commands.check raises a app_commands.CheckFailure that you can handle in your error handlers
!d discord.app_commands.check
@discord.app_commands.check(predicate)```
A decorator that adds a check to an application command.
These checks should be predicates that take in a single parameter taking a [`Interaction`](https://discordpy.readthedocs.io/en/stable/interactions/api.html#discord.Interaction). If the check returns a `False`-like value then during invocation a [`CheckFailure`](https://discordpy.readthedocs.io/en/stable/interactions/api.html#discord.app_commands.CheckFailure) exception is raised and sent to the appropriate error handlers.
These checks can be either a coroutine or not...
IMO you shouldn't use a slash command at all. The entire purpose of them is to publish and democratize them, which is the exact opposite of what you want. There's no reason to make a slash command in that case
Another thing you can do is to make a guild command on your test server or a servers you own. Then you can use the integration settings to limit it so that only you can see it.
You should still have a check in your code incase you mess up the permissions though.
Looking for some help to make some code a bit more efficient, to prevent my bot from being rate limited
You would have to post your code and what ratlimit you are running into to get help
I've posted the code in #1330227391951409253
@stark ingot
I want to add a count down function into my bot for this specific command, could anyone help?
server_info = {
"name": "A DayZ Walk",
"password": "...",
"start_time": "2024-12-13"
}
@bot.tree.command(name="info-dayz", description="Shows DayZ server information.")
async def info_dayz(interaction: discord.Interaction):
embed = discord.Embed(title="DayZ Server Information", color=discord.Color.green())
embed.add_field(name="Server Name", value=server_info['name'], inline=False)
embed.add_field(name="Password", value=server_info['password'], inline=False)
embed.add_field(name="Start Time", value=server_info['start_time'], inline=False)
await interaction.response.send_message(embed=embed, ephemeral=True)
seems like you made it. what's the issue?
do you mean this?
<t:1737281969:R>
Yeah that
3 steps:
- parse the date into a
datetime.datetimeobject with.strptime - wrap it in
<t:[timestamp]:[format]>-Ras the format is for relative time (in 10 minutes, in 8 seconds, 4 hours ago) - send it
Yeah ngl that kinda confuses me
how?
I don't know python that well so most of it confuses me
these are all the formats

