#discord-bots

1 messages · Page 233 of 1

vocal snow
#

Async

fading linden
#

i should move to that then

vocal snow
#

!d aiohttp

unkempt canyonBOT
#

Common data structures used by aiohttp internally...

fading linden
#

im just wonderign why

fading linden
#

also you're on the spot
magician

vale wing
#

Is it paid

fading linden
vale wing
#

To upgrade to VPS

#

Hosting services are aids

fading linden
#

at least i can transfer it to a less congested line

fading linden
vale wing
fading linden
vale wing
fading linden
vale wing
fading linden
#

team's there pretty quick to answer to my concerns so thats also a plus

#

i was more concerned that my code is probably doing some unnecessary stuff, since im also not a pro coder/coder by trade

#

im just fascinated that i can do things conveniently from my phone

gleaming marsh
#

Can you use a non bot discord account to upload files as well?

vocal snow
#

what do you mean by that?

#

that button lets you upload files

gleaming marsh
#

I have been able to use a bot to send files in a server but was wondering if i can do it without a discord bot

vocal snow
#

you could use a webhook

gleaming marsh
#

I send memes to my friend via dms and sometimes it is a lot 😅 so i wanted to automate it

vocal snow
#

that isn't possible

gleaming marsh
#

what about in a server

vocal snow
#

you could use a webhook in a server

gleaming marsh
#

where can i learn that?

gleaming marsh
#

alright!

vocal snow
#

you can create a webhook by going to a text channel's settings -> Integrations

#

you can also do that with a bot, but that would defeat the purpose i suppose

gleaming marsh
#

Yeah thanks zeffo!

sacred plume
#

I'm trying to count online, idle and dnd members. Any ideas why the lists are blank ?

@loop(seconds=statscooldownamount)
async def checkonlinemembers():
    try:
        guild = bot.get_guild(guildID)
        online_members = []
        idle_members = []
        dnd_members = []
        for member in guild.members:
            if member.status == discord.Status.online:
                online_members.append(member)
            elif member.status == discord.Status.idle:
                idle_members.append(member)
            elif member.status == discord.Status.dnd:
                dnd_members.append(member)
        
        print(online_members)
        print(idle_members)
        print(dnd_members)
#

all lists

stray mural
sacred plume
#

thanks!

stray mural
#

np

sinful thistle
#

guys

#

wassup

#

client + regex > bot

thin trout
#

i want to create a slash command but i can't import app_commands from discord, can someone help me?

vale wing
#
TypeError: Unsupported operand type(s) +: 'discord.Client' and 're.Pattern'```
#

How to solv

vale wing
thin trout
vale wing
outer viper
#

Hi im currently developing a discord bot but i get into a problem, is there anyone who have a little experince with it?

thin trout
vale wing
thin trout
vale wing
#

Okay seems correct, maybe venv issue

#

What interpreter do you have configured in vscode

outer viper
# vale wing What the problem is

ohm so i tried to check on my other python file on my on_message function if it is an actual bot and its id is =123456 etc and apparently doesnt rlly want work

outer viper
#

so everytime my first bot sends a message onto my channel i want the second bot in dif file reply to that message with anything like a "hi" message

vale wing
#

Assuming msg is your parsed Message

hazy vault
#

Guys I'm trying to install discord_components library in REPLIT but for some reason I can't

vale wing
# thin trout python

Could you do ctrl + shift + p -> Python: Select Interpreter and show the list to me

outer viper
vale wing
#

The list from there

hazy vault
vale wing
hazy vault
#

HOW

vale wing
#

Is your shift broken

thin trout
vale wing
# hazy vault HOW

Open up that terminal or command line whatever it's called in replit and do poetry add discord.py

outer viper
#

so this is how my on_message function look like:

bot1 = commands.Bot(command_prefix=':', intents=intents)

@bot1.event
async def on_message(message):
if message.author == bot1.user:
return

#1092844660235440309

if (message.author.id == "393841441656406026" or message.author.id == "1092844660235440309") and (message.author != bot1.user):
    print("Other bot sent a message!")
    await message.channel.send('Igaz ag a norman ideju nem bela user kuldte az uzit')
else:
    await message.channel.send('Hi hamis ag')

await bot1.process_commands(message)

but everytime i type anything on channel it goes the else branch (thats normal) but when i make the other file's bot to write onto my channel sth it still goes there (but i want to go the true branc that time)

vale wing
#

But you seem to have python installed

#

Is python extension enabled

#

Oh heck there are now headers in discrod???

thin trout
#

yes

vale wing
#

Bro this is wild

hazy vault
vale wing
outer viper
#

?

thin trout
outer viper
#

@vale wing do you know the problem?

hazy vault
outer viper
#

no

hazy vault
#

K SORRY

vale wing
outer viper
#

yes i did this

#

apperently the mistake i have made is that i tried to find the other's bot id (i wrote it by the bot then i copied from my discord server) both were different from each other

#

and apparently i guess not even one of them was correct so it was a bit of riculous now im trying with the name attribute

#

well i have no clue how to get the discord bots id (i thought i could ) but well with name it work

solar coyote
#
class Prot(discord.ui.View):
    response1=None
    list_result=[]
    def __init__(self, users:list):
        super().__init__(timeout=10)
        self.users1=users
        

    @discord.ui.select(
        max_values=1,
        placeholder="Choose your action",
        options=[
            
        ]
    )
    
    async def selected(self, interaction:discord.Interaction, selected:discord.ui.Select):
    

    async def on_timeout(self): 
        self.disabled = True
        await self.message.edit(view=self)
        print("TIMEDOUT")
#

self object has on attribute message

#

how to fix

steel loom
#

Can you use RPC for bots?

small crag
#

how would i go about turning hours & minutes into unix as well?

@client.command()
async def timetest(ctx, *, message):

  s = message
  f = time.mktime(datetime.datetime.strptime(s, "%d/%m/%Y").timetuple())
  d = round(int(f))
  await ctx.send(f"<t:{d}>")```
this code turns d/m/y into a timestamp but you cannot specify the exact time in hours & minutes
old ibex
#

What do you mean by that?

small crag
#

so i can tell it a date

#

in dmy format

#

but i cant tell it an exact time either (hours & minutes)

#

so like lets say 4/29/23 18:00

#

it wouldnt take the last part of the input (18:00)

silent ermine
sterile terrace
#

anyone know how to add paywall to a discord bot (crypto only)

smoky sinew
smoky sinew
sterile terrace
smoky sinew
#

what do you mean by 'how so'

sterile terrace
uneven imp
#

Gotta serious question about discord bots in python

sterile terrace
uneven imp
#

How do I make them

sterile terrace
#

i’m using a whole different wrapper

smoky sinew
#

is it hikari you're using

sterile terrace
#

but i’m just looking for recommendations for adding a paywall to it

#

preferably crypto

smoky sinew
#

how is that related to discord bots

sterile terrace
#

because i’m wanting to add it to my bot

smoky sinew
#

that doesn't make it related

#

i don't know anything about crypto

#

and implementation varies widely on the crypto you're using

gusty flax
#

R u asking the way to incorporate it with the layout of sending that. Or what to use.

sullen shoal
# uneven imp How do I make them

discord api is all about the websocket protocol, and ratelimits for which you could work around by exponential backoffs and stuff, but wrappers like discordpy, hikari, handles all that for you, so just learn Python, visit their maintained git repo, see the examples, and see what each of their those methods do in the documentation of the wrapper

teal swan
#

Hay guys, can someone tell my why its gray?, i cant use it in PyCharm

sullen shoal
#

why do you need that obscure module at all?

#

there's no need for monkey patching anymore, Danny had decided to take back his decisions and implement the newer API versions of Discord API in Discord.py module

teal swan
sullen shoal
teal swan
#

nah i following chatgpt xD

sullen shoal
#

chatgpt's dataset is limited to 2021, a lot has changed since then

teal swan
#

i see xD

sullen shoal
#

if you want to build a decent discord bot and not waste your time for very basic one that nobody anymore really cares about, you'll need to know what you're doing, so go through http://docs.python.org/tutorial
once that's done, see the docs of the discordpy module

teal swan
#

thx ❤️

#

but one question i have.. how can i do commands from main to commands class.. if i start it dont works

teal swan
tropic sable
#

how do i download the discord client again

vocal snow
tropic sable
#

yea

#

discord py

whole shoal
#

How do I disable a select menu on timeout

solar coyote
#

await interaction.response.send_modal(NumberChoice()) TypeError: __init__() should return None, not 'coroutine'

#
class NumberChoice(discord.ui.Modal, title="Select the number"):
    async def __init__(self):
        self.result_list=[]
        super().__init__(timeout=30, custom_id="select_num")
    number=discord.ui.TextInput(label="Enter your Number")

    async def on_submit(self, interaction: Interaction, modals:discord.ui.Modal):
        self.result_list.append([interaction.user,modals.value[0]])
        await interaction.response.send_message(f"{interaction.user} chose the number {modals.value[0]}")
        print(self.result_list)
        
    
