#discord-bots

1 messages · Page 195 of 1

slate swan
#

about this

smoky sinew
#

no

ionic garden
#

how do i prevent other users from interacting with it?

hushed galleon
#

!d discord.ui.View.interaction_check < implement this method to decide when the view should reject an interaction

unkempt canyonBOT
#

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.
sturdy shadow
#

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

sick birch
#

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

timid spade
#

is it possible to add select options in Modals?

sick birch
#

No, I don't think

timid spade
#

buttons?

naive briar
#

No

timid spade
#

How can i get whatever user typed in the Modal for the text variable?

slate swan
#

How to fix this error

#

@sick birch

#

Anyone?

naive briar
#

Your bot simply don't have to permission to edit that guild

#

Read the error

slate swan
#

Oh

sick birch
timid spade
#

i want the text in another function
by text i mean the text user will input

sick birch
timid spade
sick birch
sturdy shadow
sick birch
#

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

timid spade
#

its a select call back

sick birch
#

What callback is this for?

#

Another modal?

timid spade
sick birch
#

Is the select menu sent after the modal?

timid spade
sick birch
#

So you want to pass the information from the select menu to the modal?

smoky sinew
#

you could add that to the __init__

slate swan
#
    @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

sturdy shadow
sick birch
sturdy shadow
#

min 1 max is however many options there are

sick birch
#

You just pass those values into min= and max= kwargs

sturdy shadow
#

would that be in the discord.ui.select()

#

or the option

smoky sinew
timid spade
flint belfry
#
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
slate swan
#

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?

sick birch
young dagger
#

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```
sick birch
sick birch
#

You want it to to run once every 5 seconds, yes?

young dagger
#

Correct @sick birch

sick birch
#

So you shouldn't need that while true loop

timid spade
sick birch
#

You just instantiate it there

#
class MySelect(ui.Select):
  ...

class MyModal(ui.Modal):
  ...

  async def on_submit(...)
    select = MySelect()
    # send select
slate swan
#

How do I pass a variable from a function so it's accessible within a class? @sick birch

sick birch
#

You pass it into the class's constructor

#
class MyClass:
  def __init__(self, arg):
    ...

def my_func(...):
  MyClass(arg)
smoky sinew
#

hi y9

smoky sinew
slate swan
#
class MyClass:
  def __init__(self, arg):
      blah
  if blah:
      newfunction

async def my_func(...):
  MyClass(arg)
  ctx.send(blahblah)
smoky sinew
#

why would you want to create a function if a certain condition was true 🤨

#

do you mean call a function

slate swan
smoky sinew
#

so you want to call a function

#

not create one

slate swan
#

Yeah @discord.ui.button

sick birch
smoky sinew
#

calling

sick birch
slate swan
#

So it needs to be indented with the init. then what does add_item do?

sick birch
#

It adds an item

#

!d discord.ui.View.add_item

unkempt canyonBOT
#

add_item(item)```
Adds an item to the view.

This function returns the class instance to allow for fluent-style chaining.
smoky sinew
#

but you have to instantiate it, don't create it with a decorator

slate swan
#

then how do I add everything else like the color of the button etc?

smoky sinew
#

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))
ionic garden
#

what's the convention for naming discord bot cogs?

smoky sinew
sick birch
#

Same as naming your classes

smoky sinew
#

unless you just do button.callback = ...

slate swan
smoky sinew
#

what do you mean, the callback when you press the button?

slate swan
#

yeah

#

Like what the bot will reply with if you press the button

smoky sinew
#
def callback(self, interaction):
    await interaction.response.send_message("hello")

if condition:
    button = Button(label = "My Button")
    button.callback = callback
#

like this

slate swan
#

and that'd also go within the class

smoky sinew
#

sure, that works

#

you can even define the callback function within __init__ if you want

slate swan
#

How so?

sick birch
#

Would not recommend

#

Just subclass your button tbh

smoky sinew
#

it wouldn't be any simpler

slate swan
smoky sinew
#
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

smoky sinew
slate swan
#

