#discord-bots
1 messages · Page 195 of 1
no
how do i prevent other users from interacting with it?
!d discord.ui.View.interaction_check < implement this method to decide when the view should reject an interaction
await interaction_check(interaction, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A callback that is called when an interaction happens within the view that checks whether the view should process item callbacks for the interaction.
This is useful to override if, for example, you want to ensure that the interaction author is a given user.
The default implementation of this returns `True`.
Note
If an exception occurs within the body then the check is considered a failure and [`on_error()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View.on_error "discord.ui.View.on_error") is called.
say I have a select menu right how could I make it where under certain circumstances it won't allow them to click a certain one
like for example say I make a if statement, say their username doesn't have a t in it
or their account was made to recent
You can't on the client side
The user will be able to click on it but you'll just have to send a response message saying they can't check that option
You can also have them press a button, which sends a select menu, with some certain options just not showing at all
is it possible to add select options in Modals?
No, I don't think
buttons?
No
How can i get whatever user typed in the Modal for the text variable?
Oh
In which TextInput object?
uh i dont get it but imma send the modal class code
i want the text in another function
by text i mean the text user will input
self.option1.value then
yeah but how can i get it in this different function
Is this callback not inside class Modal?
See the issue Is I'm trying to have combos like this
Toppings:
meat
cheese
lettuce
chocolate syrup
food:
sandwich
icecream
I wanna make it where they can choose meat cheese lettuce but if they have those 3 selected then try selecting chocolate syrup it won't work
Yeah there's no native way to do that
You'll just have to send them a message saying they can't pick that option if they do pick it
a dropdown select menu
Is the select menu sent after the modal?
the modal appears after you make a selection
So you want to pass the information from the select menu to the modal?
you could add that to the __init__
@discord.ui.button(label="Создать персонажа", custom_id="create-1", style=discord.ButtonStyle.primary)
async def create_button(self, button, interaction):
try:
with connection.cursor() as cursor:
insert =(f"""
INSERT INTO `discord`.`users`
(`user_id`, `user_name`)
VALUES ('{interaction.user.id}', '{interaction.user.name}');""")
insert = cursor.execute(insert)
insert = cursor.fetchone()
connection.commit()
await interaction.response.send_message('Персонаж создан', ephemeral=True)
await interaction.response.defer()
except (discord.errors.InteractionResponded, pymysql.err.IntegrityError):
await interaction.response.send_message('Вы уже создавали персонажа ранее', ephemeral=True)
await interaction.response.defer()
dear friends, please tell me what to write in except so that such an error does not occur? When a button is clicked by a person who is already entered into the database, this error occurs
how can I make it where they have to pick one but they can pick multiple
Pick one or pick multiple?
min 1 max is however many options there are
remove the defer
You just pass those values into min= and max= kwargs
yes, it would be min_values and max_values though
from modal to select menu
user will select an option then they will see the modal according to it
then i want info of both interactions to do the final thing
makes sense?
ids = config['ids']['ids'] if config['ids']['enabled'] else None
if ids:
kw = {
'guild_ids': ids
}
else:
kw = {}
@bot.slash_command(**kw)
async def command(...):
...
``` is there anything easier than that? i want to store in a dict whether it should have guild_ids defined or not and the ids
okay i'm planning to create a white list of arguments for my string. Like i'm planning to only allow 0 to 9 numbers, d letter and #
how do i do it?
No you just said 2 opposite things
First you said modal to select menu
Then you're saying option to modal
uh modal to select.
Why is it not possible to have two tasks running? Here is my code:
class MyClient(commands.Bot):
async def setup_hook(self):
update_elo_ratings.start()
check_queue.start()
async def on_ready(self):
print('Bot is ready!')
@tasks.loop(hours=24)
async def update_elo_ratings():
... # do some handling
@tasks.loop(seconds=5)
async def check_queue():
while True:
if len(current_players) < 10:
... # do some handling```
Then you construct your ui.Select inside the ui.Modal's on_submit method by passing in the proper arguments
Probably has to do with the while True loop
You want it to to run once every 5 seconds, yes?
Correct @sick birch
So you shouldn't need that while true loop
okay i can try
after putting the ui.Select in ui.Modal class
how can i access the Select class
You don't put the select in the modal
You just instantiate it there
class MySelect(ui.Select):
...
class MyModal(ui.Modal):
...
async def on_submit(...)
select = MySelect()
# send select
How do I pass a variable from a function so it's accessible within a class? @sick birch
You pass it into the class's constructor
class MyClass:
def __init__(self, arg):
...
def my_func(...):
MyClass(arg)
hi y9
by putting it in the function's arguments
so within the class MyClass, if I wanted to create a function if the variable was truthy how would I?
class MyClass:
def __init__(self, arg):
blah
if blah:
newfunction
async def my_func(...):
MyClass(arg)
ctx.send(blahblah)
why would you want to create a function if a certain condition was true 🤨
do you mean call a function
I subclassed view and if a variable is true I want to add the button to the message
Yeah @discord.ui.button
Calling the function or dynamically creating one?
calling
class MyClass(ui.View):
def __init__(self, arg):
if arg:
self.add_item(...)
So it needs to be indented with the init. then what does add_item do?
add_item(item)```
Adds an item to the view.
This function returns the class instance to allow for fluent-style chaining.
it can be a button, a select menu, or text input
but you have to instantiate it, don't create it with a decorator
then how do I add everything else like the color of the button etc?
you can pass that to the button constructor
let me give an example
if condition:
self.add_item(Button(label = "My Button", style = discord.ButtonStyle.primary))
what's the convention for naming discord bot cogs?
the same as a class just PascalCase
Same as naming your classes
i think you might have to subclass button though, i don't know how you would add the callback otherwise
unless you just do button.callback = ...
and then how would I send the interaction reply?
what do you mean, the callback when you press the button?
def callback(self, interaction):
await interaction.response.send_message("hello")
if condition:
button = Button(label = "My Button")
button.callback = callback
like this
and that'd also go within the class
sure, that works
you can even define the callback function within __init__ if you want
How so?
it wouldn't be any simpler
would callback be indented with init?
class MyButton(discord.ui.Button):
def __init__(self):
super().__init__(label = "My Button")
async def callback(self, interaction):
...
# vs
def callback(self, interaction):
...
button = Button(label = "My Button")
button.callback = callback
choose which one you prefer
it should be one level above __init__ or you can make it a separate method within the view and use self.callback instead
What if I have multiple buttons and multiple variable checks
Would I have to make a bunch of different callback functions?
probably yeah unless they do something similar
they all would reply with different things
def callback(self, interaction):
if self.custom_id == ...:
...
else:
...
button_one = Button()
button_one.callback = callback
button_two = Button()
button_two.callback = callback
you can do this but i would not recommend
either subclass them or just make a bunch of different callback functions
is there no way to do this without add_item?
why would you want to do that?
Cause I don't want to manage each button individually like that
this is the easiest way
I don't understand why I can't just check the variable then call the buttons like how you would normally
??? you don't "call the buttons" you define a new function
with the button decorator, which discord.py reads and adds that button
yeah like that though why doesn't it work
I don't see how you're "managing" every button
It's basically the same as with a decorator
yeah
You just get a bit more control
I'm saying like why wouldn't it work checking the variable then still using the decorator
def __init__(self, argument):
if argument:
my_button = discord.ui.button()(lambda self, interaction, button: ...)
you want to do this??
🥸
don't even know if that works
actually well yeah
because that's what I want it to do ? idk 🤣
but would it work with the deco?
@vocal snow
hii
Because discord.py doesn't care about your variable
It just adds the button regardless
The decorator is a shortcut for simple usecases
it doesn't even add the button doing it with the deco :
Then you're probably doing it wrong
you shouldn't even do that anyway, that's messy
it's simpler than doing it the other way though
no it's not
it might be more complex but it's not any harder, plus it's more readable anyway
I did not get it how you wrote it
i could rewrite it simpler
class MyButton(discord.ui.Button):
def __init__(self):
super().__init__(label = "My Button")
async def callback(self, interaction):
await interaction.response.send_message("hello")
class MyView(discord.ui.View):
def __init__(self, argument):
if argument:
# adds the button to the view
self.add_item(MyButton())
it's the same as writing it as a decorator, the decorator is pretty much just a shortcut for this syntax
why are there two options
because one is an alias of the other
just like how there are aliases for gray and grey
did they really make an alias for british people
pretty sure colour is the real one lol
...
@discord.ui.select(placeholder="Barretta Accessories", min_=1, max_=3, options=[?
discord/colour.py line 417
Color = Colour```
@ionic garden
min_values and max_values, not min and max
can't believe it
how can i make it so i can ban the user with the name+discrim, this is my current code.
@bot.tree.command(name="unban", description="Unbans the specified user.")
@commands.has_permissions(ban_members=True)
async def unban(interaction, user: str):
guild = interaction.guild
try:
user = int(user)
await guild.unban(discord.Object(user))
except ValueError:
channel = bot.get_channel(1073724291515949077)
unbanlogEmbed=discord.Embed(title="Logging | Unban Command", color=0xFF5349)
unbanlogEmbed.add_field(name="Executed by:", value=f'{interaction.user}', inline=True)
unbanlogEmbed.add_field(name="Executed on:", value=f'{user}', inline=True)
unbanlogEmbed.set_footer(text="Made by justin;#6868")
unbanlogEmbed.set_author(name=f'{interaction.user}', icon_url = f'{interaction.user.display_avatar}')
await channel.send(embed=unbanlogEmbed)
unbanEmbed=discord.Embed(title="Ban Command", color=0xFF5349)
unbanEmbed.add_field(name=f'{interaction.user} has executed:', value="Unban Command", inline=False)
unbanEmbed.set_footer(text="Made by justin;#6868")
unbanEmbed.set_author(name=f'{interaction.user}', icon_url = f'{interaction.user.display_avatar}')
await interaction.response.send_message(embed=unbanEmbed)```
damn
never had to make an unban command before, but why can't you just use a converter
does discord.User not work?
ah wait, it's a slash command
transformer then
i'm pretty sure it would've worked if you just type hinted it as discord.User though
is there an example for the use of this method?
you can subclass view and return true or false
why i'm receiving this exception (ignore the last line of code):
or better this in exception?
class MyView(discord.ui.View):
@discord.ui.button(label = "My Button")
async def my_button(self, interaction, button):
...
async def interaction_check(self, interaction, /):
return self.user.name == "mudkip"
@ionic garden
the button will only work if the user is mudkip
tysm!
i need help:
please don't post your question twice, it's been literally 2 minutes
also show the code above that
Pasting large amounts of code
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.
hello zeffo bro
async def roll(self, ctx, args, aliases = ['r', 'diceroll', 'dice_roll', 'dice']):
not_failure = True
try:
indice = []
cont = 0
for indz in args:
if indz == "+" or indz == "-" or indz == "*" or indz == "/":
indice.append((cont,cont+1), indz)
cont = cont+1
args_result = args.split('+', '-', "*", "/")
#resp_total
#total
ind = 0
for y in args_result:
if "#" in y:
ind = ind + 1
if y != args_result[0]:
not_failure = False
break
if ind > 1:
break
if not_failure:
for x in args_result:
if "#" in args_result[0]:
mark = args_result.split('#')
args_result[0] = mark[1]
mark.pop(1)
for z in range(0, mark):
except:
not_failure = False
#wait ctx.send(f"")```
there's nothing after your for loop
Why are you wrapping the whole thing in a try/except lol
None of your errors are going to show
good night mudkip !
not_failure = False lol
?
`
it's called a backtick btw
it's the tilda key below escape
you can't do banned_users = await ctx.guild.bans()
you have to iterate over it, like this:
async for ban_entry in ctx.guild.bans():
...
lucas unban cmd 
it could be worse
@client.event
async def on_message(message):
if message.startswith("!unban"):
:troll:
i mean the builtin unban command works perfectly fine~
What do the values look like if they select two. As all I have to do is check if two match then if they aren't supposed to match I can decline it
how would i do that
just do max_values = 25
that's all, you don't need anything else
no no
I mean, I'm trying to make combos. So say for example they do 1 and 3, I don't want them to be able to click 2. Which isn't possible so I have to make it where if they select a combo that I don't want (by checking the values) it'll just say they can't do that
that's not possible
like robin already said, you'd have to send them a message saying they can't do that
That's what I want to do
but I don't know how I'm supposed to see what 2 they selected
My testing is showing me that even when selectin the first two it only shows the response for the first one rather than both
@discord.ui.select()
async def select(self, interaction: discord.Interaction, select: Select):
return await interaction.response.send_message(f'You selected {select.values[0]}')
I have three values, acc1, acc2, and acc3
I'm selecting the first two meaning acc1 and acc2
it's only giving me the acc1 value response
@smoky sinew
class BarrettaAccessories(View):
@discord.ui.select(placeholder="Barretta Accessories", min_values=1, max_values=3, options=[
SelectOption(label="Lazer (beam)", value='acc1'),
SelectOption(label="Flash (light)", value='acc2'),
SelectOption(label="Red dot (scope)", value='acc3')
])
async def select_callback(self, interaction, select):
if select.values[0] == 'acc1':
await interaction.response.send_message(f"{select.values[0]} + Acc 1")
if select.values[0] == 'acc2':
await interaction.response.send_message(f"{select.values[0]} + {select.values[0]} Acc 2")
if select.values[0] == 'acc3':
await interaction.response.send_message("Acc 3")
don't mind the acc2 thing I meant to put 1 instead of 0
don't know, try putting user: discord.User
no
it would be if "acc1" in select.values:
so would I do if "acc1" and "acc2" in select.values:
When checking if something is equal to one thing or another, you might think that this is possible:
# Incorrect...
if favorite_fruit == 'grapefruit' or 'lemon':
print("That's a weird favorite fruit to have.")
While this makes sense in English, it may not behave the way you would expect. In Python, you should have complete instructions on both sides of the logical operator.
So, if you want to check if something is equal to one thing or another, there are two common ways:
# Like this...
if favorite_fruit == 'grapefruit' or favorite_fruit == 'lemon':
print("That's a weird favorite fruit to have.")
# ...or like this.
if favorite_fruit in ('grapefruit', 'lemon'):
print("That's a weird favorite fruit to have.")
okay well besides that is that how I would do it
@sturdy shadow read the above, it would be separate if statements for each of them, or do if "acc1" in select.values or "acc2" in select.values:
didn't work
discord.app_commands.errors.CommandInvokeError: Command 'test' raised an exception: ValueError: I/O operation on closed file. what does this error mean
yes??
what's wrong with that
by using the code you sent lol
it's == not =
and you can just do:
if reason:
...
else:
...
what is reason
did you set a default?
put reason = None
no...
keep the same code, just do if reason:
await member.send(f'If you wish to rejoin {guild.name}, you can use this invite link: {invite}')
@slate swan this code won't work, the member is already out of the server before you send this message
no that doesn't work
I need both values though
a bot can't just randomly send messages to a user that it doesn't share any servers with
if someone is selecting multiple values for example they select 3 options
@sturdy shadow
You would need to check if you have a mutual server with the user. If you do then you could reinvite them
oops wrong ping 😭
@smoky sinew
yes, because that doesn't work
if reason:
# reason is a string
else:
# reason is None (no reason)
@slate swan
I honestly don't know how to do that. or see why it would be needed as it's easier to ban someone with a id
you just need to change the order, send the message before you kick them
you would need a way to get the id of the user through the name a discrim
id works but i want to make it so u can do it with the user+discrim
`
That's what I'm saying you need to figure out how to turn a username+discrim into a id. if you can't do that just make a db with usernames and if a user joins and their username matches it ban them (would be bad though as people can change their user)
you forgot to put reason: str = None again
to fix this
wait idk if you're doing it but you should send the message before they get kicked
already said that btw
didn't see
@slate swan why are you creating and sending the invite twice, and you're sending the rejoin message before you even create the invite
if I select say 3 things will the values thing now go to select.values[2]
yeah it does since it's a list
that's all I need to do, check how many values are in the list lol
do you know to convert it?
You have an indent issue
no, you put the = None part in the function arguments and keep if reason:
how do i convert a user+discrim to an id
@clear elmpy @bot.command() async def info(ctx, user:discord.User): return await ctx.send(user.id)
are there any bots or people that know how to help make a bot to create a list of discord usernames linked with xbox gamertags?
slash command*
that has nothing to do with this?
Like, someone enters their gamertag when they join the server and it creates a list
he's making a slash command, you cannot use that converter
nope
weird that you can't
use oauth2 to get the xbox connection from their profile, you skip the need to enter the gamertag entirely
just do this then
will this create a list for us to look back at?
we want a command that we can type in to pull all that information up
if you have any tips, dm me if you have the time. i have to head to work
@bot.tree.command(name="unban", description="Unbans the specified user.")
async def info(interaction, user: str):
return await interaction.send(user)```
would this work?
@bot.command()
async def info(ctx, user):
username = username.split("#")
print(f"{username[0]} = {username[1]}")
user = discord.utils.get(guild.members, name=username[0], discriminator=username[1])``` works for me
not sure if it'll work in slash command though
it's not a discord bot, it's going to use the connections scope, it will give a list of everything linked to the discord account and it will use a web server
but you can use a discord bot after that
Can you dm me about this if possible? That would be perfect
what do you need to know?
I have to go to work atm so I wont respond but I would love to learn more about that
Ill dm you super quickly
alright
@bot.tree.command(name="unban", description="Unbans the specified user.")
@commands.has_permissions(ban_members=True)
async def unban(interaction, user: str):
guild = interaction.guild
try:
user = int(user)
await guild.unban(discord.Object(user))
except ValueError:
username = username.split("#")
print(f"{username[0]} = {username[1]}")
user = discord.utils.get(guild.members, name=username[0], discriminator=username[1])
channel = bot.get_channel(1073724291515949077)
unbanlogEmbed=discord.Embed(title="Logging | Unban Command", color=0xFF5349)
unbanlogEmbed.add_field(name="Executed by:", value=f'{interaction.user}', inline=True)
unbanlogEmbed.add_field(name="Executed on:", value=f'{user}', inline=True)
unbanlogEmbed.set_footer(text="Made by justin;#6868")
unbanlogEmbed.set_author(name=f'{interaction.user}', icon_url = f'{interaction.user.display_avatar}')
await channel.send(embed=unbanlogEmbed)
unbanEmbed=discord.Embed(title="an Command", color=0xFF5349)
unbanEmbed.add_field(name=f'{interaction.user} has executed:', value="Unban Command", inline=False)
unbanEmbed.set_footer(text="Made by justin;#6868")
unbanEmbed.set_author(name=f'{interaction.user}', icon_url = f'{interaction.user.display_avatar}')
await interaction.response.send_message(embed=unbanEmbed)```
is that right?
run it and test it lol
username isn't defined
you wanna unban using name#discrim?
and also be able to with an id
it's not
you can do something like this ```py
id_or_tag: str
try:
member = await guild.fetch_ban(int(id_or_tag))
except ValueError, discord.NotFound:
name, discrim = id_or_tag.split("#")
async for member in guild.bans():
# check where name = member and discrim = member.discriminator
member = member
break
await member.unban()
because guild.members means the member who are already in the cache
user = discord.utils.get(guild.members, name=username[0], discriminator=username[1])
so this is basically useless
guild = interaction.guild
try:
user = int(user)
await guild.unban(discord.Object(user))
except ValueError:
username = username.split("#")
print(f"{username[0]} = {username[1]}")
user = discord.utils.get(guild.members, name=username[0], discriminator=username[1])```
can i replace all of this ^ with this v
```py
id_or_tag: str
try:
member = await guild.fetch_ban(int(id_or_tag))
except ValueError, discord.NotFound:
name, discrim = username.split("#")
async for member in guild.bans():
# check where name = member and discrim = member.discriminator
member = member
break
await member.unban()```
that's just some pseudocode, copy pasting wont work
should i separate my bot into a fun bot and a moderation bot? or should i keep it in one?
Can't you just use discord.User converter?
won't work for username#discriminator if the user is not cached
hello andy bro
hi, why python say me "<" is str?
it's math, it's the "less than" sign
i dont understand
< is not the string. level is probably a string, which can't be compared to an int
the level var content int data...
the error message says otherwise
look:
@bot.event
async def on_ready():
print("C'est ok!")
print("Le bot est connecté au serveur discord")
setattr(bot, "db", await aiosqlite.connect("level.db"))
await asyncio.sleep(3)
async with bot.db.cursor() as cursor:
await cursor.execute("CREATE TABLE IF NOT EXISTS levels (level, INTEGER, xp INTEGER, user INTEGER, guild INTEGER)")
@bot.event
async def on_message(message):
if message.author.bot:
return
author = message.author
guild = message.guild
async with bot.db.cursor() as cursor:
await cursor.execute("SELECT xp FROM levels WHERE user = ? AND guild = ?", (author.id, guild.id,))
xp = await cursor.fetchone()
await cursor.execute("SELECT level FROM levels WHERE user = ? AND guild = ?", (author.id, guild.id,))
level = await cursor.fetchone()
if not xp or not level:
await cursor.execute ("INSERT INTO levels (level, xp, user, guild) VALUES (?, ?, ?, ?)", (0, 0, author.id, guild.id,))
await bot.db.commit()
try:
xp = xp[0]
level = level[0]
except TypeError:
xp= 0
level= 0
if level < 5:
xp += random.randint(1, 3)
await cursor.execute("UPDATE levels SET xp = ? WHERE user = ? AND guild = ?", (xp, author.id, guild.id,))
else:
rand = random.randint(1, (level//4))
if rand == 1:
xp +=random.randint(1, 3)
await cursor.execute("UPDATE levels SET xp = ? WHERE user = ? AND guild = ?", (xp, author.id, guild.id,))
if xp >= 100:
level +=1
await cursor.execute ("UPDATE levels SET level = ? WHERE user = ? AND guild = ?", (level, author.id, guild.id,))
await cursor.execute ("UPDATE levels SET xp = ? WHERE user = ? AND guild = ?", (0, author.id, guild.id,))
await message.channel.send (f"{author.mention}, tu viens de passer au niveau **{level}**!")
await bot.db.commit()
level is TEXT type there
"CREATE TABLE IF NOT EXISTS levels (level, INTEGER, xp INTEGER, user INTEGER, guild INTEGER)"
level is string
how to convert it?
is there any way to copy the text in embed when a user presses a button?
remove that extra comma you have between level and INTEGER, then maybe recreate your database
copy on their clipboard? no.
don't know how you did it in the first place because that should be invalid syntax
why is it not possible?
because that would be a huge security risk
letting people copy whatever they want to people's clipboards? nah
why? the user would copy the text on his responsability
If you want to copy text, highlight it then ctrl+c
it's just not a feature
ho shit! I did not see! this is a silly mistake!
if the user will hold the description for 2-3 seconds it will be copied automatically, why do you want the button to do it?
for pc users they can just copy paste as usual
why does it say "[Errno 2] No such file or directory"
send the full traceback and which line it happens on
and also.. don't parse your commands manually smh use an app command or a normal command
i was running the wrong file ty
it wont let my bot send a message
it doesnt show an error though, anyone know abt the issue?
Typehint user as a discord.User and discord.py will do the rest
Have you enabled the message content intent
definitely not 🚶♂️ see their Client constructor
intents.message_content = True
AttributeError: 'Intents' object has no attribute 'message_content'
bruh
that didn't work
update your discord.py
are you even on version 2.0? @inland venture
how do i check??
the command not appear, it's as if nothing is happening, but i don't get an error```py
import os
import discord
from discord.ext import commands
from dotenv import load_dotenv
import aiosqlite
import asyncio
import random
from easy_pil import *
import math
@bot.command()
async def level(ctx, member: discord.Member=None):
if member is None:
member=ctx.author
async with bot.db.cursor() as cursor:
await cursor.execute("SELECT xp FROM levels WHERE user = ? AND guild = ?", (member.id, ctx.guild.id,))
xp = await cursor.fetchone()
await cursor.execute("SELECT level FROM levels WHERE user = ? AND guild = ?", (member.id, ctx.guild.id,))
level = await cursor.fetchone()
if not xp or not level:
await cursor.execute ("INSERT INTO levels (level, xp, user, guild) VALUES (?, ?, ?, ?)", (0, 0, member.id, ctx.guild.id,))
await bot.commit()
try:
xp = xp[0]
level = level [0]
except TypeError:
xp= 0
level= 0
userData = {
"name": f"{member.name}#{member.discriminator}",
"xp": xp,
"level": level,
"next_level_up": math.ceil(6*level**4//2.5),
"percentage": xp/math.ceil(6*level**4//2.5)*100,
}
background = Editor(Canvas(900, 300), color="#141414")
profile_picture = await load_image_async(str(member.avatar.url))
profile = Editor(profile_picture).resize((150, 150)).circle_image()
poppins = Font.poppins(size=40)
poppins_small = Font.poppins(size=20)
card_right_shape = [(600, 0), (750, 300), (900, 300), (900, 0)]
background.polygon(card_right_shape, color="#FFFFFF")
background.paste(profile, (30, 30))
background.rectangle((30, 220), width=650, height=40, color="#FFFFFF")
background.bar((30, 220), max_width=650, height=40,percentage=userData["percentage"], color="#383838", radius=20,)
background.text((200, 40), userData["name"], font=poppins, color="#FFFFFF")
background.rectangle((200, 100), width=350, height=2, fill="#FFFFFF")
background.text(
(200, 130),
f"Niveau: {userData[level]} | XP: {userData['xp']}/{userData['next_level_up']}",
font = poppins_small,
color="#FFFFFF",
)
file = discord.File(fp=background.image_bytes, filename="levelcard.png")
await ctx.send(file=file)
indentation problem?
bot definition?
bot = commands.Bot (command_prefix="!", help_command=None, intents=intents)
I tried -m pip install --upgrade pip but it wouldnt let me do it
-m : The term '-m' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
- -m pip install --upgrade pip
- ~~
- CategoryInfo : ObjectNotFound: (-m:String) [], CommandNotFoundException
- FullyQualifiedErrorId : CommandNotFoundException
python -m pip install --upgrade pip
🫤
the bot is defined...
does the command show up in the help menu>
and do you have message_content intents?
i desactivate help menu...
Using intents in discord.py
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.
im talking about this thing
@slate swan
i have this:
@bot.event
async def on_message(message):
if message.author.bot:
return
author = message.author
guild = message.guild
async with bot.db.cursor() as cursor:
await cursor.execute("SELECT xp FROM levels WHERE user = ? AND guild = ?", (author.id, guild.id,))
xp = await cursor.fetchone()
await cursor.execute("SELECT level FROM levels WHERE user = ? AND guild = ?", (author.id, guild.id,))
level = await cursor.fetchone()
if not xp or not level:
await cursor.execute ("INSERT INTO levels (level, xp, user, guild) VALUES (?, ?, ?, ?)", (0, 0, author.id, guild.id,))
await bot.db.commit()
try:
xp = xp[0]
level = level[0]
except TypeError:
xp= 0
level= 0
if level < 5:
xp += random.randint(3, 5)
await cursor.execute("UPDATE levels SET xp = ? WHERE user = ? AND guild = ?", (xp, author.id, guild.id,))
else:
rand = random.randint(1, (level//4))
if rand == 1:
xp +=random.randint(3, 5)
await cursor.execute("UPDATE levels SET xp = ? WHERE user = ? AND guild = ?", (xp, author.id, guild.id,))
if xp >= 100:
level +=1
await cursor.execute ("UPDATE levels SET level = ? WHERE user = ? AND guild = ?", (level, author.id, guild.id,))
await cursor.execute ("UPDATE levels SET xp = ? WHERE user = ? AND guild = ?", (0, author.id, guild.id,))
await message.channel.send (f"{author.mention}, tu viens de passer au niveau **{level}**!")
await bot.db.commit()
no
you cant use prefix commands without that
i have imported all intent... scuze me
import os
import discord
from discord.ext import commands
from dotenv import load_dotenv
import aiosqlite
import asyncio
import random
from easy_pil import *
import math
intents = discord.Intents.all()
bot = commands.Bot (command_prefix="!", help_command=None, intents=intents)
load_dotenv()
TOKEN = os.getenv("TOKEN")
I said what I said
send ur full code
!paste it's hard to guess
Pasting large amounts of code
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.
what Catgal said, you're not processing commands
change the .event decorator on on_message to .listen()
does a field in an embed have to have a name and value?
yes.
if you want an empty one there's a workaround
just use \u200b as the value/name
is there a way to remove the big space?
for all of it?
yes
how?
!e ```py
print("""
some big line you have below the title
Username:
Department:
Invited by:
""")
@slate swan :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 |
002 | some big line you have below the title
003 | Username:
004 | Department:
005 | Invited by:
oh
ok
is it like this?
@bot.command()
async def verify(ctx):
verifyEmbed=discord.Embed(title=":kazuetypo: | DEPARTMENT SERVER VERIFICATION", description="
To be verified, please fill out the following format and once of our presidential members or department leads will rank you.
Username:
Department:
Invited by", color=0xFF5349)
await ctx.send(embed=verifyEmbed)```
triple quotes """
No
if you don't know the content of the description, you can also do this:
embed = discord.Embed(title = "My Embed", description = "")
for _ in range(3):
embed.description += "something\n"
thank you!
np
@bot.event
async def on_member_join(ctx, member):
channel = bot.get_channel(1058184521587105853)
await channel.send(f'{member.mention}')```
```Traceback (most recent call last):
File "/home/runner/kazue-bot-frfr-dep/venv/lib/python3.10/site-packages/discord/client.py", line 409, in _run_event
await coro(*args, **kwargs)
TypeError: on_member_join() missing 1 required positional argument: 'member'```
there's no context for events
what
oop
ive used it before and it worked
anyways, i removed it but it still doesn't work
show me the error
if an event passes two arguments, and you put ctx, argument, it would work fine but you are mislabeling one of them because argument would actually be the second argument passed
no error
do you have your members intent enabled?
yes
then i don't know
is it something in my code?
add a print statement maybe
i removed seomthing from my code and it worked
ok
but i want the part that i deleted
i'm not sure
Pasting large amounts of code
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.
what's the difference between brief and description
no, cogs is the thing that you inherit from
extensions are the files
ohh
you also forgot help lol
brief is the short version, help is the long one though
as for description idk
@smoky sinew do you think this code has anything to do with py @bot.event async def on_member_join(member): channel = bot.get_channel(1062870831413334127) await channel.send(f'{member.mention}')
you removed ALL of that code
what did you actually remove
yes
so you removed your bot variable too
well yeah if you have two bot variables and the second bot is not actually doing anything of course it's gonna start working when you remove it
you had an empty bot the entire time
thank you
yes
🥹
if its something async then it will be fine
@bot.event
async def on_member_join(member):
channel = bot.get_channel(1062870831413334127)
await channel.send(f'{member.mention}')```
how would i delete the message after?
i believe you can use delete_after if you want to delete a message after a set amount of time
@bot.event
async def on_member_join(member):
channel = bot.get_channel(1062870831413334127)
await channel.send(f'{member.mention}')
delete_after = 3
await asyncio.sleep(delete_after)```
would this work?
!d discord.abc.Messageable.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's a delete_after kwarg in send
i believe its await channel.send(your message, delete_after=3)
are you using dpy 2.0+?
in migrating to v2.0 it says:
Member.avatar_url_as (replaced by Member.avatar.replace)
it says what it was replaced by: Member.avatar.replace
it doesnt take a png it takes a url so you can do embed.set_thumbnail(url=ctx.message.author.avatar)
!d discord.Asset.replace
replace(*, size=..., format=..., static_format=...)```
Returns a new asset with the passed components replaced.
Changed in version 2.0: `static_format` is now preferred over `format` if both are present and the asset is not animated.
Changed in version 2.0: This function will now raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.11)") instead of `InvalidArgument`.
@bot.event
async def on_member_join(member):
channel = bot.get_channel(1062870831413334127)
await channel.send(f'{member.mention}')
delete_after = 3
await asyncio.sleep(delete_after)```
sends the message but doesn't delete it
no errors
also this
it goes for any user really (as long as you that data)
ctx.author or the user that was passsed in the member arg
delete_after is added into the send with a associated number of seconds
how do i do that
i sent the docs here, it tells you what the delete_after kwarg takes & does
are you still using it in your else block
its just .avatar not avatar_url_as
func(..., key=value) you can pass kword args into a function like this
also its useful to show the entire traceback instead
it shouldn't be ctx.message.author.avatar it should be user.avatar (or even better, user.display_avatar) and you're still using member.avatar_url_as in your else block
oh i didnt know display_avatar was a thing. whats the difference?
shows the default avatar if the user has none
avoids the whole "user.avatar is None"
how is it possible to have no avatar? just the default?
Yes
the default discord avatars when a user never sets one after making an account (iirc u can have them by also just removing your pfp)
ah ok thanks 👍
!d discord.abc.User.display_avatar
property display_avatar```
Returns the user’s display avatar.
For regular users this is just their default avatar or uploaded avatar.
New in version 2.0.
ye you can
is there a way to have 2 functions running at the same time?
await stoptyping()
await oc_submissions.submissions_handler(client, message)
I have these 2 functions and the stoptyping one removes the ability to type in a channel for 20 seconds, and i want that there so that the second function has time to set up its stuff
!e
import asyncio
async def func(id):
print(f"[{id}] started")
await asyncio.sleep(3)
print(f"[{id}] ended")
async def main():
loop = asyncio.get_event_loop()
task_1 = loop.create_task(func(1))
task_2 = loop.create_task(func(2))
await task_1
await task_2
asyncio.run(main())
@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | [1] started
002 | [2] started
003 | [1] ended
004 | [2] ended
Don't exactly sure if that's what you mean
yeahhh something like that! Cuz if it so happens that 2 people send a message to that channel right after another then itll cause other issues that i dont know how to fix, so i just set it up that it mutes the channel for a bit
unless do you think youd be able to help me figure out the other issue im running into o:?
@bot.event
async def on_member_join(member):
channel = bot.get_channel(1062870831413334127)
await channel.send(f'{member.mention}')
delete_after = 3
await asyncio.sleep(delete_after)```
sends the message but doesn't delete it
no errors
you dont have a .delete() on any message
await channel.send("...", delete_after =3)
its a kwarg in .send
!d discord.Message
class discord.Message```
Represents a message from Discord.
x == y Checks if two messages are equal.
x != y Checks if two messages are not equal.
hash(x) Returns the message’s hash.
here is a delete_after kwarg
Oh fk
^^^
!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**.

Btw always check docs
yes
ok
how do i make a sleect menu disable after like 30 seconds?
ohh ok
U need to edit the msg anyway and put view=self
!paste
Pasting large amounts of code
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.
Just set the timeout 🤷
what should go in (...)
hello
it'd be better if you explained what your end goal is
Well the end goal is where it gives me a different response for the accessories I'm using
so it should just list all the accessories you selected?
Well honestly now that I think about it I just need to be able to create a new channel that will upload this data to it
How can I send a private message to the user using slash commands?
So I need to store the accessories to a variable, list the accessories allow them to confirm or deny it. If it's a confirm create a channel with given info
if you have an interaction, you can use await interaction.user.send(...)
from your account or the bot's account
bot's
what mudkip said
so do you have a question?
but make sure you respond to the interaction too
^
self
me when i replace self with this and start adding semicolons to my code
intents.message_content = True
AttributeError: 'Intents' object has no attribute 'message_content'
update your discord.py as i've said earlier
???
Outdated lib
and stop parsing message commands manually
I did
then print out the version, if it actually worked you wouldn't get that error
1.7.3
so you didn't update
i attempted to upgrade my version, yet i didnt get an update
try pip install --upgrade discord.py, if that doesn't update it then check if your command line python is the same as your pycharm python
thank u
now i got a new issue
client = discord.Client()
TypeError: init() missing 1 required keyword-only argument: 'intents'
!intents
Using intents in discord.py
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.
is it able to make the bot send a message to a specified channel by its ID or name?
!d discord.Client.get_channel
get_channel(id, /)```
Returns a channel or thread with the given ID.
Changed in version 2.0: `id` parameter is now positional-only.
since I don't need to really "save" the data can I just store it to a variable temporarily until the ticket is made
That's a stupid question, for some reason I thought if I had too many people doing it
It would affect it lol
how will it know when to timeout
AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py:370: RuntimeWarning: coroutine 'submissions_handler.<locals>.check' was never awaited
result = condition(*args)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Why am i getting this error? i dont even have a file with 370 lines.
C:\Users\Rosy\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py:132: RuntimeWarning: coroutine 'submissions_handler.<locals>.check' was never awaited
super().dispatch(event_name, *args, **kwargs)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
C:\Users\Rosy\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py:370: RuntimeWarning: coroutine 'submissions_handler.<locals>.check' was never awaited
result = condition(*args)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
thats the full traceback
i went through all my stuff and everything seems to have an await
show your code
async def submissions_handler(client, message, delete1, delete2):
Approval_channel = client.get_channel(APPROVAL_CHANNEL)
sent_message = await Approval_channel.send(message.content)
# add the base reactions to the message
reactions = ['\N{WHITE HEAVY CHECK MARK}', '\N{CROSS MARK}']
for reaction in reactions:
await sent_message.add_reaction(reaction)
await asyncio.sleep(5)
await message.delete()
await delete1.delete()
await delete2.delete()
# Check for the wait-for
async def check(reaction, user):
role = discord.utils.get(user.guild.roles, name="OC Approver")
return role in user.roles
reaction, user = await client.wait_for("reaction_add", check=check)
await sent_message.remove_reaction(reaction, user)
if str(reaction.emoji) == "\N{WHITE HEAVY CHECK MARK}":
await sent_message.clear_reactions()
await Approval_channel.send(f"Accepted by: {user}")
await client.get_channel(APPROVED_CHARACTERS_ID).send(
f"**OC APPROVED FOR {message.author}**\n\n{message.content}")
elif str(reaction.emoji) == "\N{CROSS MARK}":
await sent_message.clear_reactions()
await Approval_channel.send(f"Rejected by: {user}")
await message.author.send(
"Unfortunately, your submission was rejected. Please contact staff if you think this is a mistake.")
Don't need to be async
gotcha
async def on_timeout(self):
await self.bot.send_message(self.channel, "You took too long to respond. Please try again.")
print("timedout")
self.clear_items()```should this work?
no
is it able to make the bot send a message to a specified channel by its ID or name by slash command?
so when should i use brief vs. description
use help over both of them
um actually it's just a preference.... description is the most preferable for consistency since it plays an actual role in app_commands ( which you might want to switch up later ), havent really seen people using brief or help
Hm 
why does it come out like this rather than just saying the actual message
@bot.event
async def on_message_delete(message):
channel = bot.get_channel(1063026363084316703)
deletelogEmbed=discord.Embed(title="A message has been deleted!", description=f'Message: {message}', color=0xFF5349)
await channel.send(embed=deletelogEmbed)```
how can i make it say the message rather than saying all of that
the deleted message
And which part of it??
the text
Then get the content out of it
how
!d discord.Message.content
The actual contents of the message. If Intents.message_content is not enabled this will always be an empty string unless the bot is mentioned or the message is a direct message.
It's called reading the docs
Is there a code where like...I search some words (just like the search section of the server) and the bot gives like 5-10 results?
Like a quick way to search using slash commands
Why don't just use Discord's built-in
Oh you mean
Here @slate swan
But it's only for a specific user I think...but yeah!! Can I do the same thing with my bot?
Can you explain further
What does it's only for specific user supposed to mean
I want the built in discord search command in my bot
So you want to search for messages on discord with your discord bot?
Yeahhh
That could be challenging
Especially if you have many messages on the server
Even the discord search sometimes breaks
Oh no I was wrong....there's no built in slash command like that
Now imagine putting that type of technology into a bot
True
But still like does anyone have any idea about the code? Maybe just 5 recent searches related to the topic in a specific channel will do!
hi
Yeah there's a search element haha but like I want to do it with the bot!
Json , python
JSON is a language? 
And you will risk rate limit doing it
^
I swear I just started yesterday lol...but I learnt a lot haha!
Alright
In js, you could easily do channel.messages.fetch
Only works for the channel it runs on though
Oh that's helpful!!
Not the entire server
There's also a limit
For example: channel.messages.fetch({ limit: 10})
Alr listening!
Set 10 to the limit
100, 1000, etc
I think that's how it works. Not very sure though
!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 "(in Python v3.11)") 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 "discord.Permissions.read_message_history") to do this.
Examples
Usage...
So like we can only search for 10 results ?
Thanks that's really helpful!!
Then, you'd do something like messages.filter with the inputted keyword
Very helpful thankyou!!
I am 17
from what i know there's none
Damn
you can add the textinputs as classvars tho
I feel like other people might be more older than me lol
Oh
Damn you know a lot about this haha @/shiv_uwu#2651
Do you have them installed
pip install [module name]
add an init.py in the modules folder
Create a file named __init__.py in that module
Oh fuck
./modules folder?
yea
Try
sys.path.append('/path/to/your/folder')
Then import roblox
I'll try GPT wait
Do you have a __init__.py file
.
Same directory
Yes
In this tutorial, you will learn to create and import custom modules in Python. Also, you will find different techniques to import and use custom and built-in modules in Python.
modules/init.py
Learn about modules and imports for beginners in python in this Python Tutorial. Why are we using modules in python and in programming in general? Why is it so important to know, learn and use?
In this video, I'll tell you about modules/packages in Python and i'll show you guys some different kinds of examples of how to import modules and use t...
Nothing
🙏
Blank
do you know why i get this error?
discord.errors.HTTPException: 400 Bad Request (error code: 50035): Invalid Form Body
In components.0.components.0: Value of field "type" must be one of (2, 3, 5, 6, 7, 8).
Yeah fine
Read error
...
...
We all have to start somewhere
Python is a powerful general-purpose programming language. Our Python tutorial will guide you to learn Python one step at a time with the help of examples.
👍
Yeah most bot developers are like that haha
Proudly made by people in my country
!resource
Yesyes it's okay to learn like that
!resources
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

True!
can i see your code? it seems like you're using a textinput inside a View class
class GamertagInput(discord.ui.TextInput):
def __init__(self):
super().__init__(label = "Gamertag")
async def callback(self, interaction):
await interaction.response.send_message("Successfully verified!")
view = discord.ui.View()
view.add_item(GamertagInput())
await _ctx.send(view = view)
nuuu, textinputs are meant to be used with modals
Bro 👀
hi! does anyone knows how to make commands that disables and enables the whole entire bot
Going to say that
did not know that
basically uhh when u disable it if u try to run any command it will show an embed says that the bot is disabled
Try searching for shutdown bot python on youtube!
....
ah alr tysm
you'll have to send a message with a button or any other component which will send a modal in response in order to get this to work
Eh, I won't recommend that
I don't get what you're trying to say
Well if he shut it down, then he cant run / on it from commands anyway
My wifi is trippin
I swear these language barriers
Tho i can disable them
if you just want to update your commands without restarting bots, look into cogs.
You*
Really? Oh god why? I tried it yesterday
the restart system is completely absurd
Try discord.TextInput instead
class discord.TextInput```
Represents a text input from the Discord Bot UI Kit.
Note
The user constructible and usable type to create a text input is [`discord.ui.TextInput`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.TextInput "discord.ui.TextInput") not this one.
New in version 2.0.
It worked but like I don't how to make it exclusive only for a particular role
UwU
How still it's going to work kek
!d discord.ext.commands.has_any_role
@discord.ext.commands.has_any_role(*items)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.check "discord.ext.commands.check") that is added that checks if the member invoking the command has **any** of the roles specified. This means that if they have one out of the three roles specified, then this check will return `True`.
Similar to [`has_role()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.has_role "discord.ext.commands.has_role"), the names or IDs passed in must be exact.
This check raises one of two special exceptions, [`MissingAnyRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingAnyRole "discord.ext.commands.MissingAnyRole") if the user is missing all roles, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure").
Changed in version 1.1: Raise [`MissingAnyRole`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.MissingAnyRole "discord.ext.commands.MissingAnyRole") or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.NoPrivateMessage "discord.ext.commands.NoPrivateMessage") instead of generic [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure")
Ayo no swear 
@lofty aurora Who's that on your pfp
Thanks!
Dunno random girl lmao
.

beech
beach*

i'll get away before the chat goes offtopic
I think her name is haerin @/shiv_uwu#2651 ...she does music!

Lol
freaking*?
You listen to kpop? @lofty aurora
spooky i wanna test a ban command, want to be my subject?
Have a nice day
Only newjeans tbh
Sure 
will a slash command work?
ong
Others are cringe
Yes
Sameeee
Anything which is "interactable" will work tho this word doesnt exist kek
Yeah they're genuinely good people lol
^
Pretty hype though
This
Lmao exactly
sadly not, Modal responses can be created only from 2, 3, 5, 6, 7, 8 component types ( i.e. buttons and select menus )
Off topic pls 
WHAT TF??
interesting
Adios
....wutt
ok show me in wyvern
BRO U gey u dont know kek
Lemme quickly turn my bot on and whoop yo ass
where'd you get 678 from?
Oh nvm
https://discord.com/developers/docs/interactions/message-components#component-object-component-types component types
Integrate your service with Discord — whether it's a bot or a game or whatever your wildest imagination can come up with.
@smoky sinew it works for slash too apparently^
what
i just rewrote the code smhhhhhhh
are u serious
yea~
Told u 
i'm sorry, that's a recent update ig
last time i read about it it was limited to components only
the hardest part of being a discord bot developer is knowing how to spell ephemeral
uh-feh-mr-rhul
e-phem-e-ral
I think you can only mention stuff in the embeds description or in the value of a field
also logging deleted messages can be a bit shady
👻
only on mobile ™️
I guess it's probably not supported for all platform yet
never worked when i tried it
why is it shady? 😭
because you're storing deleted user data, potentially without the user's knowledge or consent, all i'm saying is to be careful
client = discord.Client()
TypeError: init() missing 1 required keyword-only argument: 'intents'
???
view migratibg to 2.0 guide
actually its a 1.5 feature
you need to pass intents to your bot now
i edit my embed every 60 seconds but i cant put a image in it
i tried
file = discord.File("boom.png", filename="image.png")
embed.set_footer(text="Updates every 195 seconds")
embed.set_image(url="attachment://image.png")
await message.edit(embed=embed)
@smoky sinew I tried what you told me in DM and it came up with all kinda errors lol
!d discord.Message.edit
await edit(*, content=..., embed=..., embeds=..., attachments=..., suppress=False, delete_after=None, allowed_mentions=..., view=...)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Edits the message.
The content must be able to be transformed into a string via `str(content)`.
Changed in version 1.3: The `suppress` keyword-only parameter was added.
Changed in version 2.0: Edits are no longer in-place, the newly edited message is returned instead.
Changed in version 2.0: This function will now raise [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.11)") instead of `InvalidArgument`.
attachments kwarg
thanks
ask sarth
attachments = file? or path to the file?
file = discord.File("boom.png", filename="image.png")
attachments=[file]
Ill worry about it tomorrow. thank you for all your help so far!
@commands.has_any_role(1074232507161120798)```
im using this to make it so only the people with that role can use the command but it's not working, it's a slash commadn
You need to use the app_commands.checks version of it
!d discord.app_commands.checks.has_any_role
@discord.app_commands.checks.has_any_role(*items)```
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 **any** of the roles specified. This means that if they have one out of the three roles specified, then this check will return `True`.
Similar to [`has_role()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.checks.has_role "discord.app_commands.checks.has_role"), the names or IDs passed in must be exact.
This check raises one of two special exceptions, [`MissingAnyRole`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.MissingAnyRole "discord.app_commands.MissingAnyRole") if the user is missing all roles, 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.
Note
This is different from the permission system that Discord provides for application commands. This is done entirely locally in the program rather than being handled by Discord.
ohh, thank
the only time checks from commands works with slash commands is if its a hybrid in dpy, otherwise you need to use app_commands.checks (just to clarify)
thanks
@training.error
async def training_Error(ctx, error):
if isinstance(error, commands.MissingRole):
traininerrorEmbed=discord.Embed(title="Uh oh!", desciption="You cant do that! Try again when you have the correct roles!", color=0xFF5349)
await ctx.send(embed=traininerrorEmbed)```should this work?
This is not a Modmail thread.
...
Try it and see
Okay
so..?
So what? You tried it and got no errors
yeah
Great
but it didn't send the embed
Have you tried putting a print before sending the embed to see if it's getting called?
@upbeat gust
make an else case as well
possible that the error is not what u handled in the if case
else: ??
how can i make a selection restricted to only a specific role or users
Selection of what
u can't unless u make a channel specific with perms otherwise the select and its contents are visible to everyone
another way would be to make a secondary select and send an ephemeral response
yeah i have no idea how to do that, i know it's simple but i don't usually use error handlers 😭
in the callback if user meets requirements
raise error
thats the cide
Do you know Python syntax in general
well i figured it out
i wanted it so only admins could interact with dropdown menu
i did it like this, is there is a better way?
!d discord.ui.View.interaction_check
await interaction_check(interaction, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
A callback that is called when an interaction happens within the view that checks whether the view should process item callbacks for the interaction.
This is useful to override if, for example, you want to ensure that the interaction author is a given user.
The default implementation of this returns `True`.
Note
If an exception occurs within the body then the check is considered a failure and [`on_error()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.ui.View.on_error "discord.ui.View.on_error") is called.
Override this meth
^^ works both ways
okay thanks
we can only use ephemeral in interaction response? eh
await ctx.reply("Text", ephemeral= True)
its not working
How to get like in slash commands author of message?
anyone?
yes
!d discord.Interaction.user
The user or member that sent the interaction.
u can test again here
enable intents in dev portal
tysm
@shrewd fjord :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | AttributeError: 'str' object has no attribute 'message'
See?, This is how the error occurs
Hm 
*
Mind checking the docs xd
!d discord.ext.commands.Context.message
The message that triggered the command being executed.
Note
In the case of an interaction based context, this message is “synthetic” and does not actually exist. Therefore, the ID on it is invalid similar to ephemeral messages.
!d discord.Message.created_at
property created_at```
The message’s creation time in UTC.
Hm cool
The ctx isnt the context for some reason hm
Try printing ctx?
Wait wut..
Error is reason? How
it will be '{reason}' btw maybe xd

Nice
InteractionResponse.edit_message() got an unexpected keyword argument 'file'
I can't make it that the edited message has a file?
because i can do it with send_message
!d discord.InteractionResponse.edit_message
await edit_message(*, content=..., embed=..., embeds=..., attachments=..., view=..., allowed_mentions=..., delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).
Responds to this interaction by editing the original message of a component or modal interaction.
Use attachments kwarg
does it work the same as file where I just put the discord file object?
thx
Yeah it's same
alr i will try it, thx
But it's going to be list
attachments=[discord.File(...)]
Np
if your bot has global slash commands then it will automatically be shown afaik
its not smthg like <#commandid> ?
no
</meow:0>
that's not the same, it's just a description to make it look similar to the official one
it says at the end
your bot has to be verified and have global commands
They are added automatically as users use your slash commands
@commands.guild_only()
async def balance(ctx):
user = ctx.author
await open_bank(user)```
its showing indentation error here
can someone help?
Are you familiar with Python
is there a tutorial for hosting on VPS?
install python in vps if not installed
upload files
python3 filename.py
and?
wdym and
only a bit because of school haha
they teach very basic commands though
I would recommend being familiar with python and then hop into discord.py
so do i study some article?
you could use tmux for making it 24/7 or set up a panel

💀
it's been long since I started with python
just practice a lot
oh...sure!!
probably will start with the basics then
This guide shows how to host a bot with Docker and GitHub Actions on Ubuntu VPS
One of best ways


ive almost always spelled it empheral