class ChooseBut(discord.ui.View):
    def __init__(self,ctx):
        super().__init__(timeout=30)   #select modal input timeout
        self.value=None
        self.ctx=ctx
    
    @discord.ui.button(label="click to Choose!", style=discord.ButtonStyle.green, custom_id="join1")
    async def menu1(self, interaction:discord.Interaction, button:Button):
        await interaction.response.send_modal(NumberChoice())
solar coyote
#

oh

#

alright worked thanks

#

also how do i fetch the answer of the modal

slate swan
solar coyote
#

thanks

solar coyote
slate swan
#

the value of name field

solar coyote
#

oh ok

slate swan
smoky sinew
slate swan
#

okay i'm learning the embed thing

#

i don't know how i will make it

sick birch
unkempt canyonBOT
#

class discord.Embed(*, colour=None, color=None, title=None, type='rich', url=None, description=None, timestamp=None)```
Represents a Discord embed.

len(x) Returns the total size of the embed. Useful for checking if it’s within the 6000 character limit.

bool(b) Returns whether the embed has any data set.

New in version 2.0.

x == y Checks if two embeds are equal.

New in version 2.0...
slate swan
#

i'm planning to make it able to create it's own command for generating it's own embed

#

my plan is to allow people to create their own character template

#

but it being a thing only available for admins

#

settled for just a role

slate swan
#

the only thing to be inferred by that

junior falcon
#

Hey there guys, i have 2 files main.py and colors.py. In the second i have a function that contains a dictionary and returns it unpacked. So in the first file i import this function and i want to use it for format a string. But i get a KeyError

This is my code:

# colors.py

class TerminalColors:
    header = '\033[95m'
    purple = '\033[0;35m'
    blue = '\033[94m'
    cyan = '\033[96m'
    green = '\033[92m'
    red = '\033[91m'
    orange = '\033[93m'
    yellow = '\033[0;33m'
    bold = '\033[1m'
    underline = '\033[4m'
    end = '\033[0m'


def get_colorsformat():
    color_vars = {
        'header': f'{TerminalColors.header}',
        'purple': f'{TerminalColors.purple}',
        'blue': f'{TerminalColors.blue}',
        'cyan': f'{TerminalColors.cyan}',
        'green': f'{TerminalColors.green}',
        'red': f'{TerminalColors.red}',
        'orange': f'{TerminalColors.orange}',
        'yellow': f'{TerminalColors.yellow}',
        'bold': f'{TerminalColors.bold}',
        'underline': f'{TerminalColors.underline}',
        'end': f'{TerminalColors.end}',
        'TIME': f'{datetime.now().strftime("%H:%M:%S")}',
    }

    return {**color_vars}

And my other code

# main.py

print(log.format(get_colorsformat(), USERNAME=f"{interaction.user.name}",
                             CHANNEL_NAME=f"{interaction.channel}"))
sinful thistle
slate swan
#
TypeError: View.__init__() takes 1 positional argument but 2 were given
#

pls tell me the fix of this error

grave gyro
slate swan
#

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

slate swan
#

kk

#

@slate swan

#

why dont you subclass View it will be 3 times easier to mantain

naive briar
#

!d nextcord.ui.View

unkempt canyonBOT
#

class nextcord.ui.View(*, timeout=180.0, auto_defer=True)```
Represents a UI view.

This object must be inherited to create a UI within Discord.

New in version 2.0.
naive briar
#

Pretty this is not how you create views

view = nextcord.ui.View(dropdown, prev_button, next_button)
slate swan
plucky sun
slate swan
slate swan
naive briar
#

Yes? That's most likely where the previous error came from

slate swan
plucky sun
#

how to make the command written by a bot delete after 5 sec?

#

@slate swan

slate swan
#

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

there is delete_after argument you can specify

#
delete_after (float) – If provided, the number of seconds to wait in the background before deleting the message we just sent. If the deletion fails, then it is silently ignored.
plucky sun
#

where to put it?

        error1 = "Липсва таг на човека, който искате да забраните !"
        fix1 = "`!ban @(таг на човека) (Причината за забраната)`"
        emb1 = discord.Embed(title='! ‖ ERROR ‖ !',colour=discord.Colour.dark_red())
        emb1.set_author(name="")
        emb1.add_field(name="", value=f"═════════════════\n**Таг:** {author}\n**Грешка:** {error1}\n**Поправка:** {fix1}\n**Причина:** {reason}\n═════════════════")
        await ctx.send(embed=emb1)
        await asyncio.sleep(3)
        await ctx.message.delete()```
slate swan
#

i dont know which message you want to delete

#

when you use .send you specify delete_after argument

plucky sun
#

what the bot sends

slate swan
#

thats argument not a function do you know what argument is?

plucky sun
#

@slate swan

slate swan
#

guys, how do i gather user ID using my cog?

#

i'm planning to cryptograph that ID

#

so hackers won't use that ID to do whatever they want with that person

#

and also only the system knows the ID of that user and i won't be able to know it since it's cryptographed

unkempt canyonBOT
#

property id```
Equivalent to [`User.id`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.id "discord.User.id")
young pendant
#

Basicly you rightclick on a message, Click on "Apps" and select the "Report" command, could you maybe help me?