What if I have multiple buttons and multiple variable checks

smoky sinew
#

what about it

#

just do the same thing for other buttons

slate swan
#

Would I have to make a bunch of different callback functions?

smoky sinew
#

probably yeah unless they do something similar

slate swan
#

they all would reply with different things

smoky sinew
#
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

slate swan
#

is there no way to do this without add_item?

smoky sinew
#

why would you want to do that?

slate swan
#

Cause I don't want to manage each button individually like that

smoky sinew
#

this is the easiest way

slate swan
#

I don't understand why I can't just check the variable then call the buttons like how you would normally

smoky sinew
#

??? you don't "call the buttons" you define a new function

#

with the button decorator, which discord.py reads and adds that button

slate swan
#

yeah like that though why doesn't it work

sick birch
#

I don't see how you're "managing" every button

#

It's basically the same as with a decorator

smoky sinew
#

yeah

sick birch
#

You just get a bit more control

slate swan
#

I'm saying like why wouldn't it work checking the variable then still using the decorator

smoky sinew
#
def __init__(self, argument):
    if argument:
        my_button = discord.ui.button()(lambda self, interaction, button: ...)
#

you want to do this??

vocal snow
#

🥸

smoky sinew
#

don't even know if that works

slate swan
#

no, with the decorator but yeah

#

Why not though?

smoky sinew
#

actually well yeah

smoky sinew
#

it's the same thing but simpler

slate swan
#

because that's what I want it to do ? idk 🤣

smoky sinew
#

add_item is literally meant for this though

#

to add items to the view dynamically

slate swan
#

but would it work with the deco?

smoky sinew
#

@vocal snow

vocal snow
sick birch
#

It just adds the button regardless

#

The decorator is a shortcut for simple usecases

slate swan
sick birch
#

Then you're probably doing it wrong

smoky sinew
#

you shouldn't even do that anyway, that's messy

slate swan
#

it's simpler than doing it the other way though

smoky sinew
#

no it's not

#

it might be more complex but it's not any harder, plus it's more readable anyway

slate swan
#

I did not get it how you wrote it

smoky sinew
#

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

ionic garden
#

why are there two options

smoky sinew
#

just like how there are aliases for gray and grey

ionic garden
#

did they really make an alias for british people

smoky sinew
#

pretty sure colour is the real one lol

ionic garden
#

...

sturdy shadow
unkempt canyonBOT
#

discord/colour.py line 417

Color = Colour```
smoky sinew
#

@ionic garden

smoky sinew
ionic garden
#

can't believe it

clear elm
#

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)```
smoky sinew
#

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

ionic garden
smoky sinew
slate swan
#

why i'm receiving this exception (ignore the last line of code):

#

or better this in exception?

smoky sinew
#
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

ionic garden
#

tysm!

slate swan
#

i need help:

smoky sinew
#

also show the code above that

slate swan
#

sorry

#

code above?

vocal snow
#

code above the except

#

actually just paste your whole code

#

!paste

unkempt canyonBOT
#

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.

smoky sinew
slate swan
#
    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"")```
smoky sinew
#

there's nothing after your for loop

sick birch
#

Why are you wrapping the whole thing in a try/except lol

#

None of your errors are going to show

vocal snow
smoky sinew
#

?

#

`

#

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():
    ...
slate swan
#

lucas unban cmd skull

smoky sinew
#
@client.event
async def on_message(message):
    if message.startswith("!unban"):
#

:troll‎:

slate swan
#

i mean the builtin unban command works perfectly fine~

sturdy shadow
smoky sinew
#

that's all, you don't need anything else

sturdy shadow
#

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

smoky sinew
#

that's not possible

#

like robin already said, you'd have to send them a message saying they can't do that

sturdy shadow
#

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

smoky sinew
#
    @discord.ui.select()
    async def select(self, interaction: discord.Interaction, select: Select):
        return await interaction.response.send_message(f'You selected {select.values[0]}')
sturdy shadow
#

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

clear elm
sturdy shadow
#
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

smoky sinew
smoky sinew
#

