#discord-bots
1 messages · Page 233 of 1
i should move to that then
!d aiohttp
im just wonderign why
also you're on the spot
magician
Is it paid
yes
albeit i purchased the dirt cheap one
maybe time to upgrade
at least i can transfer it to a less congested line
its a private bot for now
when i make it public ill have better solutions for it
Anyways in case you'll be migrating to VPS (you eventually will) here's hosting guide https://www.pythondiscord.com/pages/guides/python-guides/docker-hosting-guide/
This guide shows how to host a bot with Docker and GitHub Actions on Ubuntu VPS
thank you
have a cookie 🍪
If it's private and already getting ratelimited the hosting is questionable ||thanks for the cookie||
this is my first bot hosting experience, so in a way yea its not great but i get to learn about it

team's there pretty quick to answer to my concerns so thats also a plus
i was more concerned that my code is probably doing some unnecessary stuff, since im also not a pro coder/coder by trade
im just fascinated that i can do things conveniently from my phone
Can you use a non bot discord account to upload files as well?
I have been able to use a bot to send files in a server but was wondering if i can do it without a discord bot
you could use a webhook
I send memes to my friend via dms and sometimes it is a lot 😅 so i wanted to automate it
that isn't possible
what about in a server
you could use a webhook in a server
where can i learn that?
https://discord.com/developers/docs/resources/webhook#webhook-resource
https://discord.com/developers/docs/resources/webhook#execute-webhook
(and if you want to avoid making the requests yourself; https://discordpy.readthedocs.io/en/stable/api.html#discord.Webhook.from_url)
alright!
you can create a webhook by going to a text channel's settings -> Integrations
you can also do that with a bot, but that would defeat the purpose i suppose
Yeah thanks zeffo!
I'm trying to count online, idle and dnd members. Any ideas why the lists are blank ?
@loop(seconds=statscooldownamount)
async def checkonlinemembers():
try:
guild = bot.get_guild(guildID)
online_members = []
idle_members = []
dnd_members = []
for member in guild.members:
if member.status == discord.Status.online:
online_members.append(member)
elif member.status == discord.Status.idle:
idle_members.append(member)
elif member.status == discord.Status.dnd:
dnd_members.append(member)
print(online_members)
print(idle_members)
print(dnd_members)
all lists
maybe its an intent issue, u can fix that by adding
intents = discord.Intents.all()
bot = commands.Bot(command_prefix="{ur prefix here}", intents=intents)
client = discord.Client(intents=intents)
all intents to ur bot
ohh so that's what i missed. I had Intents.default() instead of all
thanks!
np
👀
i want to create a slash command but i can't import app_commands from discord, can someone help me?

TypeError: Unsupported operand type(s) +: 'discord.Client' and 're.Pattern'```
How to solv
Last version of dpy installed?
You need specifically presences intent
yes
Do pip show discord.py
Hi im currently developing a discord bot but i get into a problem, is there anyone who have a little experince with it?
and i what i have to do after that?
What output do you have
What the problem is
Okay seems correct, maybe venv issue
What interpreter do you have configured in vscode
ohm so i tried to check on my other python file on my on_message function if it is an actual bot and its id is =123456 etc and apparently doesnt rlly want work
python
so everytime my first bot sends a message onto my channel i want the second bot in dif file reply to that message with anything like a "hi" message
You can if message's author is bot with msg.author.bot
Assuming msg is your parsed Message
Guys I'm trying to install discord_components library in REPLIT but for some reason I can't
Could you do ctrl + shift + p -> Python: Select Interpreter and show the list to me
Outdated, use discord.py 2
is it possible to hop on a vc and i can show my screen im sure it might be some simple mistake but i have been tried +4 hours and previously also a lot
Sorry can't really do that
CAN I USE IT IN REPLIT
Discord.py yes
HOW
Is your shift broken
said failed
Open up that terminal or command line whatever it's called in replit and do poetry add discord.py
so this is how my on_message function look like:
bot1 = commands.Bot(command_prefix=':', intents=intents)
@bot1.event
async def on_message(message):
if message.author == bot1.user:
return
#1092844660235440309
if (message.author.id == "393841441656406026" or message.author.id == "1092844660235440309") and (message.author != bot1.user):
print("Other bot sent a message!")
await message.channel.send('Igaz ag a norman ideju nem bela user kuldte az uzit')
else:
await message.channel.send('Hi hamis ag')
await bot1.process_commands(message)
but everytime i type anything on channel it goes the else branch (thats normal) but when i make the other file's bot to write onto my channel sth it still goes there (but i want to go the true branc that time)
🧐
But you seem to have python installed
Is python extension enabled
Oh heck there are now headers in discrod???
yes
Bro this is wild
Can you explain, I'm still a newbie
Uh that's kinda weird let's figure it out
?
i have to go work now, can we do it tomorrow if you want
@vale wing do you know the problem?
Do you mean my problem?
no
K SORRY
Your condition needs to be like this
if message.author.bot:
return
For comparison with exactly your bot
if message.author.id == bot.user.id
yes i did this
apperently the mistake i have made is that i tried to find the other's bot id (i wrote it by the bot then i copied from my discord server) both were different from each other
and apparently i guess not even one of them was correct so it was a bit of riculous now im trying with the name attribute
well i have no clue how to get the discord bots id (i thought i could ) but well with name it work
class Prot(discord.ui.View):
response1=None
list_result=[]
def __init__(self, users:list):
super().__init__(timeout=10)
self.users1=users
@discord.ui.select(
max_values=1,
placeholder="Choose your action",
options=[
]
)
async def selected(self, interaction:discord.Interaction, selected:discord.ui.Select):
async def on_timeout(self):
self.disabled = True
await self.message.edit(view=self)
print("TIMEDOUT")
self object has on attribute message
how to fix
Can you use RPC for bots?
how would i go about turning hours & minutes into unix as well?
@client.command()
async def timetest(ctx, *, message):
s = message
f = time.mktime(datetime.datetime.strptime(s, "%d/%m/%Y").timetuple())
d = round(int(f))
await ctx.send(f"<t:{d}>")```
this code turns d/m/y into a timestamp but you cannot specify the exact time in hours & minutes
What do you mean by that?
so i can tell it a date
in dmy format
but i cant tell it an exact time either (hours & minutes)
so like lets say 4/29/23 18:00
it wouldnt take the last part of the input (18:00)
What
So from my knowledge you would want to use %H:%M I believe to get the hour and minute.
anyone know how to add paywall to a discord bot (crypto only)
not related to discord bots and you would probably want a global check
how so
?
i’m asking a genuine question
what do you mean by 'how so'
^ @smoky sinew
Gotta serious question about discord bots in python
besides that is there any other way
How do I make them
i’m using a whole different wrapper
then what do you want me to say
is it hikari you're using
ya
but i’m just looking for recommendations for adding a paywall to it
preferably crypto
how is that related to discord bots
because i’m wanting to add it to my bot
that doesn't make it related
i don't know anything about crypto
and implementation varies widely on the crypto you're using
R u asking the way to incorporate it with the layout of sending that. Or what to use.
what to use for it
discord api is all about the websocket protocol, and ratelimits for which you could work around by exponential backoffs and stuff, but wrappers like discordpy, hikari, handles all that for you, so just learn Python, visit their maintained git repo, see the examples, and see what each of their those methods do in the documentation of the wrapper
Hay guys, can someone tell my why its gray?, i cant use it in PyCharm
why do you need that obscure module at all?
there's no need for monkey patching anymore, Danny had decided to take back his decisions and implement the newer API versions of Discord API in Discord.py module
because i want to use embed buttons
are you following a tutorial?
nah i following chatgpt xD
chatgpt's dataset is limited to 2021, a lot has changed since then
i see xD
if you want to build a decent discord bot and not waste your time for very basic one that nobody anymore really cares about, you'll need to know what you're doing, so go through http://docs.python.org/tutorial
once that's done, see the docs of the discordpy module
thx ❤️
but one question i have.. how can i do commands from main to commands class.. if i start it dont works
FR if i know that earlier i never asked ChatGPT for it.. i spent 7 hours for nothing..
how do i download the discord client again
How do I disable a select menu on timeout
await interaction.response.send_modal(NumberChoice()) TypeError: __init__() should return None, not 'coroutine'
class NumberChoice(discord.ui.Modal, title="Select the number"):
async def __init__(self):
self.result_list=[]
super().__init__(timeout=30, custom_id="select_num")
number=discord.ui.TextInput(label="Enter your Number")
async def on_submit(self, interaction: Interaction, modals:discord.ui.Modal):
self.result_list.append([interaction.user,modals.value[0]])
await interaction.response.send_message(f"{interaction.user} chose the number {modals.value[0]}")
print(self.result_list)
class ChooseBut(discord.ui.View):
def __init__(self,ctx):
super().__init__(timeout=30) #select modal input timeout
self.value=None
self.ctx=ctx
@discord.ui.button(label="click to Choose!", style=discord.ButtonStyle.green, custom_id="join1")
async def menu1(self, interaction:discord.Interaction, button:Button):
await interaction.response.send_modal(NumberChoice())
__init__ cant be async
thanks
async def on_submit(self, interaction: discord.Interaction):
await interaction.response.send_message(f'Thanks for your feedback, {self.name.value}!', ephemeral=True)
where did they fetch the feedback
the value of name field
oh ok
why doesn;t this program work, https://paste.pythondiscord.com/xogovedoga
what do you mean by work? the command?
!d discord.Embed
class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.
len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.
bool(b) Returns whether the embed has any data set.
New in version 2.0.
x == y Checks if two embeds are equal.
New in version 2.0...
i'm planning to make it able to create it's own command for generating it's own embed
my plan is to allow people to create their own character template
but it being a thing only available for admins
settled for just a role
yeah
the only thing to be inferred by that
Hey there guys, i have 2 files main.py and colors.py. In the second i have a function that contains a dictionary and returns it unpacked. So in the first file i import this function and i want to use it for format a string. But i get a KeyError
This is my code:
# colors.py
class TerminalColors:
header = '\033[95m'
purple = '\033[0;35m'
blue = '\033[94m'
cyan = '\033[96m'
green = '\033[92m'
red = '\033[91m'
orange = '\033[93m'
yellow = '\033[0;33m'
bold = '\033[1m'
underline = '\033[4m'
end = '\033[0m'
def get_colorsformat():
color_vars = {
'header': f'{TerminalColors.header}',
'purple': f'{TerminalColors.purple}',
'blue': f'{TerminalColors.blue}',
'cyan': f'{TerminalColors.cyan}',
'green': f'{TerminalColors.green}',
'red': f'{TerminalColors.red}',
'orange': f'{TerminalColors.orange}',
'yellow': f'{TerminalColors.yellow}',
'bold': f'{TerminalColors.bold}',
'underline': f'{TerminalColors.underline}',
'end': f'{TerminalColors.end}',
'TIME': f'{datetime.now().strftime("%H:%M:%S")}',
}
return {**color_vars}
And my other code
# main.py
print(log.format(get_colorsformat(), USERNAME=f"{interaction.user.name}",
CHANNEL_NAME=f"{interaction.channel}"))
ARE YOU KIDDING
TypeError: View.__init__() takes 1 positional argument but 2 were given
pls tell me the fix of this error
You gave an argument to ' View' class while it takes no argument
show code
bot is not allowing me to send codes as its length is more than max limit of automod
!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.
!d nextcord.ui.View
class nextcord.ui.View(*, timeout=180.0, auto_defer=True)```
Represents a UI view.
This object must be inherited to create a UI within Discord.
New in version 2.0.
Pretty this is not how you create views
view = nextcord.ui.View(dropdown, prev_button, next_button)
https://github.com/nextcord/nextcord/tree/master/examples/views
here are many view examples in nextcord
you can look into this
A Python wrapper for the Discord API forked from discord.py - nextcord/examples/views at master · nextcord/nextcord
how to fix error https://pastebin.com/sq6vhLbD
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
i think you meant interaction.response.send_message
is there any mistake in tht line
Yes? That's most likely where the previous error came from
how could i make changes in that code , i am newbie in nextcord.py module that's why i am asking like a noob 🐧
!d discord.TextChannel.send
await send(content=None, *, tts=False, embed=None, embeds=None, file=None, files=None, stickers=None, delete_after=None, nonce=None, allowed_mentions=None, reference=None, ...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Sends a message to the destination with the content given.
The content must be a type that can convert to a string through `str(content)`. If the content is set to `None` (the default), then the `embed` parameter must be provided.
To upload a single file, the `file` parameter should be used with a single [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") object. To upload multiple files, the `files` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`File`](https://discordpy.readthedocs.io/en/latest/api.html#discord.File "discord.File") objects. **Specifying both parameters will lead to an exception**.
To upload a single embed, the `embed` parameter should be used with a single [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") object. To upload multiple embeds, the `embeds` parameter should be used with a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.11)") of [`Embed`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Embed "discord.Embed") objects. **Specifying both parameters will lead to an exception**.
there is delete_after argument you can specify
delete_after (float) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.
where to put it?
error1 = "Липсва таг на човека, който искате да забраните !"
fix1 = "`!ban @(таг на човека) (Причината за забраната)`"
emb1 = discord.Embed(title='! ‖ ERROR ‖ !',colour=discord.Colour.dark_red())
emb1.set_author(name="")
emb1.add_field(name="", value=f"═════════════════\n**Таг:** {author}\n**Грешка:** {error1}\n**Поправка:** {fix1}\n**Причина:** {reason}\n═════════════════")
await ctx.send(embed=emb1)
await asyncio.sleep(3)
await ctx.message.delete()```
i dont know which message you want to delete
when you use .send you specify delete_after argument
thats argument not a function do you know what argument is?
no 😅
@slate swan
guys, how do i gather user ID using my cog?
i'm planning to cryptograph that ID
so hackers won't use that ID to do whatever they want with that person
and also only the system knows the ID of that user and i won't be able to know it since it's cryptographed
property id```
Equivalent to [`User.id`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.id "discord.User.id")
Hey, could you help me maybe with my script?
Don't want to be annoying if you don't have time, please let me know
Basicly you rightclick on a message, Click on "Apps" and select the "Report" command, could you maybe help me?
I got a script right here but its not working as its supposed to so```
https://paste.pythondiscord.com/utunojunox
first of all you shouldnt use discord_slash its really outdated since discord.py has slash commands support built in already
so, what should I use then?
here are examples
if you want to do Report command available under Apps section when clicking on a message you should use client.tree.context_menu
this is example of such context menu
https://github.com/Rapptz/discord.py/blob/master/examples/app_commands/basic.py#L92-L113
and it even does what you need
ty
Can someone help me?
a reminder that programming discord bots can indeed be useful in your future
my reminder is just gonna be the sample code of a running twitch chat bot
I got intensely happy when I saw this
The embed doesn’t work
Hey, I have one more question:
https://paste.pythondiscord.com/ezekotaray That is my script
I tried to run it, but it gives me this error
ModuleNotFoundError: No module named 'settings'
@formal basin
But embed=embed didn’t work
embed= not embedlog=
But I named it embedlog
you don't know what keyword arguments are do you
Oh I see
nice
Any good guides for making a Discord bot that utilises slash commands and embeds? Ideally text but I don't mind a video
embeds are pretty simple to implement
appreciate the quick response, tyvm
is there any way to send images with nsfw tag with url in an embed ?
on the same topic, 
@smoky sinew
Sorry for the ping but it's just so you know it's here but it's kinda urgent
, so whenever you have time lemme know.
i'm pretty sure spoilered images just prepend spoiler to the file name
e.g. SPOILER_image.png
as for the URL part, i'm not sure
Yes, but i am providing it as a url which doesn't have a spoiler in the name
I see
I will just go the long way
Thanks for the input
dont mind the code if its broken i have removed irrelevant parts,
url = "https://www.achaheart.org/media/1836/asd-illustration.jpg?mode=max&upscale=false&width=950"
end = 'jpg'
async with aiohttp.ClientSession() as session:
async with session.get(url) as resp:
img = await resp.read()
with io.BytesIO(img) as file:
file = discord.File(file, filename=f"SPOILER_Imagination.{end}")
embed.set_image(url=f"attachment://SPOILER_Imagination.{end}")
await ctx.followup.send(embed=embed,file=file)
so the file name is SPOILER_Imagination.jpg in this particular case, and in an embed, it doesnt work, although i havent tried without embed either
idk what doesn't work means
it doesnt have the spoiler tag
so that the image is hidden
thats for text
async with bot.http_session.get(IMAGE_URL) as response:
with io.BytesIO(await response.read()) as data:
file = discord.File(data, filename="SPOILER_test.jpeg")
await ctx.send(file=file)
this worked for me
try embed
what you're doing won't work because SPOILER_Imagination isn't saved locally
i don't know if there's a way to set an embed image to a BytesIO object but i will check
actually wait
ah wait you don't need to do that

sorry i have no clue how to work with discord files
i wouldn't merge tkinter and discord.py code if i were you but you can't use while True with a running event loop
well you're not doing anything as of right now
the function is not even being called anywhere
then i'm not sure
like i said i don't think tkinter will work or work well with a running discord bot
Why not
!e
import asyncio
async def while_task(id: int) -> None:
while True:
print(id)
await asyncio.sleep(0)
async def main():
task_1 = asyncio.create_task(while_task(1))
task_2 = asyncio.create_task(while_task(2))
await task_1
await task_2
asyncio.run(main())
@naive briar :x: Your 3.11 eval job has completed with return code 143 (SIGTERM).
001 | 1
002 | 2
003 | 1
004 | 2
005 | 1
006 | 2
007 | 1
008 | 2
009 | 1
010 | 2
011 | 1
... (truncated - too many lines)
Full output: too long to upload
!d discord.Member.discriminator
property discriminator```
Equivalent to [`User.discriminator`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.discriminator "discord.User.discriminator")
i wouldn't know anything about that but you could just keep the GUI as a separate program
hey guys, im trying to get entries on a table with aiosqlite and its returning empty messages,
"""Appends the avatar url from the database table by joining them together."""
fetch = []
async with self.bot.database.cursor() as db:
await db.execute(f'SELECT * FROM uwu WHERE Member = {member.id}')
check = await db.fetchall()
if check is not None:
for u in check:
fetch.append(f'hi testing {u[1]}\n')
return ''.join(fetch)
except Exception as e:
return e```
i checked the data in the table and they are all there, not sure what to do
@smoky sinew do you know how to solve this issue?
why did you ping me
!sql-fstrings also look at this
Don't use f-strings (f"") or other forms of "string interpolation" (%, +, .format) to inject data into a SQL query. It is an endless source of bugs and syntax errors. Additionally, in user-facing applications, it presents a major security risk via SQL injection.
Your database library should support "query parameters". A query parameter is a placeholder that you put in the SQL query. When the query is executed, you provide data to the database library, and the library inserts the data into the query for you, safely.
For example, the sqlite3 package supports using ? as a placeholder:
query = "SELECT * FROM stocks WHERE symbol = ?;"
params = ("RHAT",)
db.execute(query, params)
Note: Different database libraries support different placeholder styles, e.g. %s and $1. Consult your library's documentation for details.
See Also
• Python sqlite3 docs - How to use placeholders to bind values in SQL queries
• PEP-249 - A specification of how database libraries in Python should work
and check if the case is correct because your database may or may not be case sensitive
My discord is all about esports tournaments, managed entirely through discord. I want my bot's tournament timer to work even after bot restarts, so I am saving unix time of the specified start time of the tournament to my database of-course. My plan was to have some asyncio tasks on bot startup, and on adding a new tournament, that'd do asyncio.sleep until the current time is the unix timestamp that is in my database. However, I think I'd need something more efficient this time, as I'd also like to offer them the feature to cancel/stop/remove a tournament. Any idea?
okay, I think I am just looking for asyncio.Task.cancel lol
hello
!d discord.ext.tasks.loop perhaps
@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
If you're doing background tasks in dpy it's best method in most cases
yeah, I could probably workaround with tasks.Loop class as well, however, it is more geared towards background loops rather than tasks, so it can get restrictive
like doing count=1
If you don't need ws connection ie receiving events you can just use requests module and simply do requests to discord API from your tkinter app
Would want to use executor tho
Good Sleeky — Oggi alle 11:39
why this dosent works (i used the command and nt happens)
import discord
from discord.ext import commands
import json
with open("Globalvariables.json") as f:
Variables = json.load(f)
adminrole = int(Variables["Admin"])
with open("Warns.json") as w:
Warndata = json.load(w)
class Warncog(commands.Cog):
def init(self, bot):
self.bot = bot
@commands.has_role(adminrole)
@commands.command()
async def warn(self, ctx, user, Reason):
if user in Warndata:
Warndata[f"{user}"].append(Reason)
else:
Warndata.setdefault(f"{user}", [])
Warndata[f"{user}"].append(Reason)
async def setup(bot):
await bot.add_cog(Warncog(bot))
use package cookies-discord-components instead
but I should note that you should use discord.py 2.x or some other fork instead of some very old library
just don't use relative imports lmao
show me the line where you're importing that fails
show the file structure
How are you executing the code?
How are you running that file?
Yeah
Maybe try invoking as a module instead?
class NumberChoice(discord.ui.Modal, title="Select the number"):
def __init__(self):
self.result_list=[]
super().__init__(timeout=30, custom_id="select_num")
number=discord.ui.TextInput(label="Enter your Number", max_length=3)
async def on_submit(self, interaction: Interaction):
self.result_list.append([interaction.user,self.number.value[0]])
await interaction.response.send_message(f"{interaction.user} chose the number {self.number.value[0]}", ephemeral=True)
self.result_list.append([interaction.user,self.number.value[0]])
client.mismatch_result[interaction.guild.id]=self.result_list
print(client.mismatch_result[interaction.guild.id])
why does this code add only the last person who replied and not all the users who answered?
@client.command()
async def clear(ctx):
if ctx.author.guild_permissions.administrator:
args = ctx.content.split()
if len(args) == 1:
await ctx.channel.purge(limit=10)
else:
try:
count = int(args[1])
await ctx.channel.purge(limit=count+1)
except ValueError:
print("ValueError!")
Why does the /clear command not worrk
it hhasnt any problems but the bot wont Delete the messages
how to get members count of a server where the bot is
how to activate button in other class in v.2 ?
i try this:
assert self.view is not None
view: Menu_Lang = self.view
self.view.children[0].disabled = False
it doesnt work (if so i have only one button)
!d discord.Guild.member_count
property member_count```
Returns the member count if available.
Warning
Due to a Discord limitation, in order for this attribute to remain up-to-date and accurate, it requires [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") to be specified.
Changed in version 2.0: Now returns an `Optional[int]`.
It didn't work

You already have d.py v2 though?
d.py natively supports components/slash commands now
But what is the solution
Use discord.py instead of cookies-discord-components or whatever
do you mean this
yes that is what they said
yo
could you give me a syntax to restrict the command to people who have a specific role in a specific guild
!d discord.app_commands.checks.has_role
@discord.app_commands.checks.has_role(item, /)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check "discord.app_commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.
If a string is specified, you must give the exact name of the role, including caps and spelling.
If an integer is specified, you must give the exact snowflake ID of the role.
This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.MissingRole "discord.app_commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.NoPrivateMessage "discord.app_commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure "discord.app_commands.CheckFailure").
New in version 2.0...
@tree.command()
@app_commands.checks.has_role(123456789) # ID of the role, can be name as well
async def cool(interaction: discord.Interaction):
await interaction.response.send_message('You are cool indeed')
thanks
does bot.add_check() work with slash commands?
if not how do I add checks for slash commands (disnake)
also why can't I find a slash command example on their repository
i swear it existed
am I blind because I can't see it there... is it supposed to be what's inside subcmd.py?
or does it not have a separate file of its own
i think thats the case
ty, that works
for global checks, i think youd want this
https://docs.disnake.dev/en/stable/ext/commands/api.html#disnake.ext.commands.InteractionBot.add_app_command_check
thanks!
I need to take a look at a discord economy bot code using discord.py
o Sorry
I have been trying to make a anti toxicity thing and make a thing so they can’t bypass it and found something online but it doesn’t seem to work
Anyone know?
Anyone
Why are you even implementing multiple variations of each word but with different cases? Just .lower() or .upper() the message content and make a list according to that
you could also try using levenshtein distance
Anyways, is there a way to get discord rpc data from a user?
nvm, its activity. Though it'd be something related to rpc
Where do I put the .upper()?
you use it on the message content to make it of 1 case
!e
print("TEST".lower())
@lyric sphinx :white_check_mark: Your 3.11 eval job has completed with return code 0.
test
What if they do it in lower?
why would it matter?
Because they would bypass it
you make the string always the same case to not implement both versions of the word in your list
rn you're doing "X", "x"
but you can just .lower() and check for "x" or .upper() and check for "X"
Can I do both?
why?
If i do .lower() and they do an upper version will it get deleted?
thats the point?
To delete the words
i didnt ask whats the point, i said thats the point
to ignore the case in which user wrote the message
also, you're doing word in message.content, but message content is a string, so iterating over it -> iterating over characters, not words
Can you just give me an example
ok, couple of minutes
!e
banned_list: list[str] = ["word_1", "word_2"]
message_content: str = "WoRd_1"
if any([word in banned_list for word in message_content.lower().split()]):
print("Bad message detected")
@lyric sphinx :white_check_mark: Your 3.11 eval job has completed with return code 0.
Bad message detected
although you should just use a profanity filter library
Ohhh
!pypi profanity-check
or this ^
you could set a ,,limit" for the ,,amount" of profanity and delete all messages in which the profanity amount is higher than the limit
Can I not have spaces in the words?
!e what ```py
print("hi" in "hello hi")
@smoky sinew :white_check_mark: Your 3.11 eval job has completed with return code 0.
True
Will it not work with spaces
Because I’m trying
profanity-check is better
It’s not profanity it’s toxicity
^
just use profanity-check
oops, seems like i didn't really read his code correctly, mb. Long time didn't use python.
Can you give me an example
? install profanity check, then run it on the message, if the profanity is higher than <x> - delete the message
well, yeah, you pip install it, like any other package
Then can you show me the code for it
i already said what you have to do
its like 2 lines, just check the profanity check page and you'll see how to use it
why?
what command are you running?
pip install profanity check
are you doing pip install profanity check or pip install profanity-check
Yes
are you trolling?
like, what yes? how am i supposed to understand which of these options is yes?
No
k im done 💀
Look
well, you import it, because if you want to use a package - you need to import it
from profanity-check import profanity-check
I think you're simply not ready for discord bots. Learn more basics of python, then get into bot development. Its not an easy process.
open the package page on pypi and check how it works. It has a great example of how to use it
Ok
So It’s telling me to write the bad words
?
In the usage
it shows how it works
Yeah it’s telling me to write the words
i can't tell if you're trolling or not
And say how much of profanity it’s worth
well yeah, then you just use this amount of profanity to determine whether the message needs to be deleted
I want every word of profanity deleted
you can't delete every word of profanity, the algorithm that this package uses is far from perfect
more precision -> less speed
But that gonna be hard to write every single profanity word
you dont need to?
the algorithm already has a db of bad words
it seems to me like you're not really understanding anything of what you're doing
Can’t I just make every word in the db get deleted
well, the words are only the basic ones, people tend to try and get around the blocks by messing up the way they write the words
so by deleting every word only from the db, you'll only delete exact matches
while the algorithm determines how close is it to a bad word
if i say fuk instead of fuck it won't get deleted in your code
Just never mind
Honestly, my best tip (no aggression intended), would be to go and actually learn programming before going into bot development
I swear, its so much better and easier when you actually understand what you're doing
Thanks for your help
Ok, so I need help with events, I've been trying to use the on_message event but i dont know how to use it.
any examples that could show me how?
im having an argument with my friend im making a bot with him and basically he wants to make tickets when their called #bicxter etc whatever but i think it hsould be #ticket-5001 or something because we store the channel ids in database and its easier to get it with the ticket- thing idk
which should i do
pls how can i make a command accessible only in a specific guild ?
your choice whether you want to try naming it after the author vs using an incrementing number, but trusting the channel name is a fragile approach since any admin can rename it, whereas channel id stays the same
god i love abusing private discord.py variables
Why am I getting AttributeError: 'Intents' object has no attribute 'GUILD_VOICE_STATES' from this?
nvm chatgpt knew
isn't that a discord.js intent
it was supposed to be voice_states
also intents.messages = True is included in Intents.default(), so i'm assuming you meant to do intents.message_content = True
.default() enables all non-privileged intents
no such thing as attribute message_content
it's supposed to be messages
then you're using an outdated version of discord.py
either way default() enables messages
how do i check
discord.__version__
also why does this just hang on voice_state.channel.connect() forever 😭
try:
connection = await voice_state.channel.connect()
except discord.ClientException:
connection = get_voice_client_from_channel_id(voice_state.channel.id)
1.7.3
ah yes
classic version
fr tho
i wonder if the API gateway that 1.7.3 uses is going to get removed soon
considering it's more than 2 years old at this point
i will make my own super basic wrapper with requests
👍
@smoky sinew do you know what's with this tho
okay i just checked 1.7.3 uses v8
no clue
fair enough
can i add a timeout to the await somehow?
because it is connecting but never getting past that await still
i don't think you can interrupt a coroutine like that
also i just checked, and v7 got removed in february so you might only have a few months left of using 1.7.3
until you're forced to migrate
forced how
your bot wouldn't start
don't need it to start if it's already running
i'm going to assume that was a joke but i genuinely can't tell
Is there a way i can terminate a view after it has completed what it was meant to do?
more specifically, if a view had a button callback is there a way to disable that button after it has completed what it was meant to do?
i thought of doing button.disabled = True from the button's callback but maybe i dont understand how its meant to work
that would work fine, you just have to edit the message with the new view afterwards
await interaction.edit_original_response(view=self)
oh yep that did it, thanks!
i used interaction.response.edit_message instead but yeah same effect
i'm pretty sure those do different things but i always forget which one is which
oh? I'll look into that later then, i chose that to stay consistent with my code ¯_(ツ)_/¯
I need to take a look at a discord economy bot code using discord.py
👌
lmao i stopped paying attention to discord.py updates after 1.6 sorry
allowed_pstfxs = [
"ня", "nya"
]
async def on_message(message):
if not any(message.endswith(postfix) for postfix in allowed_pstfxs):
await message.delete()
pls how can i make a command accessible only in a specific guild ?
what library?
also text command or slash command
pycord
both pls
well with a text command you can just get the guild id from the context and if its not in a specific list of guild ids then dont run the command
idk pycord slash command tho
ok so after some quick research, there is a guild_ids parameter you can set when creating a slash command to make it only visible to those guilds
hope I helped. if you need more specifics, ask in #1035199133436354600
thanks
i installed discord-py-slash-command but when i try to import it can't find it can anyone help me
don't use it, discord.py and its forks have added slash command support already
how do i use discord.py slash commands
ok a very basic slash command example:
@bot.tree.command(name='avatar', description="gets a requested user's avatar")
@app_commands.describe(user='the user you are trying to get')
async def _avatar(interaction: discord.Interaction, user: discord.User):
await interaction.response.defer(thinking=True)
embed = discord.Embed(title=f"{user.name}'s Avatar", url=user.avatar.url)
embed.set_author(name=f"{user.name}#{user.discriminator}", icon_url=user.avatar.url, url=user.avatar.url)
embed.set_image(url=user.avatar.url)
embed.set_footer(text=f"Requested by {interaction.user.name}#{interaction.user.discriminator}", icon_url=interaction.user.avatar.url)
await interaction.followup.send(embed=embed)
imports:
import discord
from discord.ext import commands # for the bot
from discord import app_commands # for the slash command```
You also need to sync the commands
how do i do that
@commands.Cog.listener()
async def on_raw_reaction_add(self, rre):
if rre.emoji.name == "\N{OPTICAL DISC}":
#print(rre)
channel = self.bot.get_channel(rre.channel_id)
if channel != None: #not a dm
message = await channel.fetch_message(rre.message_id) #works
else: #a dm
print(self.bot.get_channel(rre.channel_id))
user = self.bot.get_user(rre.user_id) #works - returns ClientUser
message = user.get_message(rre.message_id) #DOES NOT WORK - ClientUser has no attribute get_message
reaction = get(message.reactions, emoji=rre.emoji.name)
COUNT = reaction.count
if COUNT > 1:
await self._dvonreact(message.content)
await message.add_reaction("\N{DVD}")
hello, I need a little help, I'm trying to get a message object using only a user id and message id, I've tried this and a few others but it doesn't work
What doesn't work
message = user.get_message(rre.message_id) This line. I can't find a way to get the message object
how do sync my slash commands
How to? Bot checks users for a role > bot finds someone with that certain role > bot gives a new role and takes away that certain role.
!d discord.TextChannel.fetch_message - that's why we have the docs
await fetch_message(id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Retrieves a single [`Message`](https://docs.pycord.dev/en/stable/api/models.html#discord.Message "discord.Message") from the destination.
You already have the channel object, just use that
the problem with this is, I've already tried getting the channel using the channel ID, when I put a dm channel id in get_channel, it returns None
that's why I used channel == None as check whether it is a dm channel or a channel in a guild
Help me fellow programmers.
Oh it seems you all are busy, ill comeback later
!d discord.User.dm_channel - that's still why we have the docs. You already have the user/member object, so, you know
property dm_channel```
Returns the channel associated with this user if it exists.
If this returns `None`, you can create a DM channel by calling the [`create_dm()`](https://docs.pycord.dev/en/stable/api/models.html#discord.User.create_dm "discord.User.create_dm") coroutine function.
also saw this, but i only have access to a ClientUser object, not a User object
oh also I've looked into how to get a user object using only the id, my search might not be exhaustive though. I only came across client.get_user(user_id) which returns a ClientUser
Then it was your client that added the reaction 🤷
@bot.event
async def setup_hook():
print('loading slash commands')
await bot.tree.sync()```
sorry was busy
no problem thank tho
it takes a few minutes for the commands to register
the first time
but after 5 minutes you should see them
thanks
will do thanks
btw im usually not available after this time each day as i will be alseep
*asleep
well yeah, I was hoping that I could get access to the dm_channel between the bot (the client) and the user who sent a message to it, using info that on_raw_reaction_add() receives
how can it be understood. no error and the code does not work.
I found a workaround! thanks for the help @naive briar
"Bot checks users for a role" — don't really get what you're trying to do
"Bot finds someone with certain role" — you can get all roles members via role.members if that's what you meant
"Bot gives a new role and takes away that certain role" — member.add_roles() and member.remove_roles()
If any additional explanations needed feel free to ask
What i mean with first one is that the bot checks all the server members for a role and when a member has that role, he removes and gives him another one.
.
Help pls

If I rephrase it as "bot gets all members with selected role, removes that role and gives new one" would it be what you mean
yes
First of all, use SQL parameters
Don't use f-strings (f"") or other forms of "string interpolation" (%, +, .format) to inject data into a SQL query. It is an endless source of bugs and syntax errors. Additionally, in user-facing applications, it presents a major security risk via SQL injection.
Your database library should support "query parameters". A query parameter is a placeholder that you put in the SQL query. When the query is executed, you provide data to the database library, and the library inserts the data into the query for you, safely.
For example, the sqlite3 package supports using ? as a placeholder:
query = "SELECT * FROM stocks WHERE symbol = ?;"
params = ("RHAT",)
db.execute(query, params)
Note: Different database libraries support different placeholder styles, e.g. %s and $1. Consult your library's documentation for details.
See Also
• Python sqlite3 docs - How to use placeholders to bind values in SQL queries
• PEP-249 - A specification of how database libraries in Python should work
Second, use async db wrapper
Judging by syntax you have there it's most likely sqlite3, use aiosqlite
Third, .fetchone() may return empty list but you're still trying to access the first element which might simply not exist. You need to handle that situation
Huh
Forth, use proper naming convention
Fifth, since no errors appear you probably have bad error handler that eats up unknown errors, make sure it raises the exception if it hasn't been handled
Ik, many things to fix but you should definitely work on all these
Step by step
anyone know how to add buttons in an embed?
guys do u have a good tutorial for discord bot making in yt
Yt tutorials are pretty outdated. There's a quick start guide in the documentation you can check out, and if you need help with anything specific you can ask here
In my welcome message I use easy_pil so I need the member.avatar.url but when a user doesn’t have any pfp, the messages doesn’t send. What can I do?
use display_avatar instead of avatar to get user avatar
Thank you
someone know why i can't import app_commands from discord?
how to make persistent cooldown commands
like after i restart bot cooldown ends
you could probably use a db - which isn't an idea I like
Don't think there's any other way
please use #bot-commands
Any help? #1102304738055291063 message
async def warnings(ctx, user: discord.Member = None):
if user == None:
users = ctx.author
await open_account(user)
users = await get_warns_data()
warns_amt = users[str(user.id)]["warns"]
em = discord.Embed(title = f"{user.name}'s warnings", color = discord.Color.yellow())
em.add_field(name = "warns",value = warns_amt)
await ctx.send(embed = em)
@client.command()
@commands.has_permissions(manage_messages=True)
async def warn(ctx, user: discord.User):
await open_account(user)
users = await get_warns_data()
warns = 1
await ctx.send(f"{user.name} has been warned")
users[str(user.id)]["warns"] += warns
with open("warndata.json","w") as f:
json.dump(users,f)
async def open_account(user):
users = await get_warns_data()
if str(user.id) in users:
return False
else:
users[str(user.id)] = {}
users[str(user.id)]["warns"] = 0
with open("warndata.json","w") as f:
json.dump(users,f)
return True
async def get_warns_data():
with open("warndata.json","r") as f:
users = json.load(f)
return users```
File "/home/runner/zag/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 60, in warnings
File "main.py", line 94, in open_account
UnboundLocalError: local variable 'get_warns_data' referenced before assignment
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/home/runner/zag/venv/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/zag/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "/home/runner/zag/venv/lib/python3.10/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: UnboundLocalError: local variable 'get_warns_data' referenced before assignment
172.31.128.1 - - [30/Apr/2023 19:24:21] "HEAD / HTTP/1.1" 200 -
can someone help me
Definition of get_warns_data() is inside open_account(). Just move it out
how do ephemeral messages work
Now get_warns_data() I undefined
how do i make options in slash commands not required
When type hinting, set them to typing.Optional or give it a value of None when defining the function
thank you again
sorry to bother you again but how would i make it so only a certain role or permission can use the command
Text or slash command
slash
yes
Hold up lemme start up my computer
Ok so when you create a slash command
Add an extra decorator
@app_commands.guilds(guild ids)
and put the guild ids in a list. I’m pretty sure that’s how it works but I’ve never used it.
full example:
@app_commands.command(args) # or @bot.tree.command if not in a cog
@app_commands.guilds(12345, 23456, etc) # the guild ids can be accessed when right clicking a server icon with dev mode turned on
async def command(args):
pass # code goes here```
ok i gtg now
wdym by before
Use a database
with the purge command you should set the limit to (limit=limit+1) so that it will delete the command with it
Any recommendations on my help command code?
async def help(ctx: commands.Context) -> None:
command_list = [(command.name, command.description) for command in ryan.commands]
pages = []
KEYS_PER_PAGE = 10
for index, chunk in enumerate(more_itertools.chunked(command_list, KEYS_PER_PAGE)):
embed = discord.Embed(
title=f"Help Menu - {len(ryan.commands)} Commands", color=0x808080
)
embed.set_author(name=ctx.message.author.name, icon_url=ctx.author.avatar.url)
embed.description = "\n".join(
[
f"{(index * KEYS_PER_PAGE) + i + 1}. **{name}**: `{desc}`"
for i, (name, desc) in enumerate(chunk)
]
)
pages.append(embed)
await Paginator.Simple(timeout=60).start(ctx, pages=pages)
don't reinvent the wheel, and instead subclass commands.HelpCommand
How do I make my own decorator, specifically I want to add a decorator that checks if a user is blacklisted.
see the implementation of a check, and see how it works internally: https://github.com/DisnakeDev/disnake/blob/master/disnake/ext/commands/core.py#L1692-L1783
I am linking disnake's because their docs are significantly faster and doesn't demand a super computer
however, there is no need for a decorator just for that. Have a global check, and a global error handler. Subclass CommandError and name it BlacklistedUserError or whatever, then raise that in the global check if the user is blacklisted, and ||catch catch CommandInvokeError on your global error handler, and see if .original is your subclass of CommandError||BlacklistedUserError
actually, no, you don't need to catch CommandInvokeError, just catch BlacklistedUserError
@sullen shoal Can I just ignore the discord.ext.commands.errors.CheckFailure:?
I can show you the decorator I made, I might've done something wrong, but it works as it should
It is raised when your check is False
yeah, I raise False on purpose
yes, that's why I'd say go for custom exceptions and a global check
@np.error
async def np_error(ctx: commands.Context, error) -> None:
if isinstance(error, commands.CheckFailure):
pass
else:
raise error
Something like this for each command?
you can have a local error handler for the cog as well. Or check the command name using the Context obj that you get in the global error handler and have a list of command names that you'd want to pass the error for
Hey, could I ask you for help?
I am following, what do you need help with?
https://paste.pythondiscord.com/bafisubowo
I made that script,
the system is called REPORT-SYSTEM
In the script you can see this:
user_reporting = interaction.user
user_reported = message.author
reported_message_link = message.jump_url
reported_message_content = message.content
mods_channel = self.report_channel
embed = discord.Embed(title="Reported Message", color=discord.Colour.from_rgb(255, 0, 0))
embed.add_field(name="Reporting User", value=user_reporting.mention, inline=False)
embed.add_field(name="Reported User", value=user_reported.mention, inline=False)
embed.add_field(name="Reported Message", value=reported_message_link, inline=False)
embed.add_field(name="Reported Message", value=reported_message_content, inline=False)
await mods_channel.send(embed=embed)
return embed```
I would like the report_message command to be a message command.
Like, when I right click a message and the ``APP`` section pops up with a command that I can use
do you maybe know how I can implement this in my code?
i`m kinda new to discord.py and struggling to understand it a bit
I'd know for Disnake as that is what I am mainly familiar with for anything interactions specific. However, if your mission is to have both a slash command and a message command with the same functionality, you should wrap the duplicated functionalities into several functions
I am not faimilar with the design choices of Danny and Discord.py
the report_message command should not be a slash command
unfortunately, I am not useful here
Ok, still thanks for trying to help
keep in mind that your database adapter is not asynchronous, and if two people are running the same command simultaneously, the resultant can be unexpected
and, your codebase is vulnerable to SQL injections, see <#bot-commands message>
do you still need help?
these are referred to as context menus in discord.py
@app_commands.context_menu()
async def react(interaction: discord.Interaction, message: discord.Message):
await interaction.response.send_message('Very cool message!', ephemeral=True)
Hello!
I am making a lockdown command
Code:
@commands.command(name="lockdown")
@commands.has_permissions(manage_channels=True)
async def lockdown(self, ctx: commands.Context, reason: str = None):
msg = await ctx.reply(
embed=discord.Embed(
color=0x0000FF,
description=f"{ctx.author.mention}; Processing command."
).set_author(
name="Processing lockdown command",
icon_url=ctx.guild.icon
).set_footer(
text=f"Command ran by - {ctx.author}",
icon_url=ctx.author.avatar
)
)
start = time.time()
final = discord.Embed(
color=0x0000FF
).set_footer(
text=f"Command ran by - {ctx.author}",
icon_url=ctx.author.avatar
)
channels = []
roles = []
channelss = config['Lockdown Config']['Channel IDs']
roless = config['Lockdown Config']['Role IDs']
for input in channelss: channels.append(input)
for input in roless: roles.append(input)
if reason is None: reason = "No reason provided."
Locking = False
for channel_id in channels:
channel = commands.Bot.get_channel(self, channel_id)
for role_id in roles:
role = ctx.guild.get_role(role_id)
perms = channel.permissions_for(role)
if not perms.send_messages: await channel.set_permissions(role, send_messages=True)
else:
await channel.set_permissions(role, send_messages=False)
if Locking: pass
else: Locking = True
if Locking:
await channel.send("This channel has been locked by {} for reason {}".format(ctx.author.mention, reason))
final.description = f"{ctx.author.mention}; Successfully locked down server in `{elapsed}s`"
else:
await channel.send("This channel has been unlocked by {}".format(ctx.author.mention))
final.description = f"{ctx.author.mention}; Successfully unlocked server in `{elapsed}s`"
end = time.time()
elapsed = round(end - start, 2)
await msg.edit(embed=final)
@lockdown.error
async def lockdown_error(self, ctx:ctxx, error):
if isinstance(error, commands.MissingPermissions):
await ctx.reply(
embed = discord.Embed(
color = 0xFF0000,
description = f"{ctx.author.mention}; You are not authorized to run this commands"
).set_author(
name = "Missing required permissions - Manage Channels",
icon_url = ctx.guild.icon
).set_footer(
text = f"Command ran by - {ctx.author}",
icon_url = ctx.author.avatar
)
)
Config file:
"Lockdown Config": {
"Role IDs": [
1090787392501317687
],
"Channel IDs": [
1102056458855653468,
1099897631968350218
]
}
But it does the first part where it says it is initializing but it doesn't do anything after
yeah I do
you're not using the decorators
also i'm pretty sure slash commands can't return anything
you need to send the message instead
the return type would be -> None
you mean because of the return embed?
What's the best way to make a snipe command?
He's talking about return annotations
I'm new to discord.py what does that mean?
Sorry
Return annotations are just what you use to define what the function will return
Yes, and what would be the issue in my script?
def add(a: int, b: int) -> int:
return a + b
Here's a simple example, a and b are ints so that function will also return an int.
I haven't looked at your code so he might of just been giving a suggestion
if you have a Redis database, insert it there where the key would be the channel ID
and if I don't have a redis database?
have a dict
i love dict
And just use the on_message_delete event to store it all?
if your snipe command is supposed to snipe more than just one deleted deleted messages, sorted by date, you can append to a list, or if just the last one, do something like self.bot.snipe_cache[channel_id] = msg.content, and just retrieve it from the cache when needful
Hey bot people.. I wrote a discord bot a while ago kinda just going off the top of my head without any inspiration. Is this a good command handler?
class Client(discord.Client):
async def on_ready(self):
print('Logged on as', self.user)
async def on_message(self, message):
print(f"Message Recieved:\nMessage Content: {message.content}\nMessage Author: {message.author.name}#{message.author.discriminator}")
if message.author.bot: return
if message.channel.type == "private": return
if not message.content.startswith(config["prefix"]): return
messageArray = message.content[len(config["prefix"]):].split(' ')
cmd = messageArray[0]
args = messageArray[1:]
command = path.isfile(path.join(config["commandFolder"], cmd + ".py"))
if command:
exec(f"from commands import {cmd}")
await eval(f"{cmd}.{cmd}(self, message, args)")
I didn't want all of my commands to be in a single file or anything, for a cleaner look.
instead of manually creating a command handler, you might as well use the built-in command handler by discord.py
I feel like that would give me less control overall, unless I'm massively wrong. What if I wanted to add content moderation to my bot?
Trust me, you really do not wanting to be writing command parsers by hand
Especially when discord.py gives you a rich system for parsing
actually it gives you control such as commands check and converter
https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html
if you wanna see the whole command handler
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix='$', intents=intents)
@bot.command()
async def test(ctx):
pass
# or:
@commands.command()
async def test(ctx):
pass
bot.add_command(test)
this example seems to say that all of the commands are in one file...
Not really. to create commands over multiple file, we put them in a class that derived commands.Cog, and we load them with extension
https://discordpy.readthedocs.io/en/stable/ext/commands/extensions.html#ext-commands-extensions
Example would be something like
other/file.py ```py
class MyCog(commands.Cog):
@commands.command()
async def test(ctx):
...
async def setup(bot):
await bot.add_cog(MyCog())
Then you would load them by `await bot.load_extension('other.file')` in the main file
Hello!
I am making a lockdown command
Code:
@commands.command(name="lockdown")
@commands.has_permissions(manage_channels=True)
async def lockdown(self, ctx: commands.Context, reason: str = None):
msg = await ctx.reply(
embed=discord.Embed(
color=0x0000FF,
description=f"{ctx.author.mention}; Processing command."
).set_author(
name="Processing lockdown command",
icon_url=ctx.guild.icon
).set_footer(
text=f"Command ran by - {ctx.author}",
icon_url=ctx.author.avatar
)
)
start = time.time()
final = discord.Embed(
color=0x0000FF
).set_footer(
text=f"Command ran by - {ctx.author}",
icon_url=ctx.author.avatar
)
channels = []
roles = []
channelss = config['Lockdown Config']['Channel IDs']
roless = config['Lockdown Config']['Role IDs']
for input in channelss: channels.append(input)
for input in roless: roles.append(input)
if reason is None: reason = "No reason provided."
Locking = False
for channel_id in channels:
channel = commands.Bot.get_channel(self, channel_id)
for role_id in roles:
role = ctx.guild.get_role(role_id)
perms = channel.permissions_for(role)
if not perms.send_messages: await channel.set_permissions(role, send_messages=True)
else:
await channel.set_permissions(role, send_messages=False)
if Locking: pass
else: Locking = True
if Locking:
await channel.send("This channel has been locked by {} for reason {}".format(ctx.author.mention, reason))
final.description = f"{ctx.author.mention}; Successfully locked down server in `{elapsed}s`"
else:
await channel.send("This channel has been unlocked by {}".format(ctx.author.mention))
final.description = f"{ctx.author.mention}; Successfully unlocked server in `{elapsed}s`"
end = time.time()
elapsed = round(end - start, 2)
await msg.edit(embed=final)
Config file:
"Lockdown Config": {
"Role IDs": [
1090787392501317687
],
"Channel IDs": [
1102056458855653468,
1099897631968350218
]
}
But it does the first part where it says it is initializing but it doesn't do anything after
Someone got a docs for this?
?
Like leaderboard
How do you get a default pfp url?
!d discord.User.default_avatar
property default_avatar```
Returns the default avatar for a given user. This is calculated by the user’s discriminator.
python bot uses pycord docs now?? hm
Discord IDs don't have a set length
use BIGINT
currently, snowflakes are around 19 digits
but that might change
they actually didn't become 19 digits until a few months ago
What's the best way to handle discord.errors.Forbidden?
Thats a very broad question, where is it coming from?
Missing permissions attempting to add a role to a member object
is this in a command? view? event?
it's a command
slash? text?
text
this won't work
on_command_error only catches errors that are inheriting from discord.ext.commands.CommandError
instead use try/except as that's how the exception is raised when you use Member.add_roles
Just a general question, if you have a database which has a list of allowed users. How do you 'cache' the list so you don't have to use the db again and again or is it in fact actually a better practice to use the db ?

I would suppose, it's better to cache ?
You could create a python list as a botvar
Or more advanced solution would be to use cache db Like Redis
!botvar
Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:
bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"
@bot.command()
async def get(ctx: commands.Context):
"""A command to get the current value of `test`."""
# Send what the test attribute is currently set to
await ctx.send(ctx.bot.test)
@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
"""A command to set a new value of `test`."""
# Here we change the attribute to what was specified in new_text
bot.test = new_text
This all applies to cogs as well! You can set attributes to self as you wish.
Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!
why would you need to?
databases are designed to handle thousands of queries per second
making one every time someone runs a command is not that expensive
Yes, it would be wrapped in a CommandInvokeError. See the gist for retrieving the original error
error_handler.py line 49
error = getattr(error, 'original', error)```
!d vars
vars()``````py
vars(object)```
Return the [`__dict__`](https://docs.python.org/3/library/stdtypes.html#object.__dict__ "object.__dict__") attribute for a module, class, instance, or any other object with a [`__dict__`](https://docs.python.org/3/library/stdtypes.html#object.__dict__ "object.__dict__") attribute.
Objects such as modules and instances have an updateable [`__dict__`](https://docs.python.org/3/library/stdtypes.html#object.__dict__ "object.__dict__") attribute; however, other objects may have write restrictions on their [`__dict__`](https://docs.python.org/3/library/stdtypes.html#object.__dict__ "object.__dict__") attributes (for example, classes use a [`types.MappingProxyType`](https://docs.python.org/3/library/types.html#types.MappingProxyType "types.MappingProxyType") to prevent direct dictionary updates).
Without an argument, [`vars()`](https://docs.python.org/3/library/functions.html#vars "vars") acts like [`locals()`](https://docs.python.org/3/library/functions.html#locals "locals"). Note, the locals dictionary is only useful for reads since updates to the locals dictionary are ignored.
A [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") exception is raised if an object is specified but it doesn’t have a [`__dict__`](https://docs.python.org/3/library/stdtypes.html#object.__dict__ "object.__dict__") attribute (for example, if its class defines the [`__slots__`](https://docs.python.org/3/reference/datamodel.html#object.__slots__ "object.__slots__") attribute).
@commands.group(name='race')
@channel_check(Channels().bot_commands)
async def math_racer(self, ctx:Context, paper:t.Optional[int], mode:t.Optional[str]) -> None:
This keeps on giving me an error,
Command raised an exception: TypeError: MathQP.math_racer() missing 1 required keyword-only argument: 'mode'
Why is it so?
nvm fixed it
But I did get another one in its stead,
TypeError: 'float' object cannot be interpreted as an integer
nvm got it
hey so
i want to define all the slash commands in a seperate file then import that file to bot.py.
like i want separate my all commands in files. can anyone help?
so into a cog
what
you shouldn’t have one command per file
but if you really want to
!d discord.app_commands.CommandTree.add_command
add_command(command, /, *, guild=..., guilds=..., override=False)```
Adds an application command to the tree.
This only adds the command locally – in order to sync the commands and enable them in the client, [`sync()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree.sync "discord.app_commands.CommandTree.sync") must be called.
The root parent of the command is added regardless of the type passed.
or just use extensions with add_command in setup
ofc not
but like i have all the slash commands in one file
all the events in other file
and the prefix commands in other file
what will be the method to do that
cogs and extensions
but your extensions should probably be grouped by category
i am sorry but i literally dont know about both of these
that’s my fault sorry
there’s a good tutorial on the docs
i can’t link it because i’m on mobile
tutorial will be helpful
is it cool if i remind you after some time?
what function removes slash commands from the bot?
syncing the tree will remove non existent slash commands, im guessing the top or bottom is a guild specific slash while the other is global one, if you wanna remove the guild one, just sync that guild without that claim command present
but what function is it?
if it happens in a command its wrapped in CommandInvokeError, at which point you can unwrap and handle it as desired
https://github.com/thegamecracks/thegamebot/blob/v2/bot/cogs/eh.py#L350-L354
!d discord.app_commands.CommandTree.sync (assuming you're using discord.py 2.0)
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.
ty! so this will sync global and guild?
guild only gets synced if you give something to the guild parameter
so if you don't then it's considered global?
Hi, uh I’m new here, so what’s this channel about?
It's for questions and discussions relating to Discord bot development with discord.py and other relevant Python libraries.
looking at the channel's description might be good for considerations
Can discord bots work in threads now? Just saw a bounty for a bot that interacts in threads
i dont know if bots didnt support them when they were first introduced, but now sure, discord.py has supported threads since 2.0 which released last year
(and dpy 2.0 took a while before it was released, disnake's first 2.0 release, at least as indicated on their github, supported threads since october 2021)
Sweet. Thanks
is there any way to have custom decorators ? or what can be my options if i want to run a lot of checks without cluttering the main function. Basically, i wanna run checks but i dont wanna return anything to the function for if else
You can have a look at https://libs.advaith.io to know which library has support such certain features
Compares Discord libraries and their support of new API features
I'll work with discord.py, that's what I'm most familiar with. Just didn't know it had support for threads. Guess I never needed my bots to so I didn't worry about it
!d discord.ext.commands.check There's an example for implementing a custom check as it's own decorator
@discord.ext.commands.check(predicate)```
A decorator that adds a check to the [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") or its subclasses. These checks could be accessed via [`Command.checks`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command.checks "discord.ext.commands.Command.checks").
These checks should be predicates that take in a single parameter taking a [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context"). If the check returns a `False`-like value then during invocation a [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure") exception is raised and sent to the [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") event.
If an exception should be thrown in the predicate then it should be a subclass of [`CommandError`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError"). Any exception not subclassed from it will be propagated while those subclassed will be sent to [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error").
!e
pprint("You are the man")
hey guys, if you were storing data for a raffle system how would you do it? I'm currently using an SQL database and doing this:py cur.execute(''' CREATE TABLE raffles( raffleID INTEGER PRIMARY KEY AUTOINCREMENT, guildID INTEGER NOT NULL, userID INTEGER NOT NULL, userAddress STRING NOT NULL, itemID INTEGER NOT NULL, minTickets INTEGER NOT NULL, timeLeft INTEGER NOT NULL, ticketsSold INTEGER NOT NULL, completed BOOL NOT NULL ) ''') cur.execute(''' CREATE TABLE entrants( ID PRIMARY KEY, userID INTEGER NOT NULL, userAddress STRING NOT NULL, raffleID INTEGER tickets INTEGER NOT NULL, FOREIGN KEY(raffleID) REFERENCES raffles(raffleID) ) ''')
so there'd be a new row in entrants in the table every time a user enters a raffle. I'm just not sure if this is the best way of handling that data 😅
Can anyone help me code a discord bot on vsc
sure
"i wont promote" ~ Promotes
Yeah. But just to show you guys.
K dm me
I did
!warn 763833414976929812 This is a promotion, no matter what you call it. See rule 6.
:ok_hand: applied warning to @slate swan.
how to write spaces in discord.Option for slash command ?
like ```py
async def test(ctx, test test : discord.Option(str, "some test", required = True)
How are you guys storing discord oauth2 tokens?
Feels like leaving them plain in a database isn’t the best thing to do
if my discord bot was added to a bunch of servers with only the bot permission scope (this was before slash commands existed), and i want to update the bot to use slash commands, does this bot need to be re-added to every server with new permissions (applications.commands)?
wondering if anyone has gone through the same thing, and how to deal with it
Discord did automatically add the scope to some bots before a certain time. You probably will need to reinvite (not kick and rejoin, just use the invite again) with the application commands scope
if i am not associated with the servers, how should i communicate this to server owners?
You could loop through your bots guilds, try to dm the owner or ping them in a channel
I made a discord bot that daltonizes images (increased the contrast) so that colorblind people could see them. And I added a experimental function which can only detect RGB rn
Anyone know how to use BeautifulSoup4 and could possible help me with some web scraping errors im getting with my bot?
scraping what?
I'm trying to make a dnd info bot and wanting to scrape items from http://dnd5e.wikidot.com/#toc67 via command /item {item_type} {item_name} eg /item adventuring-gear Rope
I know http://www.dnd5eapi.co is a thing but it has a lot less info than http://dnd5e.wikidot.com
Any reason ur not using some dnd api or not pre scraping the data storing it in a db and using it later?
scraping data during runtime is not usually a good idea
hosting a db would add to my hosting cost and i cant afford it ;-; and to many items to have it saved locally (just lazy and cbf typing out every item)
dont need a host just make a local db file or a json file since u wont be editing the data its totally fine u can just load it on startup
also u scrape it and save it in a file
then load the file to memory when starting the bot
that way low latency plus less prone to errors
u can update ur data later too if new stuff is added make a little script for that
The hosting site i use pulls the bot from github to run it, and i'm having errors trying to scrape the info in the first place so i cant even see the info
I could make it a local db hmmm
ur not getting my point my point is store the data in a json or db file ur hosting service will pull that too
but i would need to be able to scrape the info anyway to save it
yeah i realised i missed what you were saying
use requests with soup or smn
im new to using BeautifulSoup4 and db's first time using BeautifulSoup4 today
then its a good day to learn new stuff 👍
never messed with db's before either
dbs or json its optional in this case pick either
since its gonna be a read only file
same with json lol i've only made small single propose bots ;-;
first time trying a more complex bot
gl
what event is passed when server loses a boost?
None on its own, only a GUILD_MEMBER_UPDATE event as premium_since changes
tysm
Just buy a VPS
How much your "hosting service" is
Im using railway. I've put in $5 and i get a free $5 a month with unlimited runtime so as long i use less than $5 a month its basically free forever
You can use VPS free tier
without putting in money you get a few 100 hours of runtime
Still will be better than this
You will reach that cap every month
Im running 3 bots without touching the cap
There are more than 500 hours a month
Bs4 I LOVE BS4 MEOW MROW
Free options
- digital ocean - free 200$ for 2 months
- amazon AWS - free for 1 year
- oracle cloud - not sure, must be completely free
- microsoft azure - free for one year then some services are available
@median sand
Yeah i know but if you are free you only get the 500 and thats it no more, after spending you get unlimited runtime and $5 free credit
Oracle can suck fat penis
Still better than "hosting service"
?? Obviously if you pay you get unlimited runtime
Would remove Oracle
I never used it myself tho
Either you get banned after a few hours/days for no apparent reason, or you simply cannot use it at all
Just get a 50 dollar dedicated from hetnzer or whatever they are called
Never worry again
50$/mo?
Ya
That's like for million servers bot
3$/mo is good for small bots
Oh small
Galaxygate got that
Anyone know how to make my item_type:str a list for a user to pick from
@client.tree.command(name='item', description="Allows you to search for an item")
async def item(interaction: discord.Interaction, item_type: str, item_name: str):```
But yeah in terms of free tier all those options I mentioned except oracle apparently
With choices, see the docs
Im sure a 5 dollar per month from vultr, linode, digital ocean is good
These 3 services give a trial
Aws is good until ur trial ends than u get hit with them expensive server bills
My usage with Railway and running 3 small bots
What if I don't pay 
Costing $1.42~ a month and i get $5 free credit
U lose ur access !
so i never spend the $5 i put in only the free credit
I got a database, key vault, vps on aws
Friend
Sparkedhost 1 dollar per month
Prolly would work if ur bot as its small
Rip
They are getting ddos attacks and net maintenance but compensate that with free hosting time
Like I got one free month after 2 ddoses
hey
i wanted to make a something like a stats bot
that displays members in locked voice channels
and I dont know where to start from except how to fetch the numbers
do i use loops, events or what?
any help is appreciated, thanks a lot :)
Probably a task running every 10 minutes or something in the background
Events method is much better if you do it properly
Then to fetch the numbers you need to get a guild object in the first place
That way you're sure you won't get hit by rate limits in case people join/leave your server every now and then
okayy
h-how do I do that?
like do i need a while loop
to keep checking if someone is joining or not?
For that you have events
E.g.
@bot.listen()
async def on_member_join(member: discord.Member):
print(f"{member} joined")
mhm so will this work:
while true:
async def on_member_join():
channel = utils.get(guild.channels, id=id)
member_count = member_count = len(ctx.guild.members)
await channel.edit(name = f"member_count")
async def on_member_leave():
#same_shit as before
No while loop
mhm
Just the above
No need to use utils.get either
You can get access to the guild object with member.guild in the example here ^
There's no such ctx in events as well, so you can use member.guild.members
f-strings should have {} as well:
await channel.edit(name=f"member_count") # Not good
await channel.edit(name=f"{member_count}") # Good
I was about to say "yOu sHoulD cAsT to StR wiTh str()" but suddenly remembered there are no style regulations to it
Or are there

Now you leaked your IP to everyone
And phone
And token
@slim plover yo man delete this asap
i have this one code working perfectly on host
but when i run on my pc it gives error
i dont get it its the same exact code
role = get(interaction.guild.roles, name= item)
according to error the above line is returning a coroutine
then you await the coroutine?
yep i tried but it gave another error
its get() got an unexpected keyword argument 'name'
but still why is it working for the bot which is already hosted
how do i get role object from role name now
where do you import get function
You probably overwrite the get function
Consider using utils.get instead of importing the way to use get directly
Do you have any function named get?
Also where do you have the id varriable you pass into the get function
ohk
maybe i do
Cause looks Like you are passing built in id function
yeaahh
thansk
i had this random test function in file for no reason
i thinks its causing the issue
Looks like
If you want to have get command you can do this:
@client.command(name="get")
async def random_name(...):
...```
yeah thanks
i didnt see it, but still thanks guys
also @slate swan you ever had a youtube channel?
I have a google account that has a youtube channel linked to it just like the average users that use and interact on youtube, yes
!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.
how do i give a role using a button
!d discord.Member.add_roles
await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s.
You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
when pressing a button
Im having an issue with choices/options when writing my command im using @client.tree.command
code?
Here is the start of my command```py
Define the Item Types
item_types = {
"Adventuring Gear",
"Armor and Shields",
"Trinkets",
"Weapons",
"Firearms",
"Explosives",
"Wondrous items",
"Currency",
"Poisons",
"Tools",
"Siege Equipment"
}
Command to find a item using the item's type & name
@client.tree.command(name='item', description="Allows you to search for an item")
async def item(interaction: discord.Interaction, item_type: str, item_name: str):```
I'm wanting the item_types to be the options for item_type: str
i think you might be able to use typing.Literal[*item_types] as the item type parameter
might be a better idea to use Choice though
autocomplete is usually for data that can change
wait what
you can do that? instead of autocomplete?
!d discord.app_commands.choices
@discord.app_commands.choices(**parameters)```
Instructs the given parameters by their name to use the given choices for their choices.
Example...
you can use either literal, choices, or autocomplete
actually i don't know if x[*y] is valid
nvm then
oh it is valid
How would i add this?
from typing import Literal at the very top
Im getting the errorUnpacked arguments cannot be used in type argument lists
and use item_type: Literal[*item_types]
# Define the Item Types
item_types = {
"Adventuring Gear",
"Armor and Shields",
"Trinkets",
"Weapons",
"Firearms",
"Explosives",
"Wondrous items",
"Currency",
"Poisons",
"Tools",
"Siege Equipment"
}
# Command to find a item using the item's type & name
@client.tree.command(name='item', description="Allows you to search for an item")
async def item(interaction: discord.Interaction, item_type: typing.Literal[*item_types], item_name: str):```
strange, works for me
>>> from typing import Literal
>>> x = {1, 2, 3}
>>> def y(z: Literal[*x]) -> None: ... ... print(z)
>>> y(1)
1
(variable) item_types: set[str]```
do you get that error when running it?