I got a script right here but its not working as its supposed to so```


https://paste.pythondiscord.com/utunojunox
slate swan
young pendant
#

so, what should I use then?

slate swan
#

here are examples

#

if you want to do Report command available under Apps section when clicking on a message you should use client.tree.context_menu

#

and it even does what you need

slate swan
formal basin
#

Can someone help me?

formal basin
#

No error

cold sonnet
#

a reminder that programming discord bots can indeed be useful in your future

#

my reminder is just gonna be the sample code of a running twitch chat bot

#

I got intensely happy when I saw this

formal basin
cold sonnet
#

await channel.send(embed=embed)

#

what you did is just
await channel.send(embed)

young pendant
cold sonnet
formal basin
#

But embed=embed didn’t work

cold sonnet
#

how come

#

I just don't believe you

formal basin
cold sonnet
#

embed= not embedlog=

formal basin
#

But I named it embedlog

cold sonnet
#

you don't know what keyword arguments are do you

formal basin
#

Oh I see

cold sonnet
#

nice

slate swan
#

Any good guides for making a Discord bot that utilises slash commands and embeds? Ideally text but I don't mind a video

slate swan
short silo
#

is there any way to send images with nsfw tag with url in an embed ?

short silo
#

@smoky sinew

#

Sorry for the ping but it's just so you know it's here but it's kinda urgent aniblobsweat, so whenever you have time lemme know.

smoky sinew
#

e.g. SPOILER_image.png

#

as for the URL part, i'm not sure

short silo
short silo
#

I will just go the long way

#

Thanks for the input

short silo
# smoky sinew i'm pretty sure spoilered images just prepend spoiler to the file name

dont mind the code if its broken i have removed irrelevant parts,

url = "https://www.achaheart.org/media/1836/asd-illustration.jpg?mode=max&upscale=false&width=950"
        end = 'jpg'
        async with aiohttp.ClientSession() as session:
            async with session.get(url) as resp:
                img = await resp.read()
                with io.BytesIO(img) as file:
                    file = discord.File(file, filename=f"SPOILER_Imagination.{end}")
        embed.set_image(url=f"attachment://SPOILER_Imagination.{end}")
        await ctx.followup.send(embed=embed,file=file)

#

so the file name is SPOILER_Imagination.jpg in this particular case, and in an embed, it doesnt work, although i havent tried without embed either

smoky sinew
#

idk what doesn't work means

short silo
#

so that the image is hidden

#

thats for text

smoky sinew
#
async with bot.http_session.get(IMAGE_URL) as response:
    with io.BytesIO(await response.read()) as data:
        file = discord.File(data, filename="SPOILER_test.jpeg")
        await ctx.send(file=file)
#

this worked for me

smoky sinew
#

what you're doing won't work because SPOILER_Imagination isn't saved locally

#

i don't know if there's a way to set an embed image to a BytesIO object but i will check

#

actually wait

#

ah wait you don't need to do that

short silo
smoky sinew
#

sorry i have no clue how to work with discord files

short silo
smoky sinew
#

i wouldn't merge tkinter and discord.py code if i were you but you can't use while True with a running event loop

smoky sinew
#

well you're not doing anything as of right now

#

the function is not even being called anywhere

#

then i'm not sure

#

like i said i don't think tkinter will work or work well with a running discord bot

naive briar
#

!e

import asyncio


async def while_task(id: int) -> None:
    while True:
        print(id)
        await asyncio.sleep(0)

async def main():
    task_1 = asyncio.create_task(while_task(1))
    task_2 = asyncio.create_task(while_task(2))

    await task_1
    await task_2

asyncio.run(main())
unkempt canyonBOT
#

@naive briar :x: Your 3.11 eval job has completed with return code 143 (SIGTERM).

001 | 1
002 | 2
003 | 1
004 | 2
005 | 1
006 | 2
007 | 1
008 | 2
009 | 1
010 | 2
011 | 1
... (truncated - too many lines)

Full output: too long to upload

next zephyr
#

!d discord.Member.discriminator

unkempt canyonBOT
#

property discriminator```
Equivalent to [`User.discriminator`](https://discordpy.readthedocs.io/en/latest/api.html#discord.User.discriminator "discord.User.discriminator")
smoky sinew
slate swan
#

hey guys, im trying to get entries on a table with aiosqlite and its returning empty messages,

            """Appends the avatar url from the database table by joining them together."""
            fetch = []
            async with self.bot.database.cursor() as db:
                await db.execute(f'SELECT * FROM uwu WHERE Member = {member.id}')
                check = await db.fetchall()
            if check is not None:
                for u in check:
                    fetch.append(f'hi testing {u[1]}\n')
            return ''.join(fetch)
        except Exception as e:
            return e```

i checked the data in the table and they are all there, not sure what to do
#

@smoky sinew do you know how to solve this issue?

smoky sinew
#

!sql-fstrings also look at this

unkempt canyonBOT
#
SQL & f-strings

Don't use f-strings (f"") or other forms of "string interpolation" (%, +, .format) to inject data into a SQL query. It is an endless source of bugs and syntax errors. Additionally, in user-facing applications, it presents a major security risk via SQL injection.

Your database library should support "query parameters". A query parameter is a placeholder that you put in the SQL query. When the query is executed, you provide data to the database library, and the library inserts the data into the query for you, safely.

For example, the sqlite3 package supports using ? as a placeholder:

query = "SELECT * FROM stocks WHERE symbol = ?;"
params = ("RHAT",)
db.execute(query, params)

Note: Different database libraries support different placeholder styles, e.g. %s and $1. Consult your library's documentation for details.

See Also
Python sqlite3 docs - How to use placeholders to bind values in SQL queries
PEP-249 - A specification of how database libraries in Python should work

smoky sinew
#

and check if the case is correct because your database may or may not be case sensitive

sullen shoal
#

My discord is all about esports tournaments, managed entirely through discord. I want my bot's tournament timer to work even after bot restarts, so I am saving unix time of the specified start time of the tournament to my database of-course. My plan was to have some asyncio tasks on bot startup, and on adding a new tournament, that'd do asyncio.sleep until the current time is the unix timestamp that is in my database. However, I think I'd need something more efficient this time, as I'd also like to offer them the feature to cancel/stop/remove a tournament. Any idea?

#

okay, I think I am just looking for asyncio.Task.cancel lol

summer jacinth
#

hello

vale wing
unkempt canyonBOT
#

@discord.ext.tasks.loop(*, seconds=..., minutes=..., hours=..., time=..., count=None, reconnect=True)```
A decorator that schedules a task in the background for you with optional reconnect logic. The decorator returns a [`Loop`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop "discord.ext.tasks.Loop").
vale wing
#

If you're doing background tasks in dpy it's best method in most cases

sullen shoal
#

yeah, I could probably workaround with tasks.Loop class as well, however, it is more geared towards background loops rather than tasks, so it can get restrictive

#

like doing count=1

vale wing
#

If you don't need ws connection ie receiving events you can just use requests module and simply do requests to discord API from your tkinter app

#

Would want to use executor tho

tired kernel
#

Good Sleeky — Oggi alle 11:39
why this dosent works (i used the command and nt happens)
import discord
from discord.ext import commands
import json

with open("Globalvariables.json") as f:
Variables = json.load(f)
adminrole = int(Variables["Admin"])

with open("Warns.json") as w:
Warndata = json.load(w)

class Warncog(commands.Cog):
def init(self, bot):
self.bot = bot

@commands.has_role(adminrole)
@commands.command()
async def warn(self, ctx, user, Reason):
    if user in Warndata:
        Warndata[f"{user}"].append(Reason)
    else:
        Warndata.setdefault(f"{user}", [])
        Warndata[f"{user}"].append(Reason)

async def setup(bot):
await bot.add_cog(Warncog(bot))

hazy vault
#

what's wrong

#

I am using version 3.9.7

rugged shadow
#

but I should note that you should use discord.py 2.x or some other fork instead of some very old library

#

just don't use relative imports lmao

#

show me the line where you're importing that fails

#

show the file structure

austere prairie
#

How are you executing the code?

#

How are you running that file?

#

Yeah

#

Maybe try invoking as a module instead?

solar coyote
#
class NumberChoice(discord.ui.Modal, title="Select the number"):
    def __init__(self):
        self.result_list=[]
        super().__init__(timeout=30, custom_id="select_num")
    number=discord.ui.TextInput(label="Enter your Number", max_length=3)

    async def on_submit(self, interaction: Interaction):
        self.result_list.append([interaction.user,self.number.value[0]])
        await interaction.response.send_message(f"{interaction.user} chose the number {self.number.value[0]}", ephemeral=True)
        self.result_list.append([interaction.user,self.number.value[0]])
        client.mismatch_result[interaction.guild.id]=self.result_list
        print(client.mismatch_result[interaction.guild.id])

why does this code add only the last person who replied and not all the users who answered?

terse hawk
#
@client.command()
async def clear(ctx):
    if ctx.author.guild_permissions.administrator:
            args = ctx.content.split()
            if len(args) == 1:
                
                await ctx.channel.purge(limit=10)
            else:
                
                try:
                    count = int(args[1])
                    await ctx.channel.purge(limit=count+1)
                except ValueError:
                     print("ValueError!")
#

Why does the /clear command not worrk

#

it hhasnt any problems but the bot wont Delete the messages

tall temple
#

how to get members count of a server where the bot is

steady flume
#

how to activate button in other class in v.2 ?
i try this:

assert self.view is not None
view: Menu_Lang = self.view
self.view.children[0].disabled = False

it doesnt work (if so i have only one button)

sullen shoal
unkempt canyonBOT
#

property member_count```
Returns the member count if available.

Warning

Due to a Discord limitation, in order for this attribute to remain up-to-date and accurate, it requires [`Intents.members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Intents.members "discord.Intents.members") to be specified.

Changed in version 2.0: Now returns an `Optional[int]`.
hazy vault
hazy vault
austere prairie
#

d.py natively supports components/slash commands now

hazy vault
austere prairie
#

Use discord.py instead of cookies-discord-components or whatever

hazy vault
#

do you mean this

slate swan
#

yes that is what they said

tall temple
#

yo

#

could you give me a syntax to restrict the command to people who have a specific role in a specific guild

slate swan
unkempt canyonBOT
#

@discord.app_commands.checks.has_role(item, /)```
A [`check()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.check "discord.app_commands.check") that is added that checks if the member invoking the command has the role specified via the name or ID specified.

If a string is specified, you must give the exact name of the role, including caps and spelling.

If an integer is specified, you must give the exact snowflake ID of the role.

This check raises one of two special exceptions, [`MissingRole`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.MissingRole "discord.app_commands.MissingRole") if the user is missing a role, or [`NoPrivateMessage`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.NoPrivateMessage "discord.app_commands.NoPrivateMessage") if it is used in a private message. Both inherit from [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CheckFailure "discord.app_commands.CheckFailure").

New in version 2.0...
slate swan
#
@tree.command()
@app_commands.checks.has_role(123456789) # ID of the role, can be name as well
async def cool(interaction: discord.Interaction):
    await interaction.response.send_message('You are cool indeed')
tall temple
quick gust
#

does bot.add_check() work with slash commands?

#

if not how do I add checks for slash commands (disnake)

#

also why can't I find a slash command example on their repository

#

i swear it existed

slate swan
quick gust
#

am I blind because I can't see it there... is it supposed to be what's inside subcmd.py?

slate swan
quick gust
#

or does it not have a separate file of its own

#

i think thats the case

#

ty, that works

quick gust
#

thanks!

final flame
#

I need to take a look at a discord economy bot code using discord.py

slow ether
#

o Sorry

formal basin
#

I have been trying to make a anti toxicity thing and make a thing so they can’t bypass it and found something online but it doesn’t seem to work

lyric sphinx
#

you could also try using levenshtein distance

#

Anyways, is there a way to get discord rpc data from a user?

lyric sphinx
lyric sphinx
#

!e

print("TEST".lower())
unkempt canyonBOT
#

@lyric sphinx :white_check_mark: Your 3.11 eval job has completed with return code 0.

test
formal basin
lyric sphinx
#

why would it matter?

formal basin
#

Because they would bypass it

lyric sphinx
#

you make the string always the same case to not implement both versions of the word in your list

#

rn you're doing "X", "x"

#

but you can just .lower() and check for "x" or .upper() and check for "X"

formal basin
#

Can I do both?

lyric sphinx
#

why?

formal basin
#

If i do .lower() and they do an upper version will it get deleted?

lyric sphinx
#

thats the point?

formal basin
lyric sphinx
#

i didnt ask whats the point, i said thats the point

#

to ignore the case in which user wrote the message

#

also, you're doing word in message.content, but message content is a string, so iterating over it -> iterating over characters, not words

formal basin
#

Can you just give me an example

lyric sphinx
#

ok, couple of minutes

#

!e

banned_list: list[str] = ["word_1", "word_2"]
message_content: str = "WoRd_1"
if any([word in banned_list for word in message_content.lower().split()]):
    print("Bad message detected")
unkempt canyonBOT
#

@lyric sphinx :white_check_mark: Your 3.11 eval job has completed with return code 0.