it would be if "acc1" in select.values:

sturdy shadow
#

so would I do if "acc1" and "acc2" in select.values:

smoky sinew
#

no

#

!or

unkempt canyonBOT
#

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.")
sturdy shadow
#

okay well besides that is that how I would do it

smoky sinew
#

@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:

sturdy shadow
#

yeah yeah I know but what I'm saying is

#

will select.values[0] contain both?

smoky sinew
#

select.values[0] is the first value selected

#

so no

clear elm
deep osprey
#

discord.app_commands.errors.CommandInvokeError: Command 'test' raised an exception: ValueError: I/O operation on closed file. what does this error mean

smoky sinew
#

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

sturdy shadow
smoky sinew
#

a bot can't just randomly send messages to a user that it doesn't share any servers with

sturdy shadow
#

if someone is selecting multiple values for example they select 3 options

clear elm
sturdy shadow
#

You would need to check if you have a mutual server with the user. If you do then you could reinvite them

clear elm
#

oops wrong ping 😭

clear elm
smoky sinew
#

yes, because that doesn't work

#
if reason:
    # reason is a string
else:
    # reason is None (no reason)

@slate swan

sturdy shadow
smoky sinew
#

you just need to change the order, send the message before you kick them

sturdy shadow
#

you would need a way to get the id of the user through the name a discrim

clear elm
smoky sinew
#

`

sturdy shadow
smoky sinew
#

you forgot to put reason: str = None again

sturdy shadow
#

to fix this

#

wait idk if you're doing it but you should send the message before they get kicked

sturdy shadow
#

didn't see

smoky sinew
#

@slate swan why are you creating and sending the invite twice, and you're sending the rejoin message before you even create the invite

sturdy shadow
#

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

sturdy shadow
#

You have an indent issue

smoky sinew
#

no, you put the = None part in the function arguments and keep if reason:

clear elm
#

how do i convert a user+discrim to an id

sturdy shadow
#

@clear elmpy @bot.command() async def info(ctx, user:discord.User): return await ctx.send(user.id)

zinc pollen
#

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?

sturdy shadow
zinc pollen
#

Like, someone enters their gamertag when they join the server and it creates a list

smoky sinew
sturdy shadow
#

You can't use user:discord.User or user.id in a slash command?

smoky sinew
#

nope

sturdy shadow
#

weird that you can't

smoky sinew
sturdy shadow
#

just do this then

zinc pollen
#

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

clear elm
#
@bot.tree.command(name="unban", description="Unbans the specified user.")
async def info(interaction, user: str):
    return await interaction.send(user)```
would this work?
sturdy shadow
#
@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

smoky sinew
#

but you can use a discord bot after that

zinc pollen
#

Can you dm me about this if possible? That would be perfect

smoky sinew
#

what do you need to know?

zinc pollen
#

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

smoky sinew
#

alright

clear elm
#
@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?

sturdy shadow
#

run it and test it lol

clear elm
#

username isn't defined

slate swan
#

you wanna unban using name#discrim?

clear elm
#

and also be able to with an id

smoky sinew
slate swan
#

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

clear elm
#
  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()```
slate swan
#

that's just some pseudocode, copy pasting wont work

smoky sinew
#

should i separate my bot into a fun bot and a moderation bot? or should i keep it in one?

pliant gulch
slate swan
smoky sinew
static holly
#

hi, why python say me "<" is str?

#

it's math, it's the "less than" sign

#

i dont understand

wicked atlas
#

< is not the string. level is probably a string, which can't be compared to an int

static holly
wicked atlas
#

the error message says otherwise

static holly
# wicked atlas 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()
slate swan
#

level is TEXT type there

#

"CREATE TABLE IF NOT EXISTS levels (level, INTEGER, xp INTEGER, user INTEGER, guild INTEGER)"

smoky sinew
static holly
#

how to convert it?

deep osprey
#

is there any way to copy the text in embed when a user presses a button?

wicked atlas
slate swan
wicked atlas
#

don't know how you did it in the first place because that should be invalid syntax

deep osprey
wicked atlas
#

letting people copy whatever they want to people's clipboards? nah

deep osprey
#

why? the user would copy the text on his responsability

wicked atlas
#

If you want to copy text, highlight it then ctrl+c

smoky sinew
static holly
slate swan
#

for pc users they can just copy paste as usual

rapid perch
#

Please review the same
Error When i am calling my function

#

Please help

inland venture
#

why does it say "[Errno 2] No such file or directory"

smoky sinew
#

and also.. don't parse your commands manually smh use an app command or a normal command

inland venture
#

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?

slate swan
slate swan
#

definitely not 🚶‍♂️ see their Client constructor

inland venture
#

intents.message_content = True
AttributeError: 'Intents' object has no attribute 'message_content'

smoky sinew
#

that didn't work

smoky sinew
#

are you even on version 2.0? @inland venture

inland venture
#

how do i check??

smoky sinew
#

print discord.__version__

#

yeah, you're definitely below 2.0

static holly
#

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?

slate swan
#

kanna_what bot definition?

static holly
inland venture
#

-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
naive briar
static holly
slate swan
#

and do you have message_content intents?

static holly
static holly
slate swan
#

that's not related to message_content

#

!intents

unkempt canyonBOT
#

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.

slate swan
#

im talking about this thing

static holly
#

@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()
static holly
slate swan
#

you cant use prefix commands without that

static holly
#

i have imported all intent... scuze me

naive briar
#

But did you use it?

#

And I don't see process commands in that code

static holly
#
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")
naive briar
#

I said what I said

slate swan
#

!paste it's hard to guess

unkempt canyonBOT
#

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.

static holly
slate swan
#

change the .event decorator on on_message to .listen()

clear elm
#

does a field in an embed have to have a name and value?

slate swan
#

yes.

#

if you want an empty one there's a workaround

#

just use \u200b as the value/name

clear elm
#

is there a way to remove the big space?

smoky sinew
#

why are you using fields anyways

#

just make a bold description

clear elm
#

thats not the title and description

#

there's more

slate swan
#

yeah you could just use the Description

#

why use fields here

clear elm
slate swan
#

yes

clear elm
#

how?

slate swan
#

!e ```py
print("""
some big line you have below the title
Username:
Department:
Invited by:
""")

unkempt canyonBOT
#

@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:
clear elm
#

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)```
smoky sinew
#

triple quotes """

naive briar
#

No

clear elm
#

thanks

smoky sinew
#

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"
static holly
slate swan
#

GuraSpeen np

clear elm
#
@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'```
smoky sinew
#

what

clear elm
#

oop

#

ive used it before and it worked

#

anyways, i removed it but it still doesn't work

smoky sinew
#

show me the error

smoky sinew
clear elm
smoky sinew
#

do you have your members intent enabled?

clear elm
#

yes

smoky sinew
#

then i don't know

clear elm
#

is it something in my code?

smoky sinew
#

add a print statement maybe

clear elm
#

i removed seomthing from my code and it worked

smoky sinew
#

ok

clear elm
#

but i want the part that i deleted

smoky sinew
#

i'm not sure

clear elm
#

wait are classes and cogs the same thing/

#

!paste

unkempt canyonBOT
#

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.

clear elm
#

thats the part i cut out for the event to work

ionic garden
#

what's the difference between brief and description

smoky sinew
#

extensions are the files

clear elm
#

ohh

smoky sinew
#

brief is the short version, help is the long one though

#

as for description idk

clear elm
smoky sinew
#

what did you actually remove

clear elm
smoky sinew
#

so you removed your bot variable too

clear elm
#

??

#

oh wait

#

i dont even know why thats there

#

i have that earlier in the code

smoky sinew
#

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

clear elm
#

thank you

tired notch
#

will i have to worry about performance if i put something heavy in @tasks.loop()?

slate swan
#

yes

tired notch
#

🥹

chilly dove
#

if its something async then it will be fine

clear elm
#
@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?
tired notch
#

i believe you can use delete_after if you want to delete a message after a set amount of time