Bad message detected
lyric sphinx
#

although you should just use a profanity filter library

formal basin
#

Ohhh

lyric sphinx
#

they've already done the stuff for you

#

!pypi profanity-filter

unkempt canyonBOT
lyric sphinx
#

!pypi profanity-check

unkempt canyonBOT
lyric sphinx
#

or this ^

#

you could set a ,,limit" for the ,,amount" of profanity and delete all messages in which the profanity amount is higher than the limit

formal basin
smoky sinew
unkempt canyonBOT
#

@smoky sinew :white_check_mark: Your 3.11 eval job has completed with return code 0.

True
formal basin
smoky sinew
#

who said that

#

just use profanity-check

formal basin
#

Because I’m trying

smoky sinew
#

profanity-check is better

formal basin
smoky sinew
#

there are libraries for that too

#

it already works on toxicity

lyric sphinx
smoky sinew
#

just use profanity-check

lyric sphinx
formal basin
#

Can you give me an example

lyric sphinx
formal basin
#

So I install it?

#

pip install profanity check

lyric sphinx
#

well, yeah, you pip install it, like any other package

formal basin
lyric sphinx
#

i already said what you have to do

#

its like 2 lines, just check the profanity check page and you'll see how to use it

formal basin
#

I don’t think it will work

lyric sphinx
#

why?

formal basin
#

Because it says

lyric sphinx
#

what command are you running?

formal basin
#

pip install profanity check

lyric sphinx
#

are you doing pip install profanity check or pip install profanity-check

formal basin
#

Yes

lyric sphinx
#

are you trolling?

#

like, what yes? how am i supposed to understand which of these options is yes?

formal basin
#

No

lyric sphinx
#

k im done 💀

formal basin
formal basin
lyric sphinx
#

notice 1 difference challenge (impossible)

formal basin
#

Oh

#

Do I import anything

lyric sphinx
#

well, you import it, because if you want to use a package - you need to import it

formal basin
#

from profanity-check import profanity-check

lyric sphinx
#

I think you're simply not ready for discord bots. Learn more basics of python, then get into bot development. Its not an easy process.

formal basin
#

That?

#

I’m just checking

lyric sphinx
formal basin
#

Ok

lyric sphinx
formal basin
lyric sphinx
#

?

formal basin
#

In the usage

lyric sphinx
#

it shows how it works

formal basin
lyric sphinx
#

i can't tell if you're trolling or not

formal basin
#

And say how much of profanity it’s worth

lyric sphinx
#

well yeah, then you just use this amount of profanity to determine whether the message needs to be deleted

formal basin
#

I want every word of profanity deleted

lyric sphinx
#

more precision -> less speed

formal basin
#

But that gonna be hard to write every single profanity word

lyric sphinx
#

you dont need to?

#

the algorithm already has a db of bad words

#

it seems to me like you're not really understanding anything of what you're doing

formal basin
#

Can’t I just make every word in the db get deleted

lyric sphinx
#

well, the words are only the basic ones, people tend to try and get around the blocks by messing up the way they write the words

#

so by deleting every word only from the db, you'll only delete exact matches

#

while the algorithm determines how close is it to a bad word

smoky sinew
formal basin
#

Just never mind

lyric sphinx
#

Honestly, my best tip (no aggression intended), would be to go and actually learn programming before going into bot development

#

I swear, its so much better and easier when you actually understand what you're doing

formal basin
#

Thanks for your help

smoky sinew
#

why are you using requests

#

just make the gui separate

#

use ipc maybe

slate plover
#

Ok, so I need help with events, I've been trying to use the on_message event but i dont know how to use it.

#

any examples that could show me how?

vivid axle
#

im having an argument with my friend im making a bot with him and basically he wants to make tickets when their called #bicxter etc whatever but i think it hsould be #ticket-5001 or something because we store the channel ids in database and its easier to get it with the ticket- thing idk

#

which should i do

tall temple
#

pls how can i make a command accessible only in a specific guild ?

hushed galleon
smoky sinew
scarlet sorrel
#

Why am I getting AttributeError: 'Intents' object has no attribute 'GUILD_VOICE_STATES' from this?

#

nvm chatgpt knew

scarlet sorrel
#

it was supposed to be voice_states

smoky sinew
#

also intents.messages = True is included in Intents.default(), so i'm assuming you meant to do intents.message_content = True

#

.default() enables all non-privileged intents

scarlet sorrel
#

it's supposed to be messages

smoky sinew
#

then you're using an outdated version of discord.py

scarlet sorrel
#

yep

#

new ones suck

smoky sinew
#

either way default() enables messages

smoky sinew
#

what version are you using

scarlet sorrel
smoky sinew
#

discord.__version__

scarlet sorrel
#

also why does this just hang on voice_state.channel.connect() forever 😭

            try:
                connection = await voice_state.channel.connect()
            except discord.ClientException:
                connection = get_voice_client_from_channel_id(voice_state.channel.id)
scarlet sorrel
smoky sinew
#

ah yes

scarlet sorrel
#

classic version

smoky sinew
#

i wonder if the API gateway that 1.7.3 uses is going to get removed soon

#

considering it's more than 2 years old at this point

scarlet sorrel
smoky sinew
#

👍

scarlet sorrel
smoky sinew
#

okay i just checked 1.7.3 uses v8

scarlet sorrel
#

fair enough

scarlet sorrel
#

because it is connecting but never getting past that await still

smoky sinew
#

i don't think you can interrupt a coroutine like that

#

also i just checked, and v7 got removed in february so you might only have a few months left of using 1.7.3

#

until you're forced to migrate

scarlet sorrel
smoky sinew
scarlet sorrel
#

don't need it to start if it's already running

smoky sinew
#

i'm going to assume that was a joke but i genuinely can't tell

feral sinew
#

Is there a way i can terminate a view after it has completed what it was meant to do?
more specifically, if a view had a button callback is there a way to disable that button after it has completed what it was meant to do?

#

i thought of doing button.disabled = True from the button's callback but maybe i dont understand how its meant to work

smoky sinew
#

await interaction.edit_original_response(view=self)

feral sinew
#

oh yep that did it, thanks!
i used interaction.response.edit_message instead but yeah same effect

smoky sinew
feral sinew
#

oh? I'll look into that later then, i chose that to stay consistent with my code ¯_(ツ)_/¯

final flame
#

I need to take a look at a discord economy bot code using discord.py

slate swan
#

👌

smoky sinew
hallow kernel
#
allowed_pstfxs = [
    "ня", "nya"
]
async def on_message(message):
    if not any(message.endswith(postfix) for postfix in allowed_pstfxs):
        await message.delete()
tall temple
#

pls how can i make a command accessible only in a specific guild ?

merry cliff
#

also text command or slash command

tall temple
tall temple
merry cliff
#

well with a text command you can just get the guild id from the context and if its not in a specific list of guild ids then dont run the command

#

idk pycord slash command tho

#

ok so after some quick research, there is a guild_ids parameter you can set when creating a slash command to make it only visible to those guilds

merry cliff
tall temple
#

thanks

slate swan
#

i installed discord-py-slash-command but when i try to import it can't find it can anyone help me

merry cliff
merry cliff
#

ok a very basic slash command example:

#
@bot.tree.command(name='avatar', description="gets a requested user's avatar")
@app_commands.describe(user='the user you are trying to get')
async def _avatar(interaction: discord.Interaction, user: discord.User):
    await interaction.response.defer(thinking=True)

    embed = discord.Embed(title=f"{user.name}'s Avatar", url=user.avatar.url)
    embed.set_author(name=f"{user.name}#{user.discriminator}", icon_url=user.avatar.url, url=user.avatar.url)
    embed.set_image(url=user.avatar.url)
    embed.set_footer(text=f"Requested by {interaction.user.name}#{interaction.user.discriminator}", icon_url=interaction.user.avatar.url)

    await interaction.followup.send(embed=embed)
#

imports:

#
import discord
from discord.ext import commands  # for the bot
from discord import app_commands  # for the slash command```
naive briar
#

You also need to sync the commands

slate swan
hard bramble
#
    @commands.Cog.listener()
    async def on_raw_reaction_add(self, rre):
        if rre.emoji.name == "\N{OPTICAL DISC}":
            #print(rre)
            channel = self.bot.get_channel(rre.channel_id)
            if channel != None: #not a dm
                message = await channel.fetch_message(rre.message_id) #works 
            else: #a dm
                print(self.bot.get_channel(rre.channel_id))
                user = self.bot.get_user(rre.user_id) #works - returns ClientUser
                message = user.get_message(rre.message_id) #DOES NOT WORK - ClientUser has no attribute get_message
            reaction = get(message.reactions, emoji=rre.emoji.name)
            COUNT = reaction.count
            if COUNT > 1:
                await self._dvonreact(message.content)
                await message.add_reaction("\N{DVD}")

hello, I need a little help, I'm trying to get a message object using only a user id and message id, I've tried this and a few others but it doesn't work

naive briar
#

What doesn't work

hard bramble
slate swan
#

how do sync my slash commands

slate plover
#

How to? Bot checks users for a role > bot finds someone with that certain role > bot gives a new role and takes away that certain role.