clear elm
smoky sinew
#

are you using nextcord? @slate swan

#

nvm

flat pier
#

!d discord.abc.Messageable.send

unkempt canyonBOT
#
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**.
flat pier
#

there's a delete_after kwarg in send

tired notch
#

i believe its await channel.send(your message, delete_after=3)

flat pier
#

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

tired notch
#

it doesnt take a png it takes a url so you can do embed.set_thumbnail(url=ctx.message.author.avatar)

flat pier
#

!d discord.Asset.replace

unkempt canyonBOT
#

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`.
clear elm
#
@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

flat pier
#

it goes for any user really (as long as you that data)

#

ctx.author or the user that was passsed in the member arg

chilly dove
clear elm
#

how do i do that

flat pier
# unkempt canyon

i sent the docs here, it tells you what the delete_after kwarg takes & does

#

are you still using it in your else block

tired notch
#

its just .avatar not avatar_url_as

chilly dove
flat pier
#

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

tired notch
flat pier
#

avoids the whole "user.avatar is None"

tired notch
#

how is it possible to have no avatar? just the default?

flat pier
#

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)

tired notch
#

ah ok thanks 👍

flat pier
#

!d discord.abc.User.display_avatar

unkempt canyonBOT
#

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.
spiral crypt
#

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

naive briar
#

!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())
unkempt canyonBOT
#

@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
naive briar
#

Don't exactly sure if that's what you mean

spiral crypt
#

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:?

clear elm
#
@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
spiral crypt
slate swan
unkempt canyonBOT
#

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.
shrewd fjord
#

here is a delete_after kwarg

shrewd fjord
shrewd fjord
#

!d discord.TextChannel.send

unkempt canyonBOT
#
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**.
shrewd fjord
shrewd fjord
#

Btw always check docs

slate swan
#

yes

clear elm
#

how do i make a sleect menu disable after like 30 seconds?

shrewd fjord
#

Need to use slee

#

Sleep* then disable it

#

.disabled=True

clear elm
shrewd fjord
#

U need to edit the msg anyway and put view=self

clear elm
#

!paste

unkempt canyonBOT
#

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.

naive briar
shrewd fjord
#

Oh

#

Then u can use
async def on_timeout(...)

#

Then disable the select

clear elm
#

what should go in (...)

smoky sinew
#

hello

sturdy shadow
#

hey

#

I suppose it's not really that needed tbf

smoky sinew
#

it'd be better if you explained what your end goal is

sturdy shadow
#

Well the end goal is where it gives me a different response for the accessories I'm using

smoky sinew
#

so it should just list all the accessories you selected?

sturdy shadow
#

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

deep osprey
#

How can I send a private message to the user using slash commands?

sturdy shadow
#

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

smoky sinew
slate swan
deep osprey
slate swan
#

what mudkip said

slate swan
#

but make sure you respond to the interaction too

clear elm
slate swan
inland venture
smoky sinew
#

me when i replace self with this and start adding semicolons to my code

inland venture
#

intents.message_content = True
AttributeError: 'Intents' object has no attribute 'message_content'

inland venture
#

???

naive briar
#

Outdated lib

smoky sinew
inland venture
smoky sinew
inland venture
smoky sinew
#

so you didn't update

inland venture
#

i attempted to upgrade my version, yet i didnt get an update

smoky sinew
#

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

inland venture
#

thank u

#

now i got a new issue

#

client = discord.Client()
TypeError: init() missing 1 required keyword-only argument: 'intents'

slate swan
#

!intents

unkempt canyonBOT
#

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.

deep osprey
#

is it able to make the bot send a message to a specified channel by its ID or name?

naive briar
#

!d discord.Client.get_channel

unkempt canyonBOT
#

get_channel(id, /)```
Returns a channel or thread with the given ID.

Changed in version 2.0: `id` parameter is now positional-only.
sturdy shadow
#

That's a stupid question, for some reason I thought if I had too many people doing it

#

It would affect it lol

clear elm
spiral crypt
#

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.

naive briar
#

Send full traceback

#

And it seems like you didn't await a coroutine

spiral crypt
#

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

smoky sinew
#

show your code

spiral crypt
#
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.")
naive briar
#

check cannot be async

#

And you don't need it anyway

spiral crypt
#

dont need check or?

#

just the async

naive briar
#

Don't need to be async

spiral crypt
#

gotcha

clear elm
#
    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?
slate swan
#

no

deep osprey
#

is it able to make the bot send a message to a specified channel by its ID or name by slash command?

ionic garden
#

so when should i use brief vs. description

smoky sinew
ionic garden
#

lmao alr

#

why tho

slate swan
shrewd fjord
#

Hm pithink

clear elm
#

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)```
naive briar
#

It's the message's object representative string

#

It's simple Python

clear elm
#

how can i make it say the message rather than saying all of that

naive briar
#

Say the what

#

Which part of the message, be specific

clear elm
#

the deleted message

naive briar
#

And which part of it??

clear elm
#

the text

naive briar
#

Then get the content out of it

clear elm
#

how

naive briar
#

!d discord.Message.content

unkempt canyonBOT
naive briar
#

It's called reading the docs

lofty aurora
#

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

naive briar
#

Why don't just use Discord's built-in

lofty aurora
slate swan
#

What are we taking about

#

I could be of some help

lofty aurora
slate swan
#

Can you explain further

naive briar
lofty aurora
slate swan
#

So you want to search for messages on discord with your discord bot?

slate swan
#

That could be challenging

#

Especially if you have many messages on the server

#

Even the discord search sometimes breaks

lofty aurora
slate swan
#

Now imagine putting that type of technology into a bot

lofty aurora
lofty aurora
dapper citrus
#

hi

slate swan
#

Hm

#

What language are you building the bot on?

lofty aurora
lofty aurora
naive briar
#

JSON is a language? ducky_sus

slate swan
#

Eek

#

Try js instead

#

Python is already too slow

naive briar
#

And you will risk rate limit doing it

slate swan
#

^

lofty aurora
lofty aurora
slate swan
#

In js, you could easily do channel.messages.fetch

#

Only works for the channel it runs on though

lofty aurora
slate swan
#

Not the entire server

#

There's also a limit

#

For example: channel.messages.fetch({ limit: 10})

lofty aurora
#

Alr listening!

slate swan
#

Set 10 to the limit

#

100, 1000, etc

#

I think that's how it works. Not very sure though

naive briar
unkempt canyonBOT
#

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...
lofty aurora
slate swan
#

10 is not the limit

#

Depends on you

#

Just set it to an appropriate amount

lofty aurora
slate swan
#

Then, you'd do something like messages.filter with the inputted keyword

smoky sinew
#

is there a decorator for text input??

#

@slate swan

lofty aurora
slate swan
#

Quick question

#

How old are you people?

lofty aurora
slate swan
#

Damn

#

you can add the textinputs as classvars tho

lofty aurora
#

I feel like other people might be more older than me lol

#

Oh

#

Damn you know a lot about this haha @/shiv_uwu#2651

slate swan
#

Do you have them installed

#

pip install [module name]

#

add an init.py in the modules folder

naive briar
#

Create a file named __init__.py in that module

slate swan
#

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

#

.

shrewd fjord
#

Same directory

naive briar
#

Yes

slate swan
shrewd fjord
#

modules/init.py

slate swan
#

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...

▶ Play video
shrewd fjord
#

Nothing

slate swan
#

🙏

shrewd fjord
#

Blank

slate swan
#

yea

#

It seems as though most people lack basic python skills

smoky sinew
# slate swan from what i know there's none

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).
shrewd fjord
#

Yeah fine

smoky sinew
shrewd fjord
#

...

naive briar
slate swan
#

👍

lofty aurora
slate swan
#

Proudly made by people in my country

shrewd fjord
#

!resource

slate swan
shrewd fjord
#

!resources

unkempt canyonBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

shrewd fjord
lofty aurora
slate swan
smoky sinew
slate swan
shrewd fjord
#

Bro 👀

young lintel
#

hi! does anyone knows how to make commands that disables and enables the whole entire bot

shrewd fjord
#

Going to say that

smoky sinew
young lintel
lofty aurora
shrewd fjord
#

....

young lintel
#

ah alr tysm

slate swan
# smoky sinew did not know that

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

naive briar
slate swan
shrewd fjord
#

Well if he shut it down, then he cant run / on it from commands anyway

#

My wifi is trippin

slate swan
#

I swear these language barriers

shrewd fjord
#

Tho i can disable them

slate swan
shrewd fjord
#

You*

lofty aurora
slate swan
#

the restart system is completely absurd

slate swan
shrewd fjord
#

Bro wut skullcap

#

!d discord.TextInput

unkempt canyonBOT
#

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.
lofty aurora
slate swan
#

UwU

shrewd fjord
#

How still it's going to work kek

slate swan
unkempt canyonBOT
#

@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")
slate swan
#

Fudge wrong channel

#

this is a check that you can use

shrewd fjord
slate swan
#

@lofty aurora Who's that on your pfp

lofty aurora
lofty aurora
slate swan
#

.

slate swan
slate swan
#

i'll get away before the chat goes offtopic

lofty aurora
#

I think her name is haerin @/shiv_uwu#2651 ...she does music!

shrewd fjord
slate swan
#

No fudging way

#

I knew it

lofty aurora
shrewd fjord
#

freaking*?

slate swan
#

fudging

#

hush

shrewd fjord
#

Freaking seems gud kek

#

Imma leave too with sarth PU_PeepoLeaveExit

slate swan
#

You listen to kpop? @lofty aurora

#

spooky i wanna test a ban command, want to be my subject?

lofty aurora
slate swan
lofty aurora
#

Others are cringe

slate swan
#

i stan newjeans ongong

#

BTS is good

shrewd fjord
lofty aurora
shrewd fjord
#

Anything which is "interactable" will work tho this word doesnt exist kek

lofty aurora
slate swan
#

Blackpink mid tbh

#

Their music makes no sense

lofty aurora
slate swan
#

Pretty hype though

lofty aurora
shrewd fjord
lofty aurora
slate swan
shrewd fjord
#

Off topic pls kek

slate swan
#

Yesyes

#

No offtopic

shrewd fjord
#

Bro slash command work

#

Works*

lofty aurora
#

Adios

shrewd fjord
#

....wutt

slate swan
shrewd fjord
#

Lemme quickly turn my bot on and whoop yo ass

shrewd fjord
#

Oh nvm

slate swan
shrewd fjord
#

I thought :-:

#

He is using module kek

#

Mah bad kek

slate swan
#

@smoky sinew it works for slash too apparently^

smoky sinew
#

i just rewrote the code smhhhhhhh

#

are u serious

slate swan
#

thi yea~

smoky sinew
#

well fuck

#

i don't know what to believe anymore

slate swan
smoky sinew
#

the hardest part of being a discord bot developer is knowing how to spell ephemeral

slate swan
#

bwaahahaha ive almost always spelled it empheral

#

only before i started writing my own wrapper

smoky sinew
#

e-phem-e-ral

shrewd fjord
#

Eh-phe-me-ral

#

Ez kek

slate swan
#

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

slate swan
#

only on mobile ™️

naive briar
#

I guess it's probably not supported for all platform yet

slate swan
#

never worked when i tried it

slate swan
#

because you're storing deleted user data, potentially without the user's knowledge or consent, all i'm saying is to be careful

inland venture
#

client = discord.Client()
TypeError: init() missing 1 required keyword-only argument: 'intents'

#

???

smoky sinew
#

actually its a 1.5 feature

#

you need to pass intents to your bot now

pastel basin
#

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)
zinc pollen
#

@smoky sinew I tried what you told me in DM and it came up with all kinda errors lol

unkempt canyonBOT
#

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`.
slate swan
#