naive briar
unkempt canyonBOT
#

await fetch_message(id, /)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Retrieves a single [`Message`](https://docs.pycord.dev/en/stable/api/models.html#discord.Message "discord.Message") from the destination.
naive briar
#

You already have the channel object, just use that

hard bramble
#

that's why I used channel == None as check whether it is a dm channel or a channel in a guild

slate plover
#

Oh it seems you all are busy, ill comeback later

naive briar
unkempt canyonBOT
#

property dm_channel```
Returns the channel associated with this user if it exists.

If this returns `None`, you can create a DM channel by calling the [`create_dm()`](https://docs.pycord.dev/en/stable/api/models.html#discord.User.create_dm "discord.User.create_dm") coroutine function.
hard bramble
hard bramble
naive briar
merry cliff
#

sorry was busy

slate swan
merry cliff
#

it takes a few minutes for the commands to register

#

the first time

#

but after 5 minutes you should see them

slate swan
#

thanks

merry cliff
#

np

#

pm me if u need further help in the future

slate swan
merry cliff
#

*asleep

hard bramble
empty palm
#

how can it be understood. no error and the code does not work.

hard bramble
vale wing
#

If any additional explanations needed feel free to ask

slate plover
vale wing
vale wing
unkempt canyonBOT
#
SQL & f-strings

Don't use f-strings (f"") or other forms of "string interpolation" (%, +, .format) to inject data into a SQL query. It is an endless source of bugs and syntax errors. Additionally, in user-facing applications, it presents a major security risk via SQL injection.

Your database library should support "query parameters". A query parameter is a placeholder that you put in the SQL query. When the query is executed, you provide data to the database library, and the library inserts the data into the query for you, safely.

For example, the sqlite3 package supports using ? as a placeholder:

query = "SELECT * FROM stocks WHERE symbol = ?;"
params = ("RHAT",)
db.execute(query, params)

Note: Different database libraries support different placeholder styles, e.g. %s and $1. Consult your library's documentation for details.

See Also
Python sqlite3 docs - How to use placeholders to bind values in SQL queries
PEP-249 - A specification of how database libraries in Python should work

vale wing
#

Second, use async db wrapper

#

Judging by syntax you have there it's most likely sqlite3, use aiosqlite

#

Third, .fetchone() may return empty list but you're still trying to access the first element which might simply not exist. You need to handle that situation

empty palm
#

Huh

vale wing
#

Forth, use proper naming convention

#

Fifth, since no errors appear you probably have bad error handler that eats up unknown errors, make sure it raises the exception if it hasn't been handled

#

Ik, many things to fix but you should definitely work on all these

#

Step by step

empty palm
#

Okay tysm!

#

👍🏻

lyric halo
#

anyone know how to add buttons in an embed?

winged coral
#

In the embed?

#

Or just components on the message

lunar knoll
#

guys do u have a good tutorial for discord bot making in yt

vocal snow
dense jackal
#

In my welcome message I use easy_pil so I need the member.avatar.url but when a user doesn’t have any pfp, the messages doesn’t send. What can I do?

shrewd apex
thin trout
#

someone know why i can't import app_commands from discord?

slate swan
#

how to make persistent cooldown commands
like after i restart bot cooldown ends

quick gust
#

Don't think there's any other way

molten hare
#

.latex

#

.latex 1

#

!d arcade

unkempt canyonBOT
sick birch
forest topaz
formal basin
#
async def warnings(ctx, user: discord.Member = None):

  if user == None:
    users = ctx.author

  
  await open_account(user)
  users = await get_warns_data()


  warns_amt = users[str(user.id)]["warns"]
   
  em = discord.Embed(title = f"{user.name}'s warnings", color = discord.Color.yellow())
  em.add_field(name = "warns",value = warns_amt)
  await ctx.send(embed = em)

@client.command()
@commands.has_permissions(manage_messages=True)
async def warn(ctx, user: discord.User):
  await open_account(user)


  users = await get_warns_data()


  warns = 1

  await ctx.send(f"{user.name} has been warned")

  users[str(user.id)]["warns"] += warns
   
  with open("warndata.json","w") as f:
    json.dump(users,f)
  
  


async def open_account(user):

  users = await get_warns_data()

  if str(user.id) in users:
    return False
  else:
      users[str(user.id)] = {}
      users[str(user.id)]["warns"] = 0

  with open("warndata.json","w") as f:
    json.dump(users,f)

  return True

  async def get_warns_data():
      with open("warndata.json","r") as f:
           users = json.load(f)

      return users```
#

File "/home/runner/zag/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 229, in wrapped
ret = await coro(*args, **kwargs)
File "main.py", line 60, in warnings
File "main.py", line 94, in open_account
UnboundLocalError: local variable 'get_warns_data' referenced before assignment

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "/home/runner/zag/venv/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 1350, in invoke
await ctx.command.invoke(ctx)
File "/home/runner/zag/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "/home/runner/zag/venv/lib/python3.10/site-packages/discord/ext/commands/core.py", line 238, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: UnboundLocalError: local variable 'get_warns_data' referenced before assignment
172.31.128.1 - - [30/Apr/2023 19:24:21] "HEAD / HTTP/1.1" 200 -

#

can someone help me

vale wing
slate swan
#

how do ephemeral messages work

formal basin
slate swan
#

how do i make options in slash commands not required

merry cliff
merry cliff
#

Np

#

Just woke up lmao

slate swan
merry cliff
#

Text or slash command

slate swan
merry cliff
#

Which library

slate swan
merry cliff
#

Hold up lemme start up my computer

#

Ok so when you create a slash command

#

Add an extra decorator

#

@app_commands.guilds(guild ids)

#

and put the guild ids in a list. I’m pretty sure that’s how it works but I’ve never used it.

#

full example:

merry cliff
# slate swan yes
@app_commands.command(args)  # or @bot.tree.command if not in a cog
@app_commands.guilds(12345, 23456, etc)  # the guild ids can be accessed when right clicking a server icon with dev mode turned on
async def command(args):
    pass  # code goes here```
#

ok i gtg now

#

wdym by before

slate swan
#

with the purge command you should set the limit to (limit=limit+1) so that it will delete the command with it

slate swan
#

Any recommendations on my help command code?

async def help(ctx: commands.Context) -> None:
    command_list = [(command.name, command.description) for command in ryan.commands]
    pages = []
    KEYS_PER_PAGE = 10
    for index, chunk in enumerate(more_itertools.chunked(command_list, KEYS_PER_PAGE)):
        embed = discord.Embed(
            title=f"Help Menu - {len(ryan.commands)} Commands", color=0x808080
        )
        embed.set_author(name=ctx.message.author.name, icon_url=ctx.author.avatar.url)
        embed.description = "\n".join(
            [
                f"{(index * KEYS_PER_PAGE) + i + 1}. **{name}**: `{desc}`"
                for i, (name, desc) in enumerate(chunk)
            ]
        )
        pages.append(embed)

    await Paginator.Simple(timeout=60).start(ctx, pages=pages)
sullen shoal
#

don't reinvent the wheel, and instead subclass commands.HelpCommand

slate swan
#

How do I make my own decorator, specifically I want to add a decorator that checks if a user is blacklisted.

sullen shoal
#

however, there is no need for a decorator just for that. Have a global check, and a global error handler. Subclass CommandError and name it BlacklistedUserError or whatever, then raise that in the global check if the user is blacklisted, and ||catch CommandInvokeError on your global error handler, and see if .original is your subclass of CommandError|| catch BlacklistedUserError

#

actually, no, you don't need to catch CommandInvokeError, just catch BlacklistedUserError

slate swan
#

@sullen shoal Can I just ignore the discord.ext.commands.errors.CheckFailure:?

#

I can show you the decorator I made, I might've done something wrong, but it works as it should

sullen shoal
slate swan
#

yeah, I raise False on purpose

sullen shoal
#

you shouldn't globally ignore it

#

create a local error handler and ignore it there

slate swan
#

Gotcha

#

So each command would have to have one as well

#

that uses the blacklist deco

sullen shoal
#

yes, that's why I'd say go for custom exceptions and a global check

slate swan
#
@np.error
async def np_error(ctx: commands.Context, error) -> None:
    if isinstance(error, commands.CheckFailure):
        pass
    else:
        raise error

Something like this for each command?

sullen shoal
#

you can have a local error handler for the cog as well. Or check the command name using the Context obj that you get in the global error handler and have a list of command names that you'd want to pass the error for

young pendant
sullen shoal
young pendant
# sullen shoal I am following, what do you need help with?

https://paste.pythondiscord.com/bafisubowo
I made that script,
the system is called REPORT-SYSTEM

In the script you can see this:

        user_reporting = interaction.user
        user_reported = message.author
        reported_message_link = message.jump_url
        reported_message_content = message.content
        mods_channel = self.report_channel
        embed = discord.Embed(title="Reported Message", color=discord.Colour.from_rgb(255, 0, 0))
        embed.add_field(name="Reporting User", value=user_reporting.mention, inline=False)
        embed.add_field(name="Reported User", value=user_reported.mention, inline=False)
        embed.add_field(name="Reported Message", value=reported_message_link, inline=False)
        embed.add_field(name="Reported Message", value=reported_message_content, inline=False)

        await mods_channel.send(embed=embed)
        return embed```

I would like the report_message command to be a message command.

Like, when I right click a message and the ``APP``  section pops up with a command that I can use
#

do you maybe know how I can implement this in my code?

#

i`m kinda new to discord.py and struggling to understand it a bit

sullen shoal
#

I'd know for Disnake as that is what I am mainly familiar with for anything interactions specific. However, if your mission is to have both a slash command and a message command with the same functionality, you should wrap the duplicated functionalities into several functions

#

I am not faimilar with the design choices of Danny and Discord.py

young pendant
sullen shoal
young pendant
#

Ok, still thanks for trying to help

sullen shoal
#

keep in mind that your database adapter is not asynchronous, and if two people are running the same command simultaneously, the resultant can be unexpected

#

and, your codebase is vulnerable to SQL injections, see <#bot-commands message>

smoky sinew
#

these are referred to as context menus in discord.py

#
@app_commands.context_menu()
async def react(interaction: discord.Interaction, message: discord.Message):
    await interaction.response.send_message('Very cool message!', ephemeral=True)
slate swan
#

Hello!

I am making a lockdown command
Code:

    @commands.command(name="lockdown")
    @commands.has_permissions(manage_channels=True)
    async def lockdown(self, ctx: commands.Context, reason: str = None):
        msg = await ctx.reply(
            embed=discord.Embed(
                color=0x0000FF,
                description=f"{ctx.author.mention}; Processing command."
            ).set_author(
                name="Processing lockdown command",
                icon_url=ctx.guild.icon
            ).set_footer(
                text=f"Command ran by - {ctx.author}",
                icon_url=ctx.author.avatar
            )
        )

        start = time.time()
        final = discord.Embed(
            color=0x0000FF
        ).set_footer(
            text=f"Command ran by - {ctx.author}",
            icon_url=ctx.author.avatar
        )
        channels = []
        roles = []
        channelss = config['Lockdown Config']['Channel IDs']
        roless = config['Lockdown Config']['Role IDs']
        for input in channelss: channels.append(input)
        for input in roless: roles.append(input)
        if reason is None: reason = "No reason provided."
        Locking = False
        for channel_id in channels:
            channel = commands.Bot.get_channel(self, channel_id)
            for role_id in roles:
                role = ctx.guild.get_role(role_id)
                perms = channel.permissions_for(role)
                if not perms.send_messages: await channel.set_permissions(role, send_messages=True)
                else:
                    await channel.set_permissions(role, send_messages=False)
                    if Locking: pass
                    else: Locking = True
            if Locking:
                await channel.send("This channel has been locked by {} for reason {}".format(ctx.author.mention, reason))
                final.description = f"{ctx.author.mention}; Successfully locked down server in `{elapsed}s`"
            else:
                await channel.send("This channel has been unlocked by {}".format(ctx.author.mention))
                final.description = f"{ctx.author.mention}; Successfully unlocked server in `{elapsed}s`"
        end = time.time()
        elapsed = round(end - start, 2)
        await msg.edit(embed=final)
    @lockdown.error
    async def lockdown_error(self, ctx:ctxx, error):
        if isinstance(error, commands.MissingPermissions):
            await ctx.reply(
                embed = discord.Embed(
                    color = 0xFF0000,
                    description = f"{ctx.author.mention}; You are not authorized to run this commands"
                ).set_author(
                    name = "Missing required permissions - Manage Channels",
                    icon_url = ctx.guild.icon
                ).set_footer(
                    text = f"Command ran by - {ctx.author}",
                    icon_url = ctx.author.avatar
                )
            )

Config file:

    "Lockdown Config": {
        "Role IDs": [
            1090787392501317687
        ],
        "Channel IDs": [
            1102056458855653468,
            1099897631968350218
        ]
    }   

But it does the first part where it says it is initializing but it doesn't do anything after

young pendant
smoky sinew
#

also i'm pretty sure slash commands can't return anything

#

you need to send the message instead

#

the return type would be -> None

young pendant
#

you mean because of the return embed?

slate swan
#

What's the best way to make a snipe command?

slate swan
young pendant
slate swan
young pendant
#

Yes, and what would be the issue in my script?

slate swan
#
def add(a: int, b: int) -> int:
    return a + b

Here's a simple example, a and b are ints so that function will also return an int.

slate swan
sullen shoal
slate swan
sullen shoal
#

have a dict

empty lintel
#

i love dict

slate swan
sullen shoal
haughty dew
#

Hey bot people.. I wrote a discord bot a while ago kinda just going off the top of my head without any inspiration. Is this a good command handler?

class Client(discord.Client):
    async def on_ready(self):
        print('Logged on as', self.user)

    async def on_message(self, message):
        print(f"Message Recieved:\nMessage Content: {message.content}\nMessage Author: {message.author.name}#{message.author.discriminator}")
        if message.author.bot: return
        if message.channel.type == "private": return
        if not message.content.startswith(config["prefix"]): return
        messageArray = message.content[len(config["prefix"]):].split(' ')
        cmd = messageArray[0]
        args = messageArray[1:]

        command = path.isfile(path.join(config["commandFolder"], cmd + ".py"))
        if command:
            exec(f"from commands import {cmd}")
            await eval(f"{cmd}.{cmd}(self, message, args)")
#

I didn't want all of my commands to be in a single file or anything, for a cleaner look.

golden portal
haughty dew
#

I feel like that would give me less control overall, unless I'm massively wrong. What if I wanted to add content moderation to my bot?

sick birch
#

Trust me, you really do not wanting to be writing command parsers by hand

#

Especially when discord.py gives you a rich system for parsing

golden portal
#

actually it gives you control such as commands check and converter

haughty dew
#
import discord
from discord.ext import commands

intents = discord.Intents.default()
intents.message_content = True

bot = commands.Bot(command_prefix='$', intents=intents)

@bot.command()
async def test(ctx):
    pass

# or:

@commands.command()
async def test(ctx):
    pass

bot.add_command(test)

this example seems to say that all of the commands are in one file...

golden portal
#

Example would be something like

other/file.py ```py
class MyCog(commands.Cog):
@commands.command()
async def test(ctx):
...

async def setup(bot):
await bot.add_cog(MyCog())

Then you would load them by `await bot.load_extension('other.file')` in the main file
slate swan
#

Hello!

I am making a lockdown command
Code:

    @commands.command(name="lockdown")
    @commands.has_permissions(manage_channels=True)
    async def lockdown(self, ctx: commands.Context, reason: str = None):
        msg = await ctx.reply(
            embed=discord.Embed(
                color=0x0000FF,
                description=f"{ctx.author.mention}; Processing command."
            ).set_author(
                name="Processing lockdown command",
                icon_url=ctx.guild.icon
            ).set_footer(
                text=f"Command ran by - {ctx.author}",
                icon_url=ctx.author.avatar
            )
        )

        start = time.time()
        final = discord.Embed(
            color=0x0000FF
        ).set_footer(
            text=f"Command ran by - {ctx.author}",
            icon_url=ctx.author.avatar
        )
        channels = []
        roles = []
        channelss = config['Lockdown Config']['Channel IDs']
        roless = config['Lockdown Config']['Role IDs']
        for input in channelss: channels.append(input)
        for input in roless: roles.append(input)
        if reason is None: reason = "No reason provided."
        Locking = False
        for channel_id in channels:
            channel = commands.Bot.get_channel(self, channel_id)
            for role_id in roles:
                role = ctx.guild.get_role(role_id)
                perms = channel.permissions_for(role)
                if not perms.send_messages: await channel.set_permissions(role, send_messages=True)
                else:
                    await channel.set_permissions(role, send_messages=False)
                    if Locking: pass
                    else: Locking = True
            if Locking:
                await channel.send("This channel has been locked by {} for reason {}".format(ctx.author.mention, reason))
                final.description = f"{ctx.author.mention}; Successfully locked down server in `{elapsed}s`"
            else:
                await channel.send("This channel has been unlocked by {}".format(ctx.author.mention))
                final.description = f"{ctx.author.mention}; Successfully unlocked server in `{elapsed}s`"
        end = time.time()
        elapsed = round(end - start, 2)
        await msg.edit(embed=final)

Config file:

    "Lockdown Config": {
        "Role IDs": [
            1090787392501317687
        ],
        "Channel IDs": [
            1102056458855653468,
            1099897631968350218
        ]
    }   

But it does the first part where it says it is initializing but it doesn't do anything after

opaque elk
#

Someone got a docs for this?

smoky sinew
opaque elk
#

Like leaderboard

smoky sinew
#

just make it

#

break it down into parts

#

and do them seperately

slate swan
#

How do you get a default pfp url?

smoky sinew
unkempt canyonBOT
#

property default_avatar```
Returns the default avatar for a given user. This is calculated by the user’s discriminator.
smoky sinew
#

python bot uses pycord docs now?? hm

slate swan
#

author.default_avatar.url ?

#

How long are Discord guild ids?

sick birch
slate swan
#

Ah. Wondering what data type to use for my database

#

to store them

smoky sinew
#

use BIGINT

sick birch
#

Or yeah bigint

smoky sinew
#

currently, snowflakes are around 19 digits

#

but that might change

#

they actually didn't become 19 digits until a few months ago

slate swan
#

What's the best way to handle discord.errors.Forbidden?

upbeat gust
slate swan
upbeat gust
slate swan
upbeat gust
slate swan
smoky sinew
#

on_command_error only catches errors that are inheriting from discord.ext.commands.CommandError

#

instead use try/except as that's how the exception is raised when you use Member.add_roles

short silo
#

Just a general question, if you have a database which has a list of allowed users. How do you 'cache' the list so you don't have to use the db again and again or is it in fact actually a better practice to use the db ?

#

I would suppose, it's better to cache ?

slate swan
#

You could create a python list as a botvar

#

Or more advanced solution would be to use cache db Like Redis

#

!botvar

unkempt canyonBOT
#
Bot variables

Python allows you to set custom attributes to most objects, like your bot! By storing things as attributes of the bot object, you can access them anywhere you access your bot. In the discord.py library, these custom attributes are commonly known as "bot variables" and can be a lifesaver if your bot is divided into many different files. An example on how to use custom attributes on your bot is shown below:

bot = commands.Bot(command_prefix="!")
# Set an attribute on our bot
bot.test = "I am accessible everywhere!"

@bot.command()
async def get(ctx: commands.Context):
    """A command to get the current value of `test`."""
    # Send what the test attribute is currently set to
    await ctx.send(ctx.bot.test)

@bot.command()
async def setval(ctx: commands.Context, *, new_text: str):
    """A command to set a new value of `test`."""
    # Here we change the attribute to what was specified in new_text
    bot.test = new_text

This all applies to cogs as well! You can set attributes to self as you wish.

Be sure not to overwrite attributes discord.py uses, like cogs or users. Name your attributes carefully!

smoky sinew
#

databases are designed to handle thousands of queries per second

#

making one every time someone runs a command is not that expensive

upbeat gust
unkempt canyonBOT
#

error_handler.py line 49

error = getattr(error, 'original', error)```
short silo
molten hare
#

!d vars

unkempt canyonBOT
#

vars()``````py

vars(object)```
Return the [`__dict__`](https://docs.python.org/3/library/stdtypes.html#object.__dict__ "object.__dict__") attribute for a module, class, instance, or any other object with a [`__dict__`](https://docs.python.org/3/library/stdtypes.html#object.__dict__ "object.__dict__") attribute.

Objects such as modules and instances have an updateable [`__dict__`](https://docs.python.org/3/library/stdtypes.html#object.__dict__ "object.__dict__") attribute; however, other objects may have write restrictions on their [`__dict__`](https://docs.python.org/3/library/stdtypes.html#object.__dict__ "object.__dict__") attributes (for example, classes use a [`types.MappingProxyType`](https://docs.python.org/3/library/types.html#types.MappingProxyType "types.MappingProxyType") to prevent direct dictionary updates).

Without an argument, [`vars()`](https://docs.python.org/3/library/functions.html#vars "vars") acts like [`locals()`](https://docs.python.org/3/library/functions.html#locals "locals"). Note, the locals dictionary is only useful for reads since updates to the locals dictionary are ignored.

A [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "TypeError") exception is raised if an object is specified but it doesn’t have a [`__dict__`](https://docs.python.org/3/library/stdtypes.html#object.__dict__ "object.__dict__") attribute (for example, if its class defines the [`__slots__`](https://docs.python.org/3/reference/datamodel.html#object.__slots__ "object.__slots__") attribute).
manic path
#
    @commands.group(name='race')
    @channel_check(Channels().bot_commands)
    async def math_racer(self, ctx:Context, paper:t.Optional[int], mode:t.Optional[str]) -> None:

This keeps on giving me an error,
Command raised an exception: TypeError: MathQP.math_racer() missing 1 required keyword-only argument: 'mode'

#

Why is it so?

#

nvm fixed it

#

But I did get another one in its stead,

TypeError: 'float' object cannot be interpreted as an integer
manic path
#

nvm got it

timid spade
#

hey so
i want to define all the slash commands in a seperate file then import that file to bot.py.
like i want separate my all commands in files. can anyone help?

merry cliff
#

so into a cog

timid spade
#

what

smoky sinew
#

but if you really want to

#

!d discord.app_commands.CommandTree.add_command

unkempt canyonBOT
#

add_command(command, /, *, guild=..., guilds=..., override=False)```
Adds an application command to the tree.

This only adds the command locally – in order to sync the commands and enable them in the client, [`sync()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.app_commands.CommandTree.sync "discord.app_commands.CommandTree.sync") must be called.

The root parent of the command is added regardless of the type passed.
smoky sinew
#

or just use extensions with add_command in setup

timid spade
smoky sinew
#

but your extensions should probably be grouped by category

timid spade
smoky sinew
#

that’s my fault sorry

#

there’s a good tutorial on the docs

#

i can’t link it because i’m on mobile

timid spade
#

tutorial will be helpful
is it cool if i remind you after some time?

slate swan
#

what function removes slash commands from the bot?

golden portal
slate swan
#

but what function is it?

hushed galleon
hushed galleon
unkempt canyonBOT
#

await sync(*, guild=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Syncs the application commands to Discord.

This also runs the translator to get the translated strings necessary for feeding back into Discord.

This must be called for the application commands to show up.
slate swan
hushed galleon
#

guild only gets synced if you give something to the guild parameter

slate swan
#

so if you don't then it's considered global?

true jungle
#

Hi, uh I’m new here, so what’s this channel about?

vocal snow
slow fog
mighty pilot
#

Can discord bots work in threads now? Just saw a bounty for a bot that interacts in threads

hushed galleon
#

i dont know if bots didnt support them when they were first introduced, but now sure, discord.py has supported threads since 2.0 which released last year
(and dpy 2.0 took a while before it was released, disnake's first 2.0 release, at least as indicated on their github, supported threads since october 2021)

mighty pilot
#

Sweet. Thanks

short silo
#

is there any way to have custom decorators ? or what can be my options if i want to run a lot of checks without cluttering the main function. Basically, i wanna run checks but i dont wanna return anything to the function for if else

slate swan
mighty pilot
#

I'll work with discord.py, that's what I'm most familiar with. Just didn't know it had support for threads. Guess I never needed my bots to so I didn't worry about it

slate swan
unkempt canyonBOT
#

@discord.ext.commands.check(predicate)```
A decorator that adds a check to the [`Command`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command "discord.ext.commands.Command") or its subclasses. These checks could be accessed via [`Command.checks`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Command.checks "discord.ext.commands.Command.checks").

These checks should be predicates that take in a single parameter taking a [`Context`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.Context "discord.ext.commands.Context"). If the check returns a `False`-like value then during invocation a [`CheckFailure`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CheckFailure "discord.ext.commands.CheckFailure") exception is raised and sent to the [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error") event.

If an exception should be thrown in the predicate then it should be a subclass of [`CommandError`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.ext.commands.CommandError "discord.ext.commands.CommandError"). Any exception not subclassed from it will be propagated while those subclassed will be sent to [`on_command_error()`](https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#discord.discord.ext.commands.on_command_error "discord.discord.ext.commands.on_command_error").
molten hare
#

!e

pprint("You are the man")
dense flower
#

hey guys, if you were storing data for a raffle system how would you do it? I'm currently using an SQL database and doing this:py cur.execute(''' CREATE TABLE raffles( raffleID INTEGER PRIMARY KEY AUTOINCREMENT, guildID INTEGER NOT NULL, userID INTEGER NOT NULL, userAddress STRING NOT NULL, itemID INTEGER NOT NULL, minTickets INTEGER NOT NULL, timeLeft INTEGER NOT NULL, ticketsSold INTEGER NOT NULL, completed BOOL NOT NULL ) ''') cur.execute(''' CREATE TABLE entrants( ID PRIMARY KEY, userID INTEGER NOT NULL, userAddress STRING NOT NULL, raffleID INTEGER tickets INTEGER NOT NULL, FOREIGN KEY(raffleID) REFERENCES raffles(raffleID) ) ''')
so there'd be a new row in entrants in the table every time a user enters a raffle. I'm just not sure if this is the best way of handling that data 😅

slate swan
#

Can anyone help me code a discord bot on vsc

dense flower
#

"i wont promote" ~ Promotes

slate swan
#

Yeah. But just to show you guys.

slate swan
slate swan
wise jewel
#

!warn 763833414976929812 This is a promotion, no matter what you call it. See rule 6.

unkempt canyonBOT
#

failmail :ok_hand: applied warning to @slate swan.

tall temple
#

how to write spaces in discord.Option for slash command ?

#

like ```py
async def test(ctx, test test : discord.Option(str, "some test", required = True)

slate swan
#

How are you guys storing discord oauth2 tokens?

#

Feels like leaving them plain in a database isn’t the best thing to do

mild lava
#

if my discord bot was added to a bunch of servers with only the bot permission scope (this was before slash commands existed), and i want to update the bot to use slash commands, does this bot need to be re-added to every server with new permissions (applications.commands)?

#

wondering if anyone has gone through the same thing, and how to deal with it

upbeat gust
mild lava
upbeat gust
royal pumice
#

I made a discord bot that daltonizes images (increased the contrast) so that colorblind people could see them. And I added a experimental function which can only detect RGB rn

median sand
#

Anyone know how to use BeautifulSoup4 and could possible help me with some web scraping errors im getting with my bot?

median sand
shrewd apex
#

Any reason ur not using some dnd api or not pre scraping the data storing it in a db and using it later?

#

scraping data during runtime is not usually a good idea

median sand
shrewd apex
shrewd apex
#

then load the file to memory when starting the bot

#

that way low latency plus less prone to errors

#

u can update ur data later too if new stuff is added make a little script for that

median sand
#

I could make it a local db hmmm

shrewd apex
#

ur not getting my point my point is store the data in a json or db file ur hosting service will pull that too

median sand
#

but i would need to be able to scrape the info anyway to save it

shrewd apex
#

make a seperate script for that

#

easier to debug them separately

median sand
#

yeah i realised i missed what you were saying

shrewd apex
#

use requests with soup or smn

median sand
#

im new to using BeautifulSoup4 and db's first time using BeautifulSoup4 today

shrewd apex
#

then its a good day to learn new stuff 👍

median sand
#

never messed with db's before either

shrewd apex
#

dbs or json its optional in this case pick either

#

since its gonna be a read only file

median sand
#

same with json lol i've only made small single propose bots ;-;

#

first time trying a more complex bot

shrewd apex
#

gl

slate swan
#

what event is passed when server loses a boost?

#

None on its own, only a GUILD_MEMBER_UPDATE event as premium_since changes

#

tysm

vale wing
#

How much your "hosting service" is

median sand
vale wing
#

You can use VPS free tier

median sand
#

without putting in money you get a few 100 hours of runtime

vale wing
#

Still will be better than this

slate swan
median sand
slate swan
vale wing
#

Free options

  • digital ocean - free 200$ for 2 months
  • amazon AWS - free for 1 year
  • oracle cloud - not sure, must be completely free
  • microsoft azure - free for one year then some services are available

@median sand

median sand
vale wing
#

Still better than "hosting service"

slate swan
#

Gl even getting a free slot

#

And chances is ur data might be deleted

slate swan
vale wing
#

I never used it myself tho

slate swan
#

Either you get banned after a few hours/days for no apparent reason, or you simply cannot use it at all

#

Just get a 50 dollar dedicated from hetnzer or whatever they are called

#

Never worry again

vale wing
#

50$/mo?

slate swan
#

Ya

vale wing
#

That's like for million servers bot

slate swan
#

They got good deals

#

For a random and small Discord bot, super useful

vale wing
#

3$/mo is good for small bots

slate swan
#

Oh small

vale wing
#

Galaxygate got that

median sand
#

Anyone know how to make my item_type:str a list for a user to pick from

@client.tree.command(name='item', description="Allows you to search for an item")
async def item(interaction: discord.Interaction, item_type: str, item_name: str):```
vale wing
#

But yeah in terms of free tier all those options I mentioned except oracle apparently

slate swan
#

Im sure a 5 dollar per month from vultr, linode, digital ocean is good

#

These 3 services give a trial

#

Aws is good until ur trial ends than u get hit with them expensive server bills

median sand
#

My usage with Railway and running 3 small bots

median sand
#

Costing $1.42~ a month and i get $5 free credit

slate swan
median sand
#

so i never spend the $5 i put in only the free credit

slate swan
#

I got a database, key vault, vps on aws

slate swan
#

Sparkedhost 1 dollar per month

#

Prolly would work if ur bot as its small

vale wing
#

I use aeza.net cause it's one of few good options for russians since sanctions

slate swan
#

Rip

vale wing
#

They are getting ddos attacks and net maintenance but compensate that with free hosting time

#

Like I got one free month after 2 ddoses

timber wren
#

hey
i wanted to make a something like a stats bot
that displays members in locked voice channels
and I dont know where to start from except how to fetch the numbers
do i use loops, events or what?
any help is appreciated, thanks a lot :)

slate swan
#

Probably a task running every 10 minutes or something in the background

vale wing
slate swan
#

Then to fetch the numbers you need to get a guild object in the first place

#

That way you're sure you won't get hit by rate limits in case people join/leave your server every now and then

timber wren
#

like do i need a while loop

#

to keep checking if someone is joining or not?

slate swan
#

For that you have events

#

E.g.

@bot.listen()
async def on_member_join(member: discord.Member):
  print(f"{member} joined")
timber wren
# slate swan For that you have events

mhm so will this work:

while true:
  async def on_member_join():
    channel = utils.get(guild.channels, id=id)
    member_count = member_count = len(ctx.guild.members) 
    await channel.edit(name = f"member_count")
  async def on_member_leave():
    #same_shit as before

slate swan
#

No while loop

timber wren
#

mhm

slate swan
#

Just the above

timber wren
#

@bot.listen()

#

okay

slate swan
#

No need to use utils.get either

slate swan
#

There's no such ctx in events as well, so you can use member.guild.members

#

f-strings should have {} as well:

await channel.edit(name=f"member_count") # Not good
await channel.edit(name=f"{member_count}") # Good
vale wing
#

I was about to say "yOu sHoulD cAsT to StR wiTh str()" but suddenly remembered there are no style regulations to it

#

Or are there

#

Now you leaked your IP to everyone

#

And phone

#

And token

#

@slim plover yo man delete this asap

timid spade
#

i have this one code working perfectly on host
but when i run on my pc it gives error

#

i dont get it its the same exact code

#

role = get(interaction.guild.roles, name= item)
according to error the above line is returning a coroutine

north kiln
#

then you await the coroutine?

timid spade
#

how do i get role object from role name now

north kiln
#

I assume it is because the get is treated as dict.get()

#

just send the whole code ig

timid spade
#

well

slate swan
#

where do you import get function

#

You probably overwrite the get function

#

Consider using utils.get instead of importing the way to use get  directly

timid spade
slate swan
#

Do you have any function named get?

#

Also where do you have the id varriable you pass into the get function

timid spade
slate swan
#

Cause looks Like you are passing built in id function

timid spade
#

i thinks its causing the issue

slate swan
#

Looks like

#

If you want to have get command you can do this:

@client.command(name="get")
async def random_name(...):
    ...```
timid spade
#

also @slate swan you ever had a youtube channel?

slate swan
#

I have a google account that has a youtube channel linked to it just like the average users that use and interact on youtube, yes

fiery hare
#

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

formal basin
#

how do i give a role using a button

smoky sinew
#

!d discord.Member.add_roles

unkempt canyonBOT
#

await add_roles(*roles, reason=None, atomic=True)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Gives the member a number of [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s.

You must have [`manage_roles`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.manage_roles "discord.Permissions.manage_roles") to use this, and the added [`Role`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Role "discord.Role")s must appear lower in the list of roles than the highest role of the member.
formal basin
smoky sinew
median sand
#

Im having an issue with choices/options when writing my command im using @client.tree.command

thin raft
#

code?

median sand
#

Here is the start of my command```py

Define the Item Types

item_types = {
"Adventuring Gear",
"Armor and Shields",
"Trinkets",
"Weapons",
"Firearms",
"Explosives",
"Wondrous items",
"Currency",
"Poisons",
"Tools",
"Siege Equipment"
}

Command to find a item using the item's type & name

@client.tree.command(name='item', description="Allows you to search for an item")
async def item(interaction: discord.Interaction, item_type: str, item_name: str):```

#

I'm wanting the item_types to be the options for item_type: str

smoky sinew
#

might be a better idea to use Choice though

#

autocomplete is usually for data that can change

thin raft
#

you can do that? instead of autocomplete?

vocal snow
#

!d discord.app_commands.choices

unkempt canyonBOT
#

@discord.app_commands.choices(**parameters)```
Instructs the given parameters by their name to use the given choices for their choices.

Example...
smoky sinew
#

you can use either literal, choices, or autocomplete

#

actually i don't know if x[*y] is valid

#

nvm then

#

oh it is valid

smoky sinew
#

from typing import Literal at the very top

median sand
#

Im getting the errorUnpacked arguments cannot be used in type argument lists

smoky sinew
#

and use item_type: Literal[*item_types]

median sand
#
# Define the Item Types
item_types = {
        "Adventuring Gear",
        "Armor and Shields",
        "Trinkets",
        "Weapons",
        "Firearms",
        "Explosives",
        "Wondrous items",
        "Currency",
        "Poisons",
        "Tools",
        "Siege Equipment"
    }


# Command to find a item using the item's type & name
@client.tree.command(name='item', description="Allows you to search for an item")
async def item(interaction: discord.Interaction, item_type: typing.Literal[*item_types], item_name: str):```
smoky sinew
#

strange, works for me

#
>>> from typing import Literal
>>> x = {1, 2, 3}
>>> def y(z: Literal[*x]) -> None:                              ...    ...     print(z)
>>> y(1)
1
median sand
#
(variable) item_types: set[str]```
smoky sinew
#

do you get that error when running it?