attachments kwarg

pastel basin
pastel basin
#

file = discord.File("boom.png", filename="image.png")

slate swan
#

attachments=[file]

pastel basin
#

i just read the docs, so its a list..

#

thanks

zinc pollen
#

Ill worry about it tomorrow. thank you for all your help so far!

clear elm
#
@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
flat pier
#

You need to use the app_commands.checks version of it

#

!d discord.app_commands.checks.has_any_role

unkempt canyonBOT
#

@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.
clear elm
flat pier
# clear elm 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)

clear elm
#

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?
novel apexBOT
#

This is not a Modmail thread.

clear elm
#

...

clear elm
#

i did

#

no errors though

upbeat gust
#

Okay

clear elm
#

so..?

upbeat gust
#

So what? You tried it and got no errors

clear elm
#

yeah

upbeat gust
#

Great

clear elm
#

but it didn't send the embed

upbeat gust
#

Have you tried putting a print before sending the embed to see if it's getting called?

clear elm
#

yes

#

nothing prints

clear elm
#

@upbeat gust

shrewd apex
#

possible that the error is not what u handled in the if case

clear elm
#

else: ??

shrewd apex
#

raise error

#

send an embed if u want to as well

timid spade
#

how can i make a selection restricted to only a specific role or users

naive briar
#

Selection of what

shrewd apex
#

another way would be to make a secondary select and send an ephemeral response

clear elm
shrewd apex
#

in the callback if user meets requirements

clear elm
#

else if:
raise error?

#

or just else:

naive briar
#

Do you know Python syntax in general

timid spade
naive briar
#

!d discord.ui.View.interaction_check

unkempt canyonBOT
#

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.
naive briar
#

Override this meth

shrewd apex
#

^^ works both ways

timid spade
#

okay thanks

#

we can only use ephemeral in interaction response? eh

#
await ctx.reply("Text", ephemeral= True)
#

its not working

strong knoll
#

How to get like in slash commands author of message?

shrewd apex
unkempt canyonBOT
minor viper
#

u can test again here

shrewd apex
#

enable intents in dev portal

inland venture
#

tysm

shrewd fjord
#

Anyone here xd?

#

In which line u getting this error?

#

!e
print("some str".message)

unkempt canyonBOT
#

@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'
shrewd fjord
#

See?, This is how the error occurs

#

Hm think

#

pithink *

#

Mind checking the docs xd

#

!d discord.ext.commands.Context.message

unkempt canyonBOT
#

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.

shrewd fjord
#

!d discord.Message.created_at

unkempt canyonBOT
shrewd fjord
#

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

vernal hollow
#

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

shrewd fjord
#

!d discord.InteractionResponse.edit_message

unkempt canyonBOT
#

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.
vernal hollow
shrewd fjord
#

I am not sure tho-

#

@slate swan

#

Lemme check the docs for ga

vernal hollow
#

thx

shrewd fjord
vernal hollow
#

alr i will try it, thx

shrewd fjord
#

But it's going to be list
attachments=[discord.File(...)]

vernal hollow
#

okay

#

its working! thanks again

shrewd fjord
#

Np

slate swan
#

how to do this ?

naive umbra
# slate swan

if your bot has global slash commands then it will automatically be shown afaik

slate swan
#

its not smthg like <#commandid> ?

naive umbra
#

no

naive briar
#

</meow:0>

slate swan
naive briar
naive umbra
# slate swan

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

vale wing
# slate swan

They are added automatically as users use your slash commands

lofty aurora
#
@commands.guild_only()
async def balance(ctx):
    user = ctx.author
  await open_bank(user)```
lofty aurora
#

can someone help?

naive briar
#

Are you familiar with Python

deep osprey
#

is there a tutorial for hosting on VPS?

thin raft
#

upload files

deep osprey
#

and?

thin raft
#

wdym and

lofty aurora
#

they teach very basic commands though

thin raft
#

I would recommend being familiar with python and then hop into discord.py

lofty aurora
thin raft
slate swan
thin raft
#

💀

thin raft
#

just practice a lot

lofty aurora
#

probably will start with the basics then

slate swan