#discord-bots

1 messages · Page 194 of 1

naive umbra
#

is there a bug you've encountered?

slate swan
shrewd fjord
#

Code?

naive umbra
#

ah I see now, the if statement is logically incorrect, it should be:

if language != "hebrew" or language != "english":
#

!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.")
gentle nova
#

@shrewd fjordspooooky scarrryyyy sceletons

shrewd fjord
#

cd

#

xd

naive umbra
slate swan
#
        if language != "hebrew" or language != "english":
            await ctx.send("Please choose english or hebrew!")
        else:```
sturdy shadow
#

where do I put the ephermal (no idea how to spell it) to make it where only the person who reacted with the original menu can see the new menu.

naive umbra
slate swan
#

instead or

#

works!

naive umbra
#

kinda also got confused, you should be using and instead of or

#

if language != "hebrew" and language != "english": should also wokr

slate swan
#

ty now ill try figure out how to make the text change somehow

#

like does it has docs

#

or somewhere i can read abt it

naive umbra
#

or write responses in both of the languages and pick one depending on what language is

shrewd fjord
#

Googletrans

#

Can do the work

#

!pip googletrans

unkempt canyonBOT
thin raft
#

chatgpt

#

you could use the openAI api

slate swan
naive umbra
slate swan
#

and like do that if language==hebrw and then blah blah

shrewd fjord
#

Ye

slate swan
#

thanksss!

shrewd fjord
# thin raft you could use the openAI api

You need the api token and other stuff, why would u use openai API just for translator tho, instead googletrans exist, and also openai takes time to respond with the answer kek

sturdy shadow
#

where do I put the ephermal (no idea how to spell it) to make it where only the person who reacted with the original menu can see the new menu.

naive umbra
shrewd fjord
thin raft
#

at least some months ago

#

ping me on reply

tough lance
sturdy shadow
young dagger
#

How can i make this task loop to run 24 hours after it completes updating all users?

@tasks.loop(hours=24)
async def update_elo_ratings():
    # Get all the users in the collection
    users = await collection.find().to_list(length=None)
    for user in users:
        summoner_id = user['summoner_id']
        summoner_name = get_summoner_name(summoner_id, RIOT_API_KEY)
        tier_and_rank = get_tier_and_rank(summoner_id, RIOT_API_KEY)
        elo_rating = get_elo_rating(summoner_name, summoner_id, RIOT_API_KEY)
        await collection.update_one({"summoner_id": summoner_id}, {"$set": {"summoner_name": summoner_name, "tier_and_rank": tier_and_rank, "elo_rating": elo_rating}})
        await asyncio.sleep(10)```
#

So if it takes 25 hours for it to complete. It should start again after 24 hours after it finished the task.

slate swan
#

dear tell me please is it possible to take the name of a function from a variable? for example:
x = "test"

def x()
....

sick birch
#

Seems like an XY problem

slate swan
#

help

young dagger
#

How can I do that?

slate swan
#

sorry ik its long

naive briar
unkempt canyonBOT
#

restart(*args, **kwargs)```
A convenience method to restart the internal task.

Note

Due to the way this function works, the task is not returned like [`start()`](https://discordpy.readthedocs.io/en/latest/ext/tasks/index.html#discord.ext.tasks.Loop.start "discord.ext.tasks.Loop.start").
naive briar
#

Already asked

slate swan
unkempt mauve
#

Code:

@bot.tree.command(name='guessinggame', description='Starts a guessing number game.')
async def guess(interaction, ctx, number: int):
    emb = discord.Embed(title='Guess the number!', description=f'{interaction.user} has started a number guessing game!')
    await interaction.response.send_message(embed=emb)
    response = await bot.wait_for('message')
    guess = int(response.content)
    if guess == response:
      await ctx.send('You have guessed the number!')```
ERROR:
```Traceback (most recent call last):
  File "main.py", line 25, in <module>
    async def guess(interaction, ctx, number: int):
  File "/home/runner/MyPythonBot/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 889, in decorator
    command = Command(
  File "/home/runner/MyPythonBot/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 685, in __init__
    self._params: Dict[str, CommandParameter] = _extract_parameters_from_callback(callback, callback.__globals__)
  File "/home/runner/MyPythonBot/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 390, in _extract_parameters_from_callback
    raise TypeError(f'parameter {parameter.name!r} is missing a type annotation in callback {func.__qualname__!r}')
TypeError: parameter 'ctx' is missing a type annotation in callback 'guess'```
slate swan
#

Code:

#
@bot.event
async def on_ready():
    print(f"{bot.user.name} is online!")
    bot.add_view(MyButton())
    bot.staff_view_added=True  
    setattr(bot, "db", await aiosqlite.connect("main.db"))
    async with bot.db.cursor() as cursor:
        await cursor.execute("CREATE TABLE IF NOT EXISTS afk (user INTEGER, guild INTEGER, reason TEXT)")
        await cursor.execute("CREATE TABLE IF NOT EXISTS warns (user INTEGER, reason TEXT, time INTEGER, guild INTEGER)")
        await cursor.execute("CREATE TABLE IF NOT EXISTS role (guild INTEGER, role_id INTEGER)")
#await cursor.execute("ALTER TABLE role ADD COLUMN language TEXT")

@bot.command()
@commands.has_permissions(administrator=True)
async def set_language(ctx, language = None):
    if language ==None:
        await ctx.send("Please write `hebrew`/`english`")
    else:
        if language not in ["hebrew", "english"]:            
            await ctx.send("Please choose english or hebrew!")
        else:
            async with aiosqlite.connect("main.db") as db:
                async with db.cursor() as cursor:   
                    await cursor.execute('SELECT language FROM role WHERE guild = ?', (ctx.guild.id,))
                    language = await cursor.fetchone()
                    if language:
                        await cursor.execute('UPDATE role SET language = ? WHERE guild = ?', (language, ctx.guild.id,))
                    else:
                        await cursor.execute('INSERT INTO role (language, guild) VALUES (?, ?)', (language, ctx.guild.id,))
                await ctx.send(f"Successfuly set the helpme language to - {language}")
                await db.commit()```

Error when i wrote set_language english:

```Command raised an exception: InterfaceError: Error binding parameter 0 - probably unsupported type.```
unkempt canyonBOT
#

Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.

A full traceback could look like:

Traceback (most recent call last):
  File "my_file.py", line 5, in <module>
    add_three("6")
  File "my_file.py", line 2, in add_three
    a = num + 3
        ~~~~^~~
TypeError: can only concatenate str (not "int") to str

If the traceback is long, use our pastebin.

naive briar
#

And what's the point of setting an db connection if you're going to create another connection anyway

slate swan
#

didnt understand

#

#await cursor.execute("ALTER TABLE role ADD COLUMN language TEXT")
like bc of that?

shrewd fjord
#

Yes

slate swan
#

oh f

#

how do i remove it then

#

does await cursor.execute("ALTER TABLE role REMOVE COLUMN language TEXT") isnt an option

shrewd fjord
slate swan
#

oh i did

shrewd fjord
#

Idk kek

slate swan
#

i did it as a note

shrewd fjord
#

Wait what was ur problem tho xd

pseudo saffron
#
class boxengame(discord.ui.View):
    @discord.ui.button(label='Spieler 1 : 0', style=discord.ButtonStyle.red)
    async def Spieler1Boxen(self, interaction: discord.Interaction,button: discord.ui.Button):
        if self.bot.boxenspieler1id == interaction.user.id:
            self.bot.boxenspieler1 += 1
            button.label = f'Spieler 1 : {str(self.bot.boxenspieler1)}'
        await interaction.response.edit_message(view=self)
    @discord.ui.button(label='TrennWand', style=discord.ButtonStyle.secondary)
    async def Trennwand(self,interaction:discord.Interaction,button:discord.ui.Button,disabled=True):
        print('LOL')
    @discord.ui.button(label='Spieler 2 : 0', style=discord.ButtonStyle.red)
    async def Spieler2Boxen(self, interaction: discord.Interaction,button: discord.ui.Button):
        if self.bot.boxenspieler2id == interaction.user.id:
            self.bot.boxenspieler2 += 1
            button.label = f'Spieler 2 : {str(self.bot.boxenspieler2)}'
        await interaction.response.edit_message(view=self)```
#

how can i use bot variables here

#

AttributeError: 'boxengame' object has no attribute 'bot'

slate swan
shrewd fjord
#

wdym bot vat?

#

Var*

pseudo saffron
#

bot vars

shrewd fjord
# slate swan at first it was no column language

Listen first of all... You should add the language column on the CREATE TABLE execution, then u should add the alter line then run the code, then stop the code, remove the alter line to avoid error and then run the code again

pseudo saffron
shrewd fjord
shrewd fjord
pseudo saffron
#

Traceback (most recent call last):
File "c:\Users\schwa\OneDrive\Desktop\Frankos Discord Bot.venv\lib\site-packages\discord\ui\view.py", line 425, in _scheduled_task
await item.callback(interaction)
File "C:\Users\schwa\OneDrive\Desktop\Frankos Discord Bot\cogs\misc.py", line 11, in Spieler1Boxen
if self.bot.boxenspieler1id == interaction.user.id:
AttributeError: 'boxengame' object has no attribute 'bot'

shrewd fjord
#

yeah self.bot u can define it on super or on init
like
self.bot="your bot instance here"

pseudo saffron
shrewd fjord
#

tho boxensplier1id will still be undefined and throw error

pseudo saffron
#
class boxengame(discord.ui.View):
    @discord.ui.button(label='Spieler 1 : 0', style=discord.ButtonStyle.red)
    async def Spieler1Boxen(self, interaction: discord.Interaction,button: discord.ui.Button):
        if self.bot.boxenspieler1id == interaction.user.id:
            self.bot.boxenspieler1 += 1
            button.label = f'Spieler 1 : {str(self.bot.boxenspieler1)}'
        await interaction.response.edit_message(view=self)
    @discord.ui.button(label='TrennWand', style=discord.ButtonStyle.secondary)
    async def Trennwand(self,interaction:discord.Interaction,button:discord.ui.Button,disabled=True):
        print('LOL')
    @discord.ui.button(label='Spieler 2 : 0', style=discord.ButtonStyle.red)
    async def Spieler2Boxen(self, interaction: discord.Interaction,button: discord.ui.Button):
        if self.bot.boxenspieler2id == interaction.user.id:
            self.bot.boxenspieler2 += 1
            button.label = f'Spieler 2 : {str(self.bot.boxenspieler2)}'
        await interaction.response.edit_message(view=self)

class misc(commands.Cog):

    def __init__(self, bot):
        self.bot = bot
        self.bot.boxenspieler1 = 0
        self.bot.boxenspieler2 = 0
        self.bot.boxenspieler1id = 0
        self.bot.boxenspieler2id = 0
        self.bot.boxenspieler1name = ''
        self.bot.boxenspieler2name = ''```
#

and if i add it

#

i get py Traceback (most recent call last): File "c:\Users\schwa\OneDrive\Desktop\Frankos Discord Bot\.venv\lib\site-packages\discord\ext\commands\bot.py", line 1349, in invoke await ctx.command.invoke(ctx) File "c:\Users\schwa\OneDrive\Desktop\Frankos Discord Bot\.venv\lib\site-packages\discord\ext\commands\core.py", line 1023, in invoke await injected(*ctx.args, **ctx.kwargs) # type: ignore File "c:\Users\schwa\OneDrive\Desktop\Frankos Discord Bot\.venv\lib\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: TypeError: boxengame.__init__() missing 1 required positional argument: 'bot'

shrewd fjord
#

Because
class variables are protected

pseudo saffron
shrewd fjord
#

It should be something like view=boxengame(bot)

pseudo saffron
#

but now i get ```py
TypeError: View.init() takes 1 positional argument but 2 were given

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

Traceback (most recent call last):
File "c:\Users\schwa\OneDrive\Desktop\Frankos Discord Bot.venv\lib\site-packages\discord\ext\commands\bot.py", line 1349, in invoke
await ctx.command.invoke(ctx)
File "c:\Users\schwa\OneDrive\Desktop\Frankos Discord Bot.venv\lib\site-packages\discord\ext\commands\core.py", line 1023, in invoke
await injected(*ctx.args, **ctx.kwargs) # type: ignore
File "c:\Users\schwa\OneDrive\Desktop\Frankos Discord Bot.venv\lib\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: TypeError: View.init() takes 1 positional argument but 2 were given

#

@shrewd fjord

slate swan
pseudo saffron
slate swan
#

You can use it anywhere with bot object

pseudo saffron
#
class boxengame(discord.ui.View):
    @discord.ui.button(label='Spieler 1 : 0', style=discord.ButtonStyle.red)
    async def Spieler1Boxen(self, interaction: discord.Interaction,button: discord.ui.Button):
        if self.bot.boxenspieler1id == interaction.user.id:
            self.bot.boxenspieler1 += 1
            button.label = f'Spieler 1 : {str(self.bot.boxenspieler1)}'
        await interaction.response.edit_message(view=self)
    @discord.ui.button(label='TrennWand', style=discord.ButtonStyle.secondary)
    async def Trennwand(self,interaction:discord.Interaction,button:discord.ui.Button,disabled=True):
        print('LOL')
    @discord.ui.button(label='Spieler 2 : 0', style=discord.ButtonStyle.red)
    async def Spieler2Boxen(self, interaction: discord.Interaction,button: discord.ui.Button):
        if self.bot.boxenspieler2id == interaction.user.id:
            self.bot.boxenspieler2 += 1
            button.label = f'Spieler 2 : {str(self.bot.boxenspieler2)}'
        await interaction.response.edit_message(view=self)

class misc(commands.Cog):

    def __init__(self, bot):
        self.bot = bot
        self.bot.boxenspieler1 = 0
        self.bot.boxenspieler2 = 0
        self.bot.boxenspieler1id = 0
        self.bot.boxenspieler2id = 0
        self.bot.boxenspieler1name = ''
        self.bot.boxenspieler2name = ''```
slate swan
#

!paste pls I’m on mobile

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
#
  • there is no init there
pseudo saffron
ionic garden
#

what's the difference between these two?

unkempt mauve
#

how can I make the bot that lets the user add as many arguments? for example, /choose first: johnny second: yes third: papa. the first two will be mandatory and the other will be optional. So 2 mandatory argument and many optional argument

chilly dove
unkempt mauve
chilly dove
#

basically yes

unkempt mauve
left fulcrum
#

Can someone send me the code that makes the status of the bot show how many members there are on the server please

left fulcrum
sick birch
#

Per-guild status

left fulcrum
sick birch
#

Let's see it

#

Since this is an API limitation

thin raft
#

maybe it tells the total amount of users?

#

sum([len(guild.members) for guild in bot.guilds]) ?

#

@left fulcrum

glad cradle
#

!d discord.ext.commands.Bot.users

unkempt canyonBOT
slate swan
#

number of users!= number of members

#

you're looking for ```py
len([m async for m in bot.get_all_members()])

naive drum
#

Do anyone have a good place for me to start with slash commands I have a old project I want to update to using slash commands

naive drum
#

404

#

Nvm

#

It’s working sorry

upper root
#

Hey guys I got a problem with pm2 could anyone help me out here?
I get this error

[PM2][ERROR] Interpreter python is NOT AVAILABLE in PATH. (type 'which python' to double check.)

When running

pm2 start main.py
upper root
#

and its where python because I am on windows

#

its literally been 1h i've been trying to fix this I feel like im gonna die

sick birch
#

You may have forgotten to check the little "Add to Path" when you installed Python

upper root
#

lemme check out but I've added it manually after

#

btw anyone knows how to send multiple embeds at once? await interaction.response.send_message(embed=embed). For example I run the command /test and I want like 5 embeds getting sent instead of one? do anyone know how. Like what code to write

hushed galleon
#

!d discord.InteractionResponse.send_message < as with most send() methods, you can use the embeds= parameter to send multiple embeds in the same message

unkempt canyonBOT
#

await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False, delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Responds to this interaction by sending a message.
upper root
chilly dove
#

so you would have to send multiple messages

upper root
upper root
chilly dove
#

it should be 25 fields not sure what 10 is referencing

upper root
#

lemme send the code here holdon

#
        records_per_embed = 10
        counter = 0
        embed_number = 1
        embed = discord.Embed(title=title.group(1), color=0x5057b5)

        sent_embeds = []

        for config in data["VenueMapConfiguration"]:
            place = config["n"]
            for sec in config["secs"]:
                row = sec["t"]
                stock = sec["q"]
                maxprice = sec["max"]
                minprice = sec["min"]

                counter += 1

                embed.add_field(name="Place", value=place, inline=True)
                embed.add_field(name="Row", value=row, inline=True)
                embed.add_field(name="Stock", value=stock, inline=True)
                if stock != 0:
                    embed.add_field(name="Lowest Price", value=minprice, inline=False)
                    embed.add_field(name="Highest Price", value=maxprice, inline=False)
                embed.add_field(name="-----------------------------", value="", inline=False)

                if counter == records_per_embed:
                    embed.set_footer(text='Mind Solution | Scraper | Embed {}'.format(embed_number),
                                     icon_url="")
                    sent_message = await interaction.response.send_message(embed=embed)
                    counter = 0
                    embed_number += 1
                    embed = discord.Embed(title="Viagogo negre", color=0x5057b5)

        if counter > 0:
            embed.set_footer(text='Mind Solution | Scraper| Embed {}'.format(embed_number),
                             icon_url="")
            await interaction.response.send_message(embed=embed)
#

any idea of how I could make it so it sends more than one embed?

chilly dove
#

you would use followup for interactions

#

interaction.followup.send

#

so initial message would be what you have interaction.response.send_message then you use the followup for further messages

upper root
#

how would I integrate it?

pseudo saffron
#

how can i desync commands on tree.sync ?

upper root
#

@chilly dove do yk how I could integrate it into the code?

pseudo saffron
#

or how to use multiple variables

#

on tree.sync

chilly dove
#

well it looks like you are doing a embed per item so assuming you keep limits in check then you would have to generate embeds upto 10 or 6000 limit then keep creating embeds in those chunks until you have gone through them all then send the first message as response.send_message then anything after that followup.send

chilly dove
pseudo saffron
#

@chilly dove await self.CommandTree.clear_commands()
AttributeError: 'Bot' object has no attribute 'CommandTree'

pseudo saffron
#

someone can explain

discord.app_commands.errors.CommandSyncFailure: Failed to upload commands to Discord (HTTP status 400, error code 50035)
In command 'exec' defined in function 'Misc3.exec'
  In parameter 'Code'
    name: Command name is invalid```
#

how to use more then one variable

#

i literlly just can use one variable

#

on tree sync

#

other will cause command name is invalid

clear elm
#

im trying to make a purge command, it deletes the amount of messages you want but it doesn't send the embed

code:

@bot.tree.command(name="purge", description="Purges the specified amount of messages.")
@commands.has_permissions(manage_messages=True)
async def purge(interaction, limit: int):
        channel = bot.get_channel(1063027652065239143)
        await interaction.channel.purge(limit=limit)
  
        embed=discord.Embed(title="Logging | Purge Command", desciption="_ _", color=0xFF5349)
        embed.add_field(name="Executed by:", value=f'{interaction.message.author}', inline=True)
        embed.add_field(name="Purged:", value=f'{limit} messages', inline=True)

        message = await channel.send(embed=embed)

        embed=discord.Embed(title="Purge Command", desciption="_ _", color=0xFF5349)
        embed.add_field(name=f'{interaction.message.author} has executed:', value="Purge Command", inline=False)

        await interaction.send(embed=embed)``` no errors.
quasi thorn
#

guys I'm kinda confused, I have a class with my cog in it, how do I load it?

pseudo saffron
upper root
#

Hey do anyone know how to fix this:

@app_commands.command(name="a", description="avenue scraper")
@app_commands.checks.has_role(1069344265404174377)
@app_commands.describe(link="Insert the venue link")
async def test(self, interaction: discord.Interaction, link: str):
    embeds = [discord.Embed(description=letter) for letter in link]
    for i, embed in enumerate(embeds):
        embed.set_footer(text=f'{i+1}/{len(embeds)}')
        try:
            await interaction.response.send_message(embed=embed)
        except Exception as e:
            print(f"An error occurred while sending the message: {e}")
        await asyncio.sleep(1)

I get this error
An error occurred while sending the message: This interaction has already been responded to before
An error occurred while sending the message: This interaction has already been responded to before

quasi thorn
#
bot = commands.Bot(command_prefix="!", intents=discord.Intents.all())
Sokobot = Sokobot(bot)
#i imported the Sokobot cog from another file 

class ArcadeBot:

    @bot.event
    async def on_ready(self):
        print(f'logging in {bot.user}')

    @bot.event
    async def setup_hook(self):
        await bot.load_extension(Sokobot)


bot.run(TOKEN)

ArcadeBot.setup_hook() missing 1 required positional argument: 'self'

clear elm
quasi thorn
clear elm
#
  File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 862, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
  File "main.py", line 163, in purge
    embed=discord.Embed(title="Logging | Purge Command", desciption="_ _", color=0xFF5349)
TypeError: Embed.__init__() got an unexpected keyword argument 'desciption'

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

Traceback (most recent call last):
  File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1242, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 876, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'purge' raised an exception: TypeError: Embed.__init__() got an unexpected keyword argument 'desciption'
quasi thorn
#

it's description

clear elm
#

oh

#

LOL

#

another error

  File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 862, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
  File "main.py", line 164, in purge
    embed.add_field(name="Executed by:", value=f'{interaction.message.author}', inline=True)
AttributeError: 'NoneType' object has no attribute 'author'

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

Traceback (most recent call last):
  File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1242, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 880, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'purge' raised an exception: AttributeError: 'NoneType' object has no attribute 'author'
#

fixed that

static holly
#

hi, can you help me? please?

clear elm
static holly
#

i have 2 traceback in my code...

smoky sinew
static holly
#

https://pastebin.com/T4BnF05J

when i enter a word:

2023-02-10 23:05:36 ERROR    discord.client Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 409, in _run_event
    await coro(*args, **kwargs)
  File "e:\SSD\Python\Code\Projets\DevBot\DiscordBot\cogcmd\leveling.py", line 32, in on_message
    async with self.bot.db.cursor() as cursor:
AttributeError: 'Bot' object has no attribute 'db'

when i enter the command:

2023-02-10 23:06:31 ERROR    discord.client Ignoring exception in on_message
Traceback (most recent call last):
  File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 409, in _run_event
    await coro(*args, **kwargs)
  File "e:\SSD\Python\Code\Projets\DevBot\DiscordBot\cogcmd\leveling.py", line 32, in on_message
    async with self.bot.db.cursor() as cursor:
AttributeError: 'Bot' object has no attribute 'db'
2023-02-10 23:06:31 ERROR    discord.ext.commands.bot Ignoring exception in command niveau
Traceback (most recent call last):
  File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 229, in wrapped
    ret = await coro(*args, **kwargs)
  File "e:\SSD\Python\Code\Projets\DevBot\DiscordBot\cogcmd\leveling.py", line 71, in niveau
    async with self.bot.db.cursor() as cursor:
AttributeError: 'Bot' object has no attribute 'db'

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

Traceback (most recent call last):
  File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1349, in invoke 
    await ctx.command.invoke(ctx)
  File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 1023, in invoke
    await injected(*ctx.args, **ctx.kwargs)  # type: ignore
  File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\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: AttributeError: 'Bot' object has no attribute 'db'    
smoky sinew
#

did you copy and paste that code @static holly

smoky sinew
#

yes but did you copy and paste it from somewhere

static holly
smoky sinew
#

can you answer the question

static holly
#

i dont understand your question

clear elm
#

...

#

code

@bot.tree.command(name="purge", description="Purges the specified amount of messages.")
@commands.has_permissions(manage_messages=True)
async def purge(interaction, limit: int):
        channel = bot.get_channel(1063027652065239143)
        await interaction.channel.purge(limit=limit)
  
        purgelogEmbed=discord.Embed(title="Logging | Purge Command", description="_ _", color=0xFF5349)
        purgelogEmbed.add_field(name="Executed by:", value=f'{interaction.user}', inline=True)
        purgelogEmbed.add_field(name="Purged:", value=f'{limit} messages', inline=True)

        await interaction.channel.send(embed=purgelogEmbed)

        purgeEmbed=discord.Embed(title="Purge Command", description="_ _", color=0xFF5349)
        purgeEmbed.add_field(name=f'{interaction.user} has executed:', value="Purge Command", inline=False)

        await interaction.send(embed=purgeEmbed)```
#

error

  File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 862, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
  File "main.py", line 172, in purge
    await interaction.send(embed=purgeEmbed)
AttributeError: 'Interaction' object has no attribute 'send'

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

Traceback (most recent call last):
  File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1242, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 880, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'purge' raised an exception: AttributeError: 'Interaction' object has no attribute 'send'```
static holly
clear elm
#

it's sending the first embed to the channel you used the command instead of the one up top

smoky sinew
#

or did you code the database feature

#

nvm

static holly
#

with a tutorial

#

the difference is that I am in a cog

smoky sinew
#

have you tried doing self.bot = await aiosqlite.connect("level.db") in __init__?

static holly
#

no

smoky sinew
clear elm
#

ohh

smoky sinew
#

an interaction can give many types of responses, such as opening a modal, editing a message, sending a message, etc

static holly
smoky sinew
static holly
#

in line 15?

static holly
smoky sinew
#

oh right

#

try asyncio.get_event_loop().run_until_complete(aiosqlite.connect("level.db"))

static holly
#

in init?

smoky sinew
#

yes

static holly
# smoky sinew yes
2023-02-10 23:35:49 ERROR    discord.client Ignoring exception in on_ready
Traceback (most recent call last):
  File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 946, in _load_from_module_spec
    await setup(self)
  File "e:\SSD\Python\Code\Projets\DevBot\DiscordBot\cogcmd\leveling.py", line 130, in setup
    await bot.add_cog(levelup(bot))
  File "e:\SSD\Python\Code\Projets\DevBot\DiscordBot\cogcmd\leveling.py", line 15, in __init__
    asyncio.get_event_loop.run_until_complete(aiosqlite.connect("level.db"))
AttributeError: 'builtin_function_or_method' object has no attribute 'run_until_complete'

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

Traceback (most recent call last):
  File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 409, in _run_event
    await coro(*args, **kwargs)
  File "e:\SSD\Python\Code\Projets\DevBot\DiscordBot\main.py", line 24, in on_ready
    await bot.load_extension("cogcmd.leveling")
  File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1012, in load_extension
    await self._load_from_module_spec(spec, name)
  File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 951, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogcmd.leveling' raised an error: AttributeError: 'builtin_function_or_method' object has no attribute 'run_until_complete'
smoky sinew
#

mb

#

get_event_loop()*

static holly
# smoky sinew get_event_loop()*
Traceback (most recent call last):
  File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 946, in _load_from_module_spec
    await setup(self)
  File "e:\SSD\Python\Code\Projets\DevBot\DiscordBot\cogcmd\leveling.py", line 130, in setup
    await bot.add_cog(levelup(bot))
  File "e:\SSD\Python\Code\Projets\DevBot\DiscordBot\cogcmd\leveling.py", line 15, in __init__
    asyncio.get_event_loop().run_until_complete(aiosqlite.connect("level.db"))
  File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 625, in run_until_complete
    self._check_running()
  File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 584, in _check_running
    raise RuntimeError('This event loop is already running')
RuntimeError: This event loop is already running

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

Traceback (most recent call last):
  File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py", line 409, in _run_event
    await coro(*args, **kwargs)
  File "e:\SSD\Python\Code\Projets\DevBot\DiscordBot\main.py", line 24, in on_ready
    await bot.load_extension("cogcmd.leveling")
  File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 1012, in load_extension       
    await self._load_from_module_spec(spec, name)
  File "C:\Users\Mathieu\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 951, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogcmd.leveling' raised an error: RuntimeError: This event loop is already running
#

@smoky sinew i delete your line?

clear elm
# smoky sinew an interaction can give many types of responses, such as opening a modal, editin...

this is the code, is it right?

@bot.tree.command(name="purge", description="Purges the specified amount of messages.")
@commands.has_permissions(manage_messages=True)
async def purge(interaction, limit: int):
        channel = bot.get_channel(1063027652065239143)
        await interaction.channel.purge(limit=limit)
  
        purgelogEmbed=discord.Embed(title="Logging | Purge Command", description="_ _", color=0xFF5349)
        purgelogEmbed.add_field(name="Executed by:", value=f'{interaction.user}', inline=True)
        purgelogEmbed.add_field(name="Purged:", value=f'{limit} messages', inline=True)

        await interaction.response.send_message(embed=purgelogEmbed)

        purgeEmbed=discord.Embed(title="Purge Command", description="_ _", color=0xFF5349)
        purgeEmbed.add_field(name=f'{interaction.user} has executed:', value="Purge Command", inline=False)

        await interaction.response.send_message(embed=purgeEmbed)```
smoky sinew
#

no

#

you can only send one response

static holly
#

i'm lost...

clear elm
smoky sinew
#

and call .send

clear elm
#

how do i do that

#

😭

#

await interaction.channel.send(embed=purgeEmbed)

#

?

smoky sinew
#

i thought you were sending it to a different channel??

clear elm
#

yeah

smoky sinew
#

you literally made a channel variable

clear elm
#

one of them, not both

smoky sinew
#

yes

#

so you send the log to the logging channel and respond to the interaction

#

you can send messages to whatever channels you want but you must respond once to the interaction

static holly
#

@smoky sinew You don't have a solution to offer me?

clear elm
smoky sinew
#

what is the point of that

clear elm
#

don't i need to add channel.send to send it to a dfifernt chanenl?

smoky sinew
#

no? interaction.channel returns the channel the interaction was executed in

clear elm
#

ohhh

#

so then how would i send it to a dfiferent channel?

smoky sinew
polar ice
#
            await message.reply(f"message here with buttons", view=SetupProcessButtons()) 

class SetupProcessButtons(discord.ui.View): 
    @discord.ui.button(label="Continue", style=discord.ButtonStyle.green)
    async def button_callback(self, button, interaction):
        await interaction.response.send_message(f"You clicked {interaction.response}!")  
    @discord.ui.button(label="Cancel", style=discord.ButtonStyle.red)
    async def button_callback(self, button, interaction):
        await interaction.response.send_message(f"You clicked {interaction.response}!")

Any ideas why only one button is showing?

smoky sinew
#

you are overriding the continue button with the cancel button

clear elm
polar ice
#

rogerrrr so i need to seperate them? SetupProcessButtonsContinue and SetupProcessButtonsCancel say?

smoky sinew
smoky sinew
polar ice
clear elm
smoky sinew
#

by snake case, i mean naming things like_this instead of LikeThis

#

PascalCase is used for class naming, and snake_case is used for functions, variables, and pretty much anything else

smoky sinew
clear elm
#

ohhhhh

polar ice
#
class SetupProcessButtons(discord.ui.View):  # Buttons which get attached when using the /setup command.
    @discord.ui.button(label="Continue", style=discord.ButtonStyle.green)
    async def button_continue(self, button, interaction):
        await interaction.response.send_message(f"You clicked {interaction.response}!")  # Button has been clicked
        
    @discord.ui.button(label="Cancel", style=discord.ButtonStyle.red)
    async def button_cancel(self, button, interaction):
        await interaction.response.send_message(f"You clicked {interaction.response}!")  # Button has been clicked**```

somethng like this? @smoky sinew
smoky sinew
#

why even have the button_ there

clear elm
#
    return await self._callback(interaction, **params)  # type: ignore
  File "main.py", line 172, in purge
    await interaction.response.send_message(embed=purgeEmbed)
  File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/interactions.py", line 769, in send_message
    await adapter.create_interaction_response(
  File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/webhook/async_.py", line 218, in request
    raise NotFound(response, data)
discord.errors.NotFound: 404 Not Found (error code: 10062): Unknown interaction

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

Traceback (most recent call last):
  File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1242, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 880, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'purge' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction
smoky sinew
#

you only have 3 seconds to respond to an interaction

#

you can send a message like purging... and then edit it once you're done

#

or you can defer the response

sick birch
clear elm
#

im so confused, so i cant send this?

        purgeEmbed=discord.Embed(title="Purge Command", description="_ _", color=0xFF5349)
        purgeEmbed.add_field(name=f'{interaction.user} has executed:', value="Purge Command", inline=False)

        await interaction.response.send_message(embed=purgeEmbed)```
smoky sinew
#

you can, but you're taking too long deleting the messages

#

by the time you are done purging, the interaction has already timed out

clear elm
#

ohhh

#

is there anyway to speed it up?

smoky sinew
#

there's no way to delete messages faster but if you look above i posted some ways to avoid the interaction timing out

clear elm
#

would i be able to edit a normal message to an embed?

smoky sinew
#

yes

clear elm
#

how would i do that?

smoky sinew
#

how would i edit a message?

#

by saving the message object and then calling .edit

slate swan
#

How do i check for a phrase in discord user's custom status?

smoky sinew
clear elm
#
  await interaction.send(f"Purging {limit} message(s) now...")
  await edit(embed=purgeEmbed)```
#

?

slate swan
smoky sinew
clear elm
#
  await interaction.send(f"Purging {limit} message(s) now...")
  await edit(content="Purging {limit} message(s) now...", embed=purgeEmbed)```
smoky sinew
#

same thing

clear elm
#

how do i do it

smoky sinew
#

first of all, interaction.send doesn't exist i explained that initially and second you need to save the message that it returns and use message.edit

clear elm
#

how do i save it'

thin raft
#

Fileconfiguration#getConfigurationSection.getkeys(true)
[pos_1, pos_1.x, pos_1.y, pos_1.z, pos_2, pos_2.x, pos_2.y, pos_2.z]

#

why isn't world in there?

#

nvm

#

there was an unindented space in the server config
:D

upper root
#

Hey guys do anyone know how tf i am supposed to do here? its been 2h im stuck:

        for conf in data["VenueMapConfiguration"]:
            embed_var = "embed" + str(counter)
            print(embed_var)
            embed_var = discord.Embed(title=title.group(1), color=0x50)
            embed_var.add_field(name="Venue", value="aa", inline=False)
            counter += 1
            await interaction.followup.send(embeds=embed_var)

I get this error:
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'viagogo' raised an exception: ValueError: embeds has a maximum of 10 elements.

#

im trying to send an embed for every time there's conf. So in this case there's conf 5 times. Basically it needs to be like embed1, embed2,embed3 so then I can simply send multiple embeds at ounce

lilac shuttle
#
import discord
from discord.ext import commands
import os
from dotenv import load_dotenv

load_dotenv()
token = os.getenv("TOKEN")

# Bot Init
bot = commands.Bot(command_prefix=".")
bot.load_extension("stocks_cog")

@bot.event
async def on_ready():
    print(f"Logged in as {bot.user}")

bot.run(token)
from discord.ext import commands
from discord_slash import cog_ext, SlashContext

class StockCog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot

    @cog_ext.cog_slash(name="add", guild_ids=[channelid])
    async def add(self, ctx: SlashContext, ticker: str):
        print(ctx)
        await ctx.send("yes")

    @cog_ext.cog_slash(name="remove", guild_ids=[channelid])
    async def remove(self, ctx: SlashContext, ticker: str):
        await ctx.send("no")

def setup(bot):
    bot.add_cog(StockCog(bot))
#

why is the interaction failing

clear elm
#
  File "main.py", line 157, in <module>
    async def purge(ctx, interaction, limit: int):
  File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 889, in decorator
    command = Command(
  File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 685, in __init__
    self._params: Dict[str, CommandParameter] = _extract_parameters_from_callback(callback, callback.__globals__)
  File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 390, in _extract_parameters_from_callback
    raise TypeError(f'parameter {parameter.name!r} is missing a type annotation in callback {func.__qualname__!r}')
TypeError: parameter 'interaction' is missing a type annotation in callback 'purge'```
mint walrus
#

I’ll pay you to make me a discord bot that allows you to dupe in fn save the world where you type in a command of my choice that gives you access to dupe on save the world. How it should work is you just drop what ever you wanna dupe and leave the game and it’ll be back in your inventory. Dm me I’ll explain more.

clear elm
lilac shuttle
clear elm
#
@bot.tree.command(name="purge", description="Purges the specified amount of messages.")
@commands.has_permissions(manage_messages=True)
async def purge(ctx, interaction, limit: int):
  channel = bot.get_channel(1073724291515949077)
  await interaction.response.send_message(f'Purging {limit} message(s) now...')
  await interaction.channel.purge(limit=limit)
  
  purgelogEmbed=discord.Embed(title="Logging | Purge Command", description="_ _", color=0xFF5349)
  purgelogEmbed.add_field(name="Executed by:", value=f'{interaction.user}', inline=True)
  purgelogEmbed.add_field(name="Purged:", value=f'{limit} messages', inline=True)

  await channel.send(embed=purgelogEmbed)```
smoky sinew
#

remove the ctx

silent ermine
#

Uhh quick question, when timing out a user, what exactly does it mean to use datetime.timedelta and datetime.datetime?

smoky sinew
silent ermine
smoky sinew
#

i think that will work

silent ermine
#

Yep it did. Thanks 👍

clear elm
#

how do i edit a message to an embed

smoky sinew
clear elm
#
  File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1242, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 880, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'purge' raised an exception: NameError: name 'message' is not defined
#
@bot.tree.command(name="purge", description="Purges the specified amount of messages.")
@commands.has_permissions(manage_messages=True)
async def purge(interaction, limit: int):
  channel = bot.get_channel(1073724291515949077)
  await interaction.channel.purge(limit=limit)
  
  purgeEmbed=discord.Embed(title="Purge Command", description="_ _", color=0xFF5349)
  purgeEmbed.add_field(name=f'{interaction.user} has executed:', value="Purge Command", inline=False)
  
  await interaction.response.send_message(f'Purging {limit} message(s) now...')
  await message.edit(embed=purgeEmbed)
  
  purgelogEmbed=discord.Embed(title="Logging | Purge Command", description="_ _", color=0xFF5349)
  purgelogEmbed.add_field(name="Executed by:", value=f'{interaction.user}', inline=True)
  purgelogEmbed.add_field(name="Purged:", value=f'{limit} messages', inline=True)

  await channel.send(embed=purgelogEmbed)```
smoky sinew
#

again, how is the bot going to know what message to edit

#

you assign the value send_message returns to a variable and then use that variable

#

and it's pointless having the description set as _ _ anyway because the description isn't required for an embed, in fact, you can make embeds without a title or description

graceful ermine
#

intents = discord.Intents.defualt()

intents.all()
bot = commands.Bot(command_prefix='*', case_insensitive=True, intents=intents)```
#

Idk why but it didn't did this before

smoky sinew
graceful ermine
#

it still won't work bro

smoky sinew
#

also i don't think intents.all() does anything, Intents.all creates a new instance of Intents

#

it won't update the previous one

graceful ermine
smoky sinew
graceful ermine
#

I'm not sure

#

How do I check?

smoky sinew
#

remove the intents line and print out discord.__version__

graceful ermine
#

Okay

#

@smoky sinew

#

that wont work either

#

discord has not attribute to version

smoky sinew
#

🤨

naive briar
smoky sinew
#

did you spell it right?

graceful ermine
#

Yeah

smoky sinew
#

and did you put the underscores?

graceful ermine
#

Yes

smoky sinew
graceful ermine
#

no

smoky sinew
#

do you have a folder named discord?

graceful ermine
#

No

smoky sinew
#

have you tried actually running the code and ignoring the error?

smoky sinew
naive briar
smoky sinew
graceful ermine
naive briar
#

And

graceful ermine
#

???

smoky sinew
clear elm
#

is is it supposed to be like this?

  message = await interaction.response.send_message("Purging {limit} message(s) now...", value=1)
  await message.edit(value=1, embed=purgeEmbed)```
graceful ermine
#

same thing bro

smoky sinew
#

have you tried actually running the code and ignoring the error?

graceful ermine
#

No

smoky sinew
graceful ermine
#

what's crazy is that my bot is running currently by my hosting services and it works perfectly fine!

smoky sinew
#

C:\Python310\python.exe -m pip freeze maybe?

naive briar
#

Do you really sure that you don't have a folder named discord

graceful ermine
#

No

clear elm
#
  message = await interaction.response.send_message(f"Purging {limit} message(s) now...")
  await message.edit(value="Purging {limit} message(s) now...", embed=purgeEmbed)```
like this? idk ive never done this before
smoky sinew
#

i think you mean to replace value with content

naive briar
#

send_message don't return the sent message anyway

smoky sinew
#

then you will have to get the response another way

naive briar
#

!d discord.InteractionResponse.send_message

unkempt canyonBOT
#

await send_message(content=None, *, embed=..., embeds=..., file=..., files=..., view=..., tts=False, ephemeral=False, allowed_mentions=..., suppress_embeds=False, delete_after=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Responds to this interaction by sending a message.
smoky sinew
#

you can do interaction.response.message.edit maybe instead

#

nvm that won't work

naive briar
#

!d discord.Interaction.edit_original_response

unkempt canyonBOT
#

await edit_original_response(*, content=..., embeds=..., embed=..., attachments=..., view=..., allowed_mentions=None)```
This function is a [*coroutine*](https://docs.python.org/3/library/asyncio-task.html#coroutine).

Edits the original interaction response message.

This is a lower level interface to [`InteractionMessage.edit()`](https://discordpy.readthedocs.io/en/latest/interactions/api.html#discord.InteractionMessage.edit "discord.InteractionMessage.edit") in case you do not want to fetch the message and save an HTTP request.

This method is also the only way to edit the original message if the message sent was ephemeral.
clear elm
#
  message = await interaction.response.send_message(f"Purging {limit} message(s) now...")
  await edit_original_response(content="Purging {limit} message(s) now...", embed=purgeEmbed)```
smoky sinew
#

interesting

smoky sinew
#

i guess you can remove the message = part now

#

i assumed that send_message would return a message

clear elm
naive briar
#

Do you know what instances are

smoky sinew
smoky sinew
#

vanilla discord.py has its own slash command system

lilac shuttle
#

oh

#

dude idk i haven’t made bots in a while i’m just trying to make a simple stock open/close bot

smoky sinew
#

i can give you a simple example of how to use slash commands in discord.py 2.0, other than that i don't know how discord_slash works

lilac shuttle
#

that works with me

smoky sinew
#
@app_commands.command()
async def add(self, interaction: discord.Interaction, ticker: str):
    await interaction.response.send_message("yes")

@app_commands.command()
async def remove(self, interaction: discord.Interaction, ticker: str):
    await interaction.response.send_message("no")
clear elm
lilac shuttle
#

this works with cogs?

smoky sinew
#

yep

lilac shuttle
#

and what is app_commands

naive briar
#

There's discord.py's slash commands walkthrough in the pins

smoky sinew
#

discord.app_commands

naive briar
#

Dumb bot

lilac shuttle
#

lol

lilac shuttle
smoky sinew
#

that works

naive briar
#

!d discord.app_commands.command

unkempt canyonBOT
#

@discord.app_commands.command(*, name=..., description=..., nsfw=False, auto_locale_strings=True, extras=...)```
Creates an application command from a regular function.
lilac shuttle
#

i’ll get on my pc in a few and test it

broken citrus
#

im making a coinflip command and need a bit of help

currently what i want is command to be like

!coinflip heads 100
to bet 100 on heads

i know how to make the !coinflip part, but how do i get the bot to be able to read the "heads" and the 100?

smoky sinew
#

do you want a message command?

#

if so, for the heads you can use a simple if statement, for 100 you can use an integer converter

#

converters handle the type conversion for you

broken citrus
smoky sinew
#

one sec

#

let me finish eating and then ill type an example

#

for heads tails it will give an argument error

broken citrus
#

alright

lilac shuttle
#
import discord
from discord import app_commands, commands

class StockCog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        
    @app_commands.command()
    async def add(self, interaction: discord.Interaction, ticker: str):
        await interaction.response.send_message("yes")

    @app_commands.command()
    async def remove(self, interaction: discord.Interaction, ticker: str):
        await interaction.response.send_message("no")
    
    
def setup(bot):
    bot.add_cog(StockCog(bot))
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 606, in _load_from_module_spec
    spec.loader.exec_module(lib)
  File "<frozen importlib._bootstrap_external>", line 883, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "/Users//Documents/Programming Projects/Stock Opening : Closing Bot/stocks_cog.py", line 2, in <module>
    from discord import app_commands, commands
ImportError: cannot import name 'app_commands' from 'discord' (/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/discord/__init__.py)
smoky sinew
#

discord.commands doesn't exist

#

it's discord.ext.commands

lilac shuttle
#
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/discord/ext/commands/bot.py", line 606, in _load_from_module_spec
    spec.loader.exec_module(lib)
  File "<frozen importlib._bootstrap_external>", line 883, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "/Users//Documents/Programming Projects/Stock Opening : Closing Bot/stocks_cog.py", line 2, in <module>
    from discord import app_commands
ImportError: cannot import name 'app_commands' from 'discord' (/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/site-packages/discord/__init__.py)
#
import discord
from discord import app_commands
from discord.ext import commands
clear elm
#
@bot.tree.command(name="purge", description="Purges the specified amount of messages.")
@commands.has_permissions(manage_messages=True)
async def purge(interaction, limit: int):
  channel = bot.get_channel(1073724291515949077)
  await interaction.channel.purge(limit=limit)
  await interaction.response.send_message(f'Purging {limit} message(s).')
  
  purgeEmbed=discord.Embed(title="Logging | Purge Command", color=0xFF5349)
  purgeEmbed.add_field(name="Executed by:", value=f'{interaction.user}', inline=True)
  purgeEmbed.add_field(name="Purged:", value=f'{limit} messages', inline=True)
  purgeEmbed.set_footer(text="Made by justin;#6868")

  await channel.send(embed=purgeEmbed)```

the embeds are only sent if you purge 1 message, anything else they don't send but they still get purged
loud junco
#

a list of number is considered text or bigint in postgres
im so confused with the datatype of a list of userid

#

its not bigint but i dont think its text as well

clear elm
# clear elm ```py @bot.tree.command(name="purge", description="Purges the specified amount o...
  File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1242, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 880, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'purge' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction```
slate swan
naive briar
#

They took too long to respond to the interaction

#

!d discord.InteractionResponse.defer

unkempt canyonBOT
#

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

Defers the interaction response.

This is typically used when the interaction is acknowledged and a secondary action will be done later.

This is only supported with the following interaction types...
smoky sinew
lilac shuttle
clear elm
smoky sinew
smoky sinew
smoky sinew
#

you need intents

#

hold on

clear elm
smoky sinew
smoky sinew
#

you need to respond

lilac shuttle
#
/Users//Documents/Programming Projects/Stock Opening : Closing Bot/main.py:12: RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
  bot.load_extension("stocks_cog")
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
2023-02-10 20:56:25 INFO     discord.client logging in using static token
2023-02-10 20:56:26 INFO     discord.gateway Shard ID None has connected to Gateway (Session ID: id).
#

then my logged in message

smoky sinew
#

i suggest you look at the migrating to 2.0 guide

lilac shuttle
#

do i do await bot.load_extension(path) in my on_ready()

naive briar
#

setup_hook is preferred

smoky sinew
#

don't load extensions in your on_ready

naive briar
#

!d discord.Client.setup_hook

unkempt canyonBOT
#

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

A coroutine to be called to setup the bot, by default this is blank.

To perform asynchronous setup after the bot is logged in but before it has connected to the Websocket, overwrite this coroutine.

This is only called once, in [`login()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.login "discord.Client.login"), and will be called before any events are dispatched, making it a better solution than doing such setup in the [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready") event.

Warning

Since this is called *before* the websocket connection is made therefore anything that waits for the websocket will deadlock, this includes things like [`wait_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_for "discord.Client.wait_for") and [`wait_until_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_until_ready "discord.Client.wait_until_ready")...
lilac shuttle
#

what if i did:

async def load_stocks_cog():
    async with bot:
        await bot.load_extension("stocks_cog")

bot.loop.run_until_complete(load_stocks_cog())
naive briar
#

No

smoky sinew
#

async with bot?? bot is not a context manager

naive briar
#

It is

smoky sinew
#

how

lilac shuttle
#

what do i do mane 😔

#

the setup_hook doc is vague

smoky sinew
#

oh it calls setup_hook

naive briar
lilac shuttle
#
async def my_setup_hook():
    await bot.load_extension("stocks_cog")
    print("Stocks cog loaded!")
    
bot.setup_hook = my_setup_hook

@bot.event
async def on_ready():
    print(f"Logged in as {bot.user}")

bot.run(token)
broken citrus
#

how do i get user id from <@user id>?

smoky sinew
lilac shuttle
#

nope

smoky sinew
#

what do you mean nope

lilac shuttle
#

didnt work

#

no i was replying to my own message

#

soz

naive briar
#

What didn't work then

naive briar
#

And which part of it?

smoky sinew
#

try subclassing bot

lilac shuttle
#

its some huge error message

naive briar
#

Then send it

lilac shuttle
#

too big

#

hold on ill make a pastebin

naive briar
#

setup function of the extension also need to be a coroutine

#

And add_cog is also a coroutine

lilac shuttle
#
def setup(bot):
    bot.add_cog(StockCog(bot))
slate swan
#

Ye

lilac shuttle
#
async def setup(bot):
   await bot.add_cog(StockCog(bot))
#

?

slate swan
#

Fine 👍

lilac shuttle
#

aight its working thx

clear elm
smoky sinew
#

show code

clear elm
#
@bot.tree.command(name="purge", description="Purges the specified amount of messages.")
@commands.has_permissions(manage_messages=True)
async def purge(interaction, limit: int):
  channel = bot.get_channel(1073724291515949077)
  await interaction.channel.purge(limit=limit)
  
  purgeEmbed=discord.Embed(title="Logging | Purge Command", color=0xFF5349)
  purgeEmbed.add_field(name="Executed by:", value=f'{interaction.user}', inline=True)
  purgeEmbed.add_field(name="Purged:", value=f'{limit} messages', inline=True)
  purgeEmbed.set_footer(text="Made by justin;#6868")

  await channel.send(embed=purgeEmbed)```
smoky sinew
#

where are you responding to the interaction

clear elm
naive briar
#

Already asked

loud junco
naive briar
#

You'd have better chance in #databases and this is not related to discord bots

smoky sinew
clear elm
# naive briar What's the problem exactly

if i have multiple embed or mesages being posted when i run the command, they will only post if only one message is purged whereas if there's only one message or embed no matter how much messages i purge, it'll always post

clear elm
clear elm
naive briar
#

Then just respond to it

smoky sinew
#

@uncut flume codeblocks or pastebin please

clear elm
uncut flume
#
import discord
from discord.ext import commands

class InChannel:
    def __init__(self, channel_name):
        self.channel_name = channel_name

    def __call__(self, func):
        async def wrapper(self, ctx):
            if ctx.channel.name != self.channel_name:
                embed = discord.Embed(
                    title="Commands only allowed in #commands",
                    description=f"This command can only be used in the {self.channel_name} channel.",
                    color=discord.Color.red()
                )
                message = await ctx.send(embed=embed)
                await message.add_reaction("🗑️")
                def check(reaction, user):
                    return user == ctx.author and str(reaction.emoji) == '🗑️'
                try:
                    reaction, user = await ctx.bot.wait_for('reaction_add', timeout=30.0, check=check)
                except:
                    pass
                else:
                    await message.delete()
                    await ctx.message.delete()
                return
            return await func(self, ctx)
        return wrapper

I'm trying to make a custom decorator to block out certain channels from bot commands. When I pass the decorator to any command, the bot stops responding to the command--even in the correct channel. There's no traceback or error message, it just ignores that command with the decorator added below.
@InChannel("commands")

naive briar
#

Is that supposed to explain anything

clear elm
lilac shuttle
sick birch
lilac shuttle
#

trying to make a voting system atm

broken citrus
#

how do i get display name from <@user id>?

lilac shuttle
#

im trying to make a private server between a few friends where they can add/remove stocks from a ticker list. what i want to do is have a voting system where all eligible users have to be online (dnd, online, idle) with a 1:2 voting ratio - whichever side wins within 1-5 minutes will be added/removed from the list

smoky sinew
lilac shuttle
#

i quit

smoky sinew
#

why

clear elm
# clear elm https://gyazo.com/d29daa725e8b6045a9629b8e5abccd64 now that i added a response, ...
  File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1242, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "/home/runner/Kazue-Assistant/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 880, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'purge' raised an exception: NotFound: 404 Not Found (error code: 10062): Unknown interaction```
this is the  error i get if i add a response
smoky sinew
#

then you are taking too long try removing the purge

shrewd fjord
shrewd fjord
#

bruh

#

Tho idk wht even he is trying kek

shrewd fjord
smoky sinew
shrewd fjord
smoky sinew
#

yeah same command though

shrewd fjord
smoky sinew
#

that won't be necessary

shrewd fjord
#

Wont be, but if u close the script the current data will be gone 🗿

clear elm
acoustic root
#

Hello all.. I am new to python, my background is MERN stack - trying to create a bot but not sure how this whole virtual containers thing works. I type pipx list and get :

#

I am pretty sure it has to do with my path settup and not sure if anyone knows of this error how to fix

clear elm
#

@smoky sinew thank u for ur help 2

shrewd fjord
#

:0

#

Not thanks to me T-T

unkempt mauve
#

Code: py @tree.command(name = 'choose', description = 'Let the bot choose among upto 10 words.') async def choose(interaction, first: str, second: str, third: str = 0, fourth: str = 0, fifth: str = 0, sixth: str = 0, seventh: str = 0, eighth: str = 0, nineth: str = 0, tenth: str = 0): chosen = random.choice(first, second, third, fourth, fifth, sixth, seventh, eighth, nineth, tenth) await interaction.response.send_message(f'`{chosen}` is my choice!')

#

error:

  File "main.py", line 27, in <module>
    async def choose(interaction, first: str, second: str, third: str = 0, fourth: str = 0, fifth: str = 0, sixth: str = 0, seventh: str = 0, eighth: str = 0, nineth: str = 0, tenth: str = 0):
  File "/home/runner/MyPythonBot/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 889, in decorator
    command = Command(
  File "/home/runner/MyPythonBot/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 685, in __init__
    self._params: Dict[str, CommandParameter] = _extract_parameters_from_callback(callback, callback.__globals__)
  File "/home/runner/MyPythonBot/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 393, in _extract_parameters_from_callback
    param = annotation_to_parameter(resolved, parameter)
  File "/home/runner/MyPythonBot/venv/lib/python3.10/site-packages/discord/app_commands/transformers.py", line 844, in annotation_to_parameter
    raise TypeError(f'invalid default parameter type given ({default.__class__}), expected {valid_types}')
TypeError: invalid default parameter type given (<class 'int'>), expected (<class 'str'>, <class 'NoneType'>)```
gaunt ice
#

u gave str = 0

#

make it to str = None maybe

acoustic root
#

anyone know what causes a normalizer err

unkempt mauve
# gaunt ice make it to str = None maybe
Traceback (most recent call last):
  File "/home/runner/MyPythonBot/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 862, in _do_call
    return await self._callback(interaction, **params)  # type: ignore
  File "main.py", line 28, in choose
    chosen = random.choice(first, second, third, fourth, fifth, sixth, seventh, eighth, nineth, tenth)
TypeError: Random.choice() takes 2 positional arguments but 11 were given

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

Traceback (most recent call last):
  File "/home/runner/MyPythonBot/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1242, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/runner/MyPythonBot/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 887, in _invoke_with_namespace
    return await self._do_call(interaction, transformed_values)
  File "/home/runner/MyPythonBot/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 876, in _do_call
    raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'choose' raised an exception: TypeError: Random.choice() takes 2 positional arguments but 11 were given```
#

Okay, fixed the error, but because of giving the other 8 the value 'None', it returns 'None' when the third one is chosen even the third one has an actual value given by the user.

unkempt canyonBOT
#

random.choice(seq)```
Return a random element from the non-empty sequence *seq*. If *seq* is empty, raises [`IndexError`](https://docs.python.org/3/library/exceptions.html#IndexError "IndexError").
naive briar
#

It takes a sequence, read the docs

vale wing
#

Try using venv+pip instead, that helps to understand concept of virtual environment better

#

!venv

unkempt canyonBOT
#
Virtual Environments

Virtual environments are isolated Python environments, which make it easier to keep your system clean and manage dependencies. By default, when activated, only libraries and scripts installed in the virtual environment are accessible, preventing cross-project dependency conflicts, and allowing easy isolation of requirements.

To create a new virtual environment, you can use the standard library venv module: python3 -m venv .venv (replace python3 with python or py on Windows)

Then, to activate the new virtual environment:

Windows (PowerShell): .venv\Scripts\Activate.ps1
or (Command Prompt): .venv\Scripts\activate.bat
MacOS / Linux (Bash): source .venv/bin/activate

Packages can then be installed to the virtual environment using pip, as normal.

For more information, take a read of the documentation. If you run code through your editor, check its documentation on how to make it use your virtual environment. For example, see the VSCode or PyCharm docs.

Tools such as poetry and pipenv can manage the creation of virtual environments as well as project dependencies, making packaging and installing your project easier.

Note: When using PowerShell in Windows, you may need to change the execution policy first. This is only required once per user:

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser
vale wing
clear elm
vale wing
#

!e py inp = "15 10 20 635" ls = list(map(int, inp.split())) print(ls)

unkempt canyonBOT
#

@vale wing :white_check_mark: Your 3.11 eval job has completed with return code 0.

[15, 10, 20, 635]
unkempt mauve
vale wing
#

I mean those arguments are hell-like structure which is totally unnecessary

#

I don't know what members helped you but they didn't seem to understand that or consider it minor factor

clear elm
#
@bot.tree.command(name="unban", description="Unbans the specified user.")
@commands.has_permissions(ban_members=True)
async def unban(interaction, member: discord.Member):
  channel = bot.get_channel(1073724291515949077)
  await member.unban()
  
  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'{member}', 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)```

this is my code, i want to make it so i can unban with the user id or user and # (because obviously those are the only 2 ways, any help will be appreciated
unkempt mauve
#

lol

#

its also not possible to add as much arguments in interaction

vale wing
#

That question already was answered to, I know, that was a suggestion

vale wing
#

And convert it to list

unkempt mauve
#

nah. thats so easy

vale wing
#

I wouldn't consider eleven? parameters a good thing considering they all just get put into a list

#

That's up to you, just telling it is a bad way

unkempt mauve
naive briar
#

Convert it to actual integer

unkempt mauve
#

lmao...

naive briar
#

Then don't convert it 🤷

vale wing
naive briar
#

Simple

vale wing
unkempt mauve
#

wait, the space splits the words right. then what if the user wants two words as one string. for example "exenifix cool, catgal cool, siam dumb"

vale wing
#

Raise conversion error

naive briar
#

!e

s = "blah, blah"
print(s.split(", "))
unkempt canyonBOT
#

@naive briar :white_check_mark: Your 3.11 eval job has completed with return code 0.

['blah', 'blah']
vale wing
#

More correct term I meant

unkempt mauve
#

kek

unkempt mauve
#

great idea. I am removing the hell arguments

clear elm
unkempt mauve
#

thanks for shorting my arguments.

clear elm
#
@bot.tree.command(name="kick", description="Kicks the specified user with a reason.")
@commands.has_permissions(kick_members=True)
async def kick(interaction, member: discord.Member, *, reason:str):
  channel = bot.get_channel(1073724291515949077)
  if member.id == interaction.user.id:
    await interaction.response.send_message("You can't kick yourself!")
  elif member.guild_permissions.administrator:
    await interaction.response.send_message("You can't kick an admin!")
    await member.kick(reason=reason)

  kicklogEmbed=discord.Embed(title="Logging | Kick Command", color=0xFF5349)
  kicklogEmbed.add_field(name="Executed by:", value=f'{interaction.user}', inline=True)
  kicklogEmbed.add_field(name="Executed on:", value=f'{member}', inline=True)
  kicklogEmbed.add_field(name="Reason:", value=f'{reason}', inline=True)
  kicklogEmbed.set_footer(text="Made by justin;#6868")
  kicklogEmbed.set_author(name=f'{interaction.user}', icon_url = f'{interaction.user.display_avatar}')
  await channel.send(embed=kicklogEmbed)
  
  kickEmbed=discord.Embed(title="Kick Command", color=0xFF5349)
  kickEmbed.add_field(name=f'{interaction.user} has executed:', value="Kick Command", inline=False)
  kickEmbed.set_footer(text="Made by justin;#6868")
  kickEmbed.set_author(name=f'{interaction.user}', icon_url = f'{interaction.user.display_avatar}')
  await interaction.response.send_message(embed=kickEmbed)```
it doesn't log when i try to ban the admin but it does when i try to ban myself, is it possible to make it so it doesn't log for myself either?
slate swan
#
@bot.event
async def on_ready():
    print(f"{bot.user.name} is online!")
    bot.add_view(MyButton())
    bot.staff_view_added=True  
    setattr(bot, "db", await aiosqlite.connect("main.db"))
    async with bot.db.cursor() as cursor:
        await cursor.execute("CREATE TABLE IF NOT EXISTS afk (user INTEGER, guild INTEGER, reason TEXT)")
        await cursor.execute("CREATE TABLE IF NOT EXISTS warns (user INTEGER, reason TEXT, time INTEGER, guild INTEGER)")
        await cursor.execute("CREATE TABLE IF NOT EXISTS role (guild INTEGER, role_id INTEGER, language TEXT)")
#await cursor.execute("ALTER TABLE role ADD COLUMN language TEXT")```

so i did that and now when trying to run this command-
```py
@bot.command()
@commands.has_permissions(administrator=True)
async def set_language(ctx, language = None):
    if language ==None:
        await ctx.send("Please write `hebrew`/`english`")
    else:
        if language not in ["hebrew", "english"]:            
            await ctx.send("Please choose english or hebrew!")
        else:
            async with aiosqlite.connect("main.db") as db:
                async with db.cursor() as cursor:   
                    await cursor.execute('SELECT language FROM role WHERE guild = ?', (ctx.guild.id,))
                    language = await cursor.fetchone()
                    if language:
                        await cursor.execute('UPDATE role SET language = ? WHERE guild = ?', (language, ctx.guild.id,))
                    else:
                        await cursor.execute('INSERT INTO role (language, guild) VALUES (?, ?)', (language, ctx.guild.id,))
                await ctx.send(f"Successfuly set the helpme language to - {language}")
                await db.commit()```
it writes
```InterfaceError: Error binding parameter 0 - probably unsupported type.```
#

like i wrote that and tried doing
await cursor.execute("ALTER TABLE role DROP COLUMN language TEXT")
but then shows this error

#

you don't need to mention type of the column when dropping it

#

then just language?

#

yes.

#

oh now works

#

tyyyyy

inland venture
#

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

#

i dont know of what im supposed to fix

slate swan
#

it means the path you provided doesnt exist..

#

OperationalError: no such column: language

shows that error but i do have this column

await cursor.execute("CREATE TABLE IF NOT EXISTS role (guild INTEGER, role_id INTEGER, language TEXT)")```
slate swan
#

wdym? sqlite explorer?

shrewd apex
#

is it postgres?

#

ALTER TABLE role ADD language TEXT

#

execute this

slate swan
#

okay

inland venture
#

what is the error "logging in using static token" supposed to mean?

#

i clearly used the correct token from the discord developer portal

naive briar
#

What does your message supposed to mean

#

!traceback

unkempt canyonBOT
#

Please provide the full traceback for your exception in order to help us identify your issue.
While the last line of the error message tells us what kind of error you got,
the full traceback will tell us which line, and other critical information to solve your problem.
Please avoid screenshots so we can copy and paste parts of the message.

A full traceback could look like:

Traceback (most recent call last):
  File "my_file.py", line 5, in <module>
    add_three("6")
  File "my_file.py", line 2, in add_three
    a = num + 3
        ~~~~^~~
TypeError: can only concatenate str (not "int") to str

If the traceback is long, use our pastebin.

slate swan
shrewd apex
#

send code and full traceback

slate swan
#
@bot.event
async def on_ready():
    print(f"{bot.user.name} is online!")
    bot.add_view(MyButton())
    bot.staff_view_added=True  
    setattr(bot, "db", await aiosqlite.connect("main.db"))
    async with bot.db.cursor() as cursor:
        await cursor.execute("CREATE TABLE IF NOT EXISTS afk (user INTEGER, guild INTEGER, reason TEXT)")
        await cursor.execute("CREATE TABLE IF NOT EXISTS warns (user INTEGER, reason TEXT, time INTEGER, guild INTEGER)")
        await cursor.execute("CREATE TABLE IF NOT EXISTS role (guild INTEGER, role_id INTEGER)")
        await cursor.execute("ALTER TABLE role ADD COLUMN language TEXT")

@bot.command()
@commands.has_permissions(administrator=True)
async def set_language(ctx, language = None):
    if language ==None:
        await ctx.send("Please write `hebrew`/`english`")
    else:
        if language not in ["hebrew", "english"]:            
            await ctx.send("Please choose english or hebrew!")
        else:
            async with aiosqlite.connect("main.db") as db:
                async with db.cursor() as cursor:   
                    await cursor.execute('SELECT language FROM role WHERE guild = ?', (ctx.guild.id,))
                    language = await cursor.fetchone()
                    if language:
                        await cursor.execute('UPDATE role SET language = ? WHERE guild = ?', (language, ctx.guild.id,))
                    else:
                        await cursor.execute('INSERT INTO role (language, guild) VALUES (?, ?)', (language, ctx.guild.id,))
                await ctx.send(f"Successfuly set the helpme language to - {language}")
                await db.commit()```
```  File "c:\Users\PC\Desktop\HelpMe Bot\main.py", line 79, in set_language
    await cursor.execute('UPDATE role SET language = ? WHERE guild = ?', (language, ctx.guild.id,))
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\aiosqlite\cursor.py", line 37, in execute
    await self._execute(self._cursor.execute, sql, parameters)
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\aiosqlite\cursor.py", line 31, in _execute
    return await self._conn._execute(fn, *args, **kwargs)
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\aiosqlite\core.py", line 129, in _execute
    return await future
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\aiosqlite\core.py", line 102, in run
    result = function()
sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type.```
inland venture
#

why does this show an error? I don't get of whats wrong with this

shrewd apex
#

it is supposed to be a string

slate swan
#

okay

naive briar
#

No one can help without knowing the error

slate swan
# shrewd apex print language and check what datatype it is

(None,)

@bot.command()
@commands.has_permissions(administrator=True)
async def set_language(ctx, language = None):
    if language ==None:
        await ctx.send("Please write `hebrew`/`english`")
    else:
        if language not in ["hebrew", "english"]:            
            await ctx.send("Please choose english or hebrew!")
        else:
            async with aiosqlite.connect("main.db") as db:
                async with db.cursor() as cursor:   
                    await cursor.execute('SELECT language FROM role WHERE guild = ?', (ctx.guild.id,))
                    language = await cursor.fetchone()
                    print(language)

                    if language:
                        await cursor.execute('UPDATE role SET language = ? WHERE guild = ?', (language, ctx.guild.id,))
                    else:
                        await cursor.execute('INSERT INTO role (language, guild) VALUES (?, ?)', (language, ctx.guild.id,))
                
                await ctx.send(f"Successfuly set the helpme language to - {language}")
                await db.commit()```
shrewd apex
slate swan
#

wdym

tacit horizon
#

imagine helping in Hebrew

vale wing
clear elm
#

idk lmao

slate swan
#

Code:

@bot.event
async def on_ready():
    print(f"{bot.user.name} is online!")
    bot.add_view(MyButton())
    bot.staff_view_added=True  
    setattr(bot, "db", await aiosqlite.connect("main.db"))
    async with bot.db.cursor() as cursor:
        await cursor.execute("CREATE TABLE IF NOT EXISTS afk (user INTEGER, guild INTEGER, reason TEXT)")
        await cursor.execute("CREATE TABLE IF NOT EXISTS warns (user INTEGER, reason TEXT, time INTEGER, guild INTEGER)")
        await cursor.execute("CREATE TABLE IF NOT EXISTS role (guild INTEGER, role_id INTEGER)")
        #await cursor.execute("ALTER TABLE role ADD COLUMN language TEXT")


@bot.command()
@commands.has_permissions(administrator=True)
async def set_language(ctx, language = None):
    if language ==None:
        await ctx.send("Please write `hebrew`/`english`")
    else:
        if language not in ["hebrew", "english"]:            
            await ctx.send("Please choose english or hebrew!")
        else:
            async with aiosqlite.connect("main.db") as db:
                async with db.cursor() as cursor:   
                    await cursor.execute('SELECT language FROM role WHERE guild = ?', (ctx.guild.id,))
                    language = await cursor.fetchone()
                   
                    if language:
                        await cursor.execute('UPDATE role SET language = ? WHERE guild = ?', (language, ctx.guild.id,))
                    else:
                        await cursor.execute('INSERT INTO role (language, guild) VALUES (?, ?)', (language, ctx.guild.id,))
                 
                await ctx.send(f"Successfuly set the helpme language to - {language}")
                await db.commit()

Error:
InterfaceError: Error binding parameter 0 - probably unsupported type.

vale wing
slate swan
# vale wing Full traceback please, unclear where exactly it occurs
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 165, in wrapped
    ret = await coro(*args, **kwargs)
  File "c:\Users\PC\Desktop\HelpMe Bot\main.py", line 80, in set_language
    await cursor.execute('UPDATE role SET language = ? WHERE guild = ?', (language, ctx.guild.id,))
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\aiosqlite\cursor.py", line 37, in execute
    await self._execute(self._cursor.execute, sql, parameters)
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\aiosqlite\cursor.py", line 31, in _execute
    return await self._conn._execute(fn, *args, **kwargs)
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\aiosqlite\core.py", line 129, in _execute
    return await future
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\aiosqlite\core.py", line 102, in run
    result = function()
sqlite3.InterfaceError: Error binding parameter 0 - probably unsupported type.```
vale wing
#

Print language and try to refactor code so you don't have that if-else hell

#

Code is really hard to read due to excessive nesting

slate swan
#

true

slate swan
# vale wing Print language and try to refactor code so you don't have that if-else hell

@bot.command()
@commands.has_permissions(administrator=True)
async def set_language(ctx, language = None):
    if language ==None:
        await ctx.send("Please write `hebrew`/`english`")
    else:
        if language not in ["hebrew", "english"]:            
            await ctx.send("Please choose english or hebrew!")
        else:
            async with aiosqlite.connect("main.db") as db:
                async with db.cursor() as cursor:   
                    await cursor.execute('SELECT language FROM role WHERE guild = ?', (ctx.guild.id,))
                    language = await cursor.fetchone()
                   print(language)
                    if language:
                        await cursor.execute('UPDATE role SET language = ? WHERE guild = ?', (language, ctx.guild.id,))
                    else:
                        await cursor.execute('INSERT INTO role (language, guild) VALUES (?, ?)', (language, ctx.guild.id,))
                 
                await ctx.send(f"Successfuly set the helpme language to - {language}")
       ``` like that?
shrewd fjord
#

language=....
print(....)

slate swan
#

yeah i did that

#

prints (None,)

shrewd fjord
#

What's the problem btw?

slate swan
#

InterfaceError: Error binding parameter 0 - probably unsupported type.

hard olive
#

I want to make a bot which will reply/send .MP4/.jpeg of the meme I wanna share

upper root
#

Hello guys who could help me with interaction.followup.send it’s been since yesterday I’ve been trying to fix my code but doesn’t work

#

I have made a loop that sends an embed for every item I have

#

But it simply doesn’t work any idea of how I could do it ?

naive briar
upper root
#
        for conf in data["VenueMapConfiguration"]:
            embed_var = "embed" + str(counter)
            print(embed_var)
            embed_var = discord.Embed(title=title.group(1), color=0x50)
            embed_var.add_field(name="Venue", value="aa", inline=False)
            counter += 1
            await interaction.followup.send(embeds=embed_var)

I get this error:
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'viagogo' raised an exception: ValueError: embeds has a maximum of 10 elements.

upper root
vale wing
clear elm
#
@bot.tree.command(name="kick", description="Kicks the specified user with a reason.")
@commands.has_permissions(kick_members=True)
async def kick(interaction, member: discord.Member, *, reason:str):
  channel = bot.get_channel(1073724291515949077)
  if member.id == interaction.user.id:
    await interaction.response.send_message("You can't kick yourself!")
  elif member.guild_permissions.administrator:
    await interaction.response.send_message("You can't kick an admin!")
    await member.kick(reason=reason)

  kicklogEmbed=discord.Embed(title="Logging | Kick Command", color=0xFF5349)
  kicklogEmbed.add_field(name="Executed by:", value=f'{interaction.user}', inline=True)
  kicklogEmbed.add_field(name="Executed on:", value=f'{member}', inline=True)
  kicklogEmbed.add_field(name="Reason:", value=f'{reason}', inline=True)
  kicklogEmbed.set_footer(text="Made by justin;#6868")
  kicklogEmbed.set_author(name=f'{interaction.user}', icon_url = f'{interaction.user.display_avatar}')
  await channel.send(embed=kicklogEmbed)
  
  kickEmbed=discord.Embed(title="Kick Command", color=0xFF5349)
  kickEmbed.add_field(name=f'{interaction.user} has executed:', value="Kick Command", inline=False)
  kickEmbed.set_footer(text="Made by justin;#6868")
  kickEmbed.set_author(name=f'{interaction.user}', icon_url = f'{interaction.user.display_avatar}')
  await interaction.response.send_message(embed=kickEmbed)```
it doesn't log when i try to kick the admin but it does when i try to kick myself, is it possible to make it so it doesn't log for myself either?
slate swan
vale wing
#

And about refactoring, you should just do this where possible

# how you do
if cond:
  # if stuff
else:
  # else stuff

# how you should do
if cond:
  # if stuff
  return
# else stuff```
#

Nesting level will be greatly reduced

slate swan
#

@vale wing fixed it!

#

had to change the parameter name

vale wing
# slate swan prints (None,)

So basically, fetchone returns tuple containing language, you just need to get the first element, it will be the value you need

vale wing
#

And that's why I dislike standard sqlite wrappers / aiosqlite

#

Those tuples everywhere are annoying

slate swan
#

what do i define hebrew to be like hebrew=the embed or like what

vale wing
#

And you are missing return statements in those blocks

upper root
#

And I genuinely don’t know how to do anymore I’ve tried everything.

vale wing
#

Should look like this

if member.id == interaction.user.id:
    await interaction.response.send_message("You can't kick yourself")
    return
if member.guild_permissions.administrator:  # not even necessary to use elif
    await interaction.response.send_message("You can't kick admin")
    return
# the rest of code```
@clear elm
vale wing
upper root
#

But what matters is that it doesn’t send multiple embeds

upper root
#

It only send one

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
vale wing
#

And example like how the dict actually looks like

#

@slate swan you still have lots of if-elses, rethink of logical structure. What do you want your code to do?

slate swan
vale wing
#

And if language is neither of them send "bad language" embed right?

slate swan
#

yes

quasi thorn
#

guys how do I make slash commands work inside a cog? I used the @app_commands.command(name="...", description="...") but I can't see them

naive briar
quasi thorn
#

ah I thought it synced automatically

vale wing
#

@slate swan ok then beginner-friendly way is like this

if language == "lang1":
  embed = discord.Embed(...)
elif language == "lang2":
  embed = discord.Embed(...)
else:
  embed = discord.Embed(...)

await inter.send(embed=embed)```
#

If there are more languages better to use dict

slate swan
#

omg i forgot about the " option

vale wing
#

Generally it's better to use the dict

slate swan
#

thank you so muchhhh

#

ill try

upper root
unkempt mauve
#

how do I make a calculate command in discord.py. for example: /calculate problem: 6+9/3*2-4 ||i am dumb||

vale wing
unkempt canyonBOT
#

A module for evaluating math expressions without eval()

vale wing
#

skill issue

clear elm
#

💀

vale wing
clear elm
#

error:

  File "/home/runner/kazue-bot-frfr/venv/lib/python3.10/site-packages/discord/app_commands/tree.py", line 1242, in _call
    await command._invoke_with_namespace(interaction, namespace)
  File "/home/runner/kazue-bot-frfr/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 886, in _invoke_with_namespace
    transformed_values = await self._transform_arguments(interaction, namespace)
  File "/home/runner/kazue-bot-frfr/venv/lib/python3.10/site-packages/discord/app_commands/commands.py", line 852, in _transform_arguments
    transformed_values[param.name] = await param.transform(interaction, value)
  File "/home/runner/kazue-bot-frfr/venv/lib/python3.10/site-packages/discord/app_commands/transformers.py", line 181, in transform
    return await maybe_coroutine(self._annotation.transform, interaction, value)  # type: ignore
  File "/home/runner/kazue-bot-frfr/venv/lib/python3.10/site-packages/discord/utils.py", line 662, in maybe_coroutine
    return await value
  File "/home/runner/kazue-bot-frfr/venv/lib/python3.10/site-packages/discord/app_commands/transformers.py", line 620, in transform
    raise TransformerError(value, self.type, self)
discord.app_commands.errors.TransformerError: Failed to convert justin alt#6346 to Member```
#

code:

@bot.tree.command(name="unban", description="Unbans the specified user.")
@commands.has_permissions(ban_members=True)
async def unban(interaction, member: discord.Member):
  channel = bot.get_channel(1073724291515949077)
  guild = interaction.guild
  await guild.unban(discord.Object(id))
  
  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'{member}', 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)```
unkempt mauve
#

what is the function for showing errors?

vale wing
#

You need to do it like this, you can't convert banned member to User if bot doesn't share guilds with them and you can't convert it to Member at all

async def unban(inter, user: str):
    try:
        user = int(user)  # try to convert to ID
        await guild.unban(discord.Object(user))
    except ValueError:
        # do bans search```
#

@clear elm ^

slate swan
unkempt mauve
clear elm
#
@bot.tree.command(name="unban", description="Unbans the specified user.")
@commands.has_permissions(ban_members=True)
async def unban(inter, user: str):
    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'{member}', 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)```
#

is that right @vale wing

alpine oar
#

yo anyone wanna help me:

#

this is the problem Fatal error in launcher: Unable to create process using '"C:\Program Files\Python310\python.exe" "C:\Program Files\Python310\Scripts\pip.exe" install discord.py':

upper root
#

@vale wing
Thanks this works well mate, but how would you add field to it?
await interaction.response.send_message(embeds=[discord.Embed(description=f"Number {i}") for i in range(5)])

naive briar
upper root
upper root
# naive briar Just use normal for loop at this point

okay figured it out

        embeds = []
        for i in range(5):
            embed = discord.Embed(description=f"Number {i}")
            embed.add_field(name="Field 1", value="Value 1")
            embed.add_field(name="Field 2", value="Value 2")
            embeds.append(embed)
        await interaction.response.send_message(embeds=embeds)
loud junco
#

i dont even know how to save variable as list at this point for my discord bot

vale wing
#

Loop probably will look better tho

slate swan
thin raft
#

send screenshot of the db

quasi thorn
slate swan
# thin raft send screenshot of the db

changed it to

    async with aiosqlite.connect("main.db") as db:
        async with db.cursor() as cursor:   
            await cursor.execute('SELECT language, role_id FROM role WHERE guild = ?', (ctx.guild.id,))
            language, role_id = await cursor.fetchone()
            if role_id:
                role = ctx.guild.get_role(role_id[0])```

and now 
```  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 873, in prepare
    self._prepare_cooldowns(ctx)
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 856, in _prepare_cooldowns
    raise CommandOnCooldown(bucket, retry_after, self._buckets.type)  # type: ignore
nextcord.ext.commands.errors.CommandOnCooldown: You are on cooldown. Try again in 1.39s
Ignoring exception in on_command_error
Traceback (most recent call last):
  File "C:\Users\PC\AppData\Roaming\Python\Python39\site-packages\nextcord\ext\commands\core.py", line 165, in wrapped
    ret = await coro(*args, **kwargs)
  File "c:\Users\PC\Desktop\HelpMe Bot\main.py", line 141, in h
    role = ctx.guild.get_role(role_id[0])
TypeError: 'int' object is not subscriptable```
quasi thorn
#

you can't do that if role_id is an int

#

!e
my_int = 34
print([i for i in my_int])

naive briar
#

Only if people really read the error

thin raft
#

role_id is an int

thin raft
slate swan
quasi thorn
#

let me redo

thin raft
#

dont tell him

#

what happens if you iterate an int @slate swan?

strong knoll
#

Can anyone give me why when I try to unban someone there is an error:
discord.ext.commands.errors.MemberNotFound: Member "Freejakob#6358" not found.

Code:

@client.command()
@discord.ext.commands.has_role("Creator")
async def unban(ctx, *, member:discord.Member):
    banned_users = await ctx.guild.bans()
    member_name, member_discriminator = member.split("#")

    for ban_entrys in banned_users:
        users = ban_entrys.user
        if(users.name, users.discriminator) == (member_name, member_discriminator):
            await ctx.guild.unban(users)
            await ctx.send(f"{users.mention} has been unbanned")
            print(f"{member} has unbanned {users}.")
            return
slate swan
thin raft
quasi thorn
#

isn't setup_hook() ratelimited as on_ready()?

quasi thorn
unkempt canyonBOT
#

@quasi thorn :x: Your 3.11 eval job has completed with return code 1.

001 | Traceback (most recent call last):
002 |   File "<string>", line 2, in <module>
003 | TypeError: 'int' object is not subscriptable
slate swan
thin raft
#

smh

quasi thorn
#

you can string your int, take first index and then return it to int

slate swan
#

worked

thin raft
#

no

slate swan
#

well i thought i needed it cuz it worked the whole time

thin raft
#

just pass role_id as parameter

#

do you know python?

slate swan
#

yeah

naive briar
#

That member doesn't exist

quasi thorn
unkempt canyonBOT
#

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

Unbans a user from the guild.

The user must meet the [`abc.Snowflake`](https://discordpy.readthedocs.io/en/latest/api.html#discord.abc.Snowflake "discord.abc.Snowflake") abc.

You must have [`ban_members`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Permissions.ban_members "discord.Permissions.ban_members") to do this.
quasi thorn
#

just guessing

naive briar
#

The bot can't find users that is not in the server

#

Just use IDs, what is wrong with it

thin raft
#

he is just doing it wrong

strong knoll
thin raft
#

try except

naive briar
#

And why are you trying to unban a member with slash command

naive briar
#

Discord won't show users that aren't in the server

strong knoll
strong knoll
thin raft
#
@commands.command()
async def unban(self, member: discord.Member) -> None:
  try:
    member.guild.unban(member)
  except discord.NotFound:
    print("member not found")

#

is really that hard to read teh docs?

thin raft
thin raft
naive briar
strong knoll
thin raft
naive briar
#

Just use IDs or better yet, Discord's

#

Why would you even make a command for it

thin raft
#

that's right

@commands.command()
async def unban(self, ctx: commands.Context, user: discord.User) -> None:
  try:
    ctx.guild.unban(user)
  except discord.NotFound:
    print("member not found")

#

I still preffer to use user

#

because if they pass name and # or a mention it will still parse as a user

#

just preferences

naive briar
#

I don't really get the trend that people keep making a command that Discord already has

thin raft
#

(╯°□°)╯︵ ┻━┻

young dagger
#

Why am I seeing the error

discord.ext.commands.errors.MemberNotFound: Member "Cordes#9576" not found.```

When I'm using:
```python
@whois.error
async def whois_error(ctx, error):
    if isinstance(error, discord.ext.commands.errors.MemberNotFound):
        await ctx.send(f"![X_](https://cdn.discordapp.com/emojis/1062028705213452318.webp?size=128 "X_") I could not find the user `{error.argument}`.")```
#

The bot sends the message that it cannot find the user. But it also raises an error in the logs and I don't understand why.

hushed galleon
#

do you have a global/cog error handler too?

young dagger
# hushed galleon do you have a global/cog error handler too?

Oh yeah you are right, I'm using this as well:

@client.event
async def on_command_error(ctx, error):
    if isinstance(error, commands.NoPrivateMessage):
        await ctx.send(str(error))
    elif isinstance(error, commands.CommandNotFound):
        pass  # Do not handle this error and simply ignore it
    else:
        # Handle other errors here
        raise error```
hushed galleon
#

those handlers will be triggered after the command's error handler so you need them to determine whether they should handle the error

#

d.py's default is to check for the presence of a cog/command error handler, but a more flexible alternative imo is setting some kind of handled attribute on the context and checking for that

young dagger
#

@hushed galleon Could I simply add another elif clause to handle the MemberNotFound error?

hushed galleon
#

then you'd be responding to the error twice

hushed galleon
golden portal
#

consider using the command extension for prefix command instead of using startwith + on_message

naive briar
golden portal
#

first example is with command extension, the second is your approach which is not great

bot = commands.Bot('!', intents=...)

@bot.command()
async def my_command(ctx):
    await ctx.send('hello')
``` instead of ```py
client = discord.Client(intents=...)

@client.event
async def on_message(message):
    if message.content.startwith('!my_command'):
        await message.channel.send('hello')

For details: https://discordpy.readthedocs.io/en/stable/ext/commands/commands.html#ext-commands-commands

light violet
#

how do i add a normal non activity sts to a bot
like the sts i have right now

shrewd fjord
#

sts? status?

#

just remove the line
await change_presence(...) And restart the bot

strong knoll
#

Hey guys, How to make like daily rewards?

#

like database.

#

and add there a player username if he does a command and add coins to the balance

vale wing
# strong knoll Hey guys, How to make like daily rewards?

Best implementation would be this

  1. Database should have a table with id and claimed_at columns
  2. When user tries to claim daily, check if user is even present in table and if more than 1 day passed from last claim
  3. Update claim time in database
pseudo saffron
#

someone knows how to sort HybridCommands using sorted ?

vale wing
#

key kwarg

#

If you mean sorted by name it's just py sorted(commands, key=lambda x: x.name)
Pretty sure they have name attr

pseudo saffron
#

i try

pseudo saffron
strong knoll
naive briar
#

If you make it

#

Then probably

spark kite
#

Hi I am new to using cogs and I wanted to know if I have to register a cog each time when my bot comes online with "client.add_cog()" or only once.

naive briar
#

Every time

spark kite
#

ok thanks

strong knoll
#

How to create a json database (I am making daily reward in a bot)?

naive briar
#

JSON is not a database

slate swan
#

||using js as db is addictive||

strong knoll
timid spade
#

when i use the change_presence function to set a status (dnd, idle , online ) for bot
it removes the previous activity status if its not provided while using the function
how can do it so it only changes the status and dont effect the activity status

quick gust
lucid galleon
#

need a help
how to get a refresh token in the client credentials flow in spotify?

quick gust
quick gust
lucid galleon
strong knoll
#

Can anybody make me a daily reward command?

quick gust
lucid galleon
naive briar
#

Other than keep asking for more

strong knoll
#

I have this:
@client.command()
async def daily(ctx):
with open ("streak.json","r") as f:
data = json.load(f)
streak=data[f"{ctx.author.id}"]["streak"]
last_claim_stamp=data[f"{ctx.author.id}"]["last_claim"]
last_claim=datetime.fromtimestamp(float(last_claim_stamp))
now =datetime.now()
delta = now-last_claim
print(f"{streak}\n{last_claim_stamp}\n{last_claim}\n{now}\n{delta}")
if delta< timedelta(hours=24):
await ctx.send('YOU ALREADY CLAIMED YOUR DAILY in 24 hours')
return
if delta > timedelta(hours=48):
print('streak reset')
streak = 1
else:
streak+=1
daily = 45+(streak*5)
data[f'{ctx.author.id}']["streak"]=streak
data[f'{ctx.author.id}']["last_claim"]= str(now.timestamp())
with open("streak.json","w") as f:
json.dump(data,f,indent=2)
embed = discord.Embed(title="Daily", colour=random.randint(0, 0xffffff), description=f"You've claimed your daily of {daily} \n Not credited")
embed.set_footer(text=f"Your daily streak : {streak}")

await ctx.send(embed=embed)

quick gust
#

learn sql and then come back to this command, it will be light work

timid spade
#

oh thanks

timid spade
#

how can i get the current activity status of the application?

vale wing
unkempt canyonBOT
#

The activities that the user is currently doing.

Note

Due to a Discord API limitation, a user’s Spotify activity may not appear if they are listening to a song with a title longer than 128 characters. See GH-1738 for more information.

vale wing
#

Honestly I don't know if there's a better way, you can search docs by yourself, there might be

timid spade
#

idk I just have this shit habit of asking questions here which I can Google

gentle nova
#

File "<frozen os>", line 679, in getitem
KeyError: 'mongodb://127.0.0.1:27017' why cant get it working

quasi thorn
slate swan
quasi thorn
#

zam I was sure I had it loaded

#

Ig I accidentally deleted it with one of my many ctrl z

vale wing
#

@slate swan interesting pfp no cap

#

Fingerart

naive briar
#

Is it a cat

slate swan
#

nuuuuu

#

it's fingers

vale wing
#

Murder's mouth looks like cat mouth tho

#

w shaped

slate swan
vocal snow
vale wing
#

Yeah clearly the murder is a cat with hands

slate swan
#

guys, i'm having problem

#

why my discord bot is not working?

naive briar
#

You didn't call anything

#

It wouldn't start in anyway

slate swan
slate swan
shrewd fjord
naive briar
#

I don't see you call this function anywhere

#

And it's basic Python

gentle nova
#

bot.run

#

where is

#

ah u using that

shrewd fjord
#

!d asyncio.run

unkempt canyonBOT
#

asyncio.run(coro, *, debug=None)```
Execute the [coroutine](https://docs.python.org/3/glossary.html#term-coroutine) *coro* and return the result.

This function runs the passed coroutine, taking care of managing the asyncio event loop, *finalizing asynchronous generators*, and closing the threadpool.

This function cannot be called when another asyncio event loop is running in the same thread.

If *debug* is `True`, the event loop will be run in debug mode. `False` disables debug mode explicitly. `None` is used to respect the global [Debug Mode](https://docs.python.org/3/library/asyncio-dev.html#asyncio-debug-mode) settings.

This function always creates a new event loop and closes it at the end. It should be used as a main entry point for asyncio programs, and should ideally only be called once.

Example...
shrewd fjord
gentle nova
#

@naive briarHey, do you know anything about \MONGODB_URI = os.environ

slate swan
#

there's no point of using bot.start there tho

shrewd fjord
#

sarth UwUPopcorn

#

48 more mins SA_kekWait

slate swan
#

instead of the load function, setup_hook could be used, and the bot started with normal bot.run()

shrewd fjord
slate swan
shrewd fjord
#

Gf better

slate swan
#

i'm confuse about the coro thing

naive briar
#

A coroutine is returned by functions that is declared with async

#

!d async

unkempt canyonBOT
#

8.9. Coroutines

New in version 3.5.

quasi thorn
#

@vale wing@slate swan sorry for ping, but I loaded and still nothing showing up

#

now my on_ready() looks like this

    async def on_ready():
        print(f'logging in {bot.user}')
        await bot.sync_commands()
        await bot.load_extension('cogs.sokobot')
slate swan
#

why it's not working?

vale wing
slate swan
vale wing
#

You don't just copypaste function signature

slate swan
#

what you are doing is ```

  • sync the commands
  • load the cog
    what you should do ispy
  • load the cog
  • sync the cmds
quasi thorn
#

lemme try

vale wing
#

And yeah do both things in setup_hook @quasi thorn

slate swan
#

i'm confuse about the coro thing

#

give me an example, i can't get it

quasi thorn
#

HEHEHEHAW IT WORKS

vale wing
slate swan
#

you can load the cogs in setup_hook instead of the load coro

quasi thorn
#

is setup_hook less ratelimited than on ready or sum?

#

I checked the docs but it doesn't say anything regarding ratelimit

naive briar
#

on_ready can be called multiple times

quasi thorn
#

wait wha

naive briar
#

While setup_hook is only called by login once

#

!d discord.Client.setup_hook

unkempt canyonBOT
#

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

A coroutine to be called to setup the bot, by default this is blank.

To perform asynchronous setup after the bot is logged in but before it has connected to the Websocket, overwrite this coroutine.

This is only called once, in [`login()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.login "discord.Client.login"), and will be called before any events are dispatched, making it a better solution than doing such setup in the [`on_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.on_ready "discord.on_ready") event.

Warning

Since this is called *before* the websocket connection is made therefore anything that waits for the websocket will deadlock, this includes things like [`wait_for()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_for "discord.Client.wait_for") and [`wait_until_ready()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.wait_until_ready "discord.Client.wait_until_ready")...
naive briar
#

Or you're calling it yourself I guess

vale wing
#

Also just telling you can use this instead of listdir with condition, pathlib is a cool thing trust me

from pathlib import Path


for p in Path("cogs").glob("*.py"):  # this will basically iterate over py files in cogs folder, you can even include subdirs files if you provide "**/*.py" to glob
    ...```
    ...
slate swan
#

strange...

vale wing
#

I don't spanish or whatever that is

#

Could you translate that please?

#

Ah wait it's FileNotFoundError

#

You provided absolute path, while you need the relative one, just add a dot before slash so it looks like this ./cogs

#

./ is current directory, / is filesystem root

slate swan
#

and yet is the same diectory

#

but still not getting it

slate swan
vale wing
#

Yeah because you aren't running the script from project root

#

Open folder in your vsc

slate swan
#

if i try to open the folder in vsc discord.py is not detected by it

#

as you can see

vale wing
#

Ctrl+shift+p -> Python: Select Interpreter -> select interpreter which you installed dpy into. Better use venv tho

slate swan
#

okay, it worked

#
  File "C:\Users\Gabriel\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 934, in _load_from_module_spec
    spec.loader.exec_module(lib)  # type: ignore
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<frozen importlib._bootstrap_external>", line 940, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "c:\Users\Gabriel\Desktop\projetos python\RP Utilities\cogs\Ping.py", line 4, in <module>
    class Ping(commands.cog):
  File "c:\Users\Gabriel\Desktop\projetos python\RP Utilities\cogs\Ping.py", line 8, in Ping
    @commands.cog.listener()
     ^^^^^^^^^^^^^^^^^^^^^ ```

What a confuse error
vale wing
#

Case matters

#

@commands.Cog.listener()

#

And everywhere in your code it should be commands.Cog

slate swan
naive briar
#

Python is case sensitive ducky_sphere

vale wing
naive briar
#

In fact, every language probably is

vale wing
#

I feel like pascal isn't

#

And I heard that assembly isn't although I am very unsure about both

#

Yeah pascal isn't

#

I wonder who even uses pascal except schools 🧐

naive briar
#

I don't even know it exists

#

Well, didn't is probably the right word after that

vale wing
#

Yeah assembly is insensitive too

vale wing
slate swan
#

but also have their unknown advantages

vale wing
#

I avoid getting off-topic

slate swan
#

is there a command that separate strings?

#

from python?

#

i'm planning to make a bot that rolls dice

#

like 1d20 + 1dx + y... ETC

thin raft
#

!d discord.Client.start

unkempt canyonBOT
#

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

A shorthand coroutine for [`login()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.login "discord.Client.login") + [`connect()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.connect "discord.Client.connect").
thin raft
#

!d discord.Client.run

unkempt canyonBOT
#

run(token, *, reconnect=True, log_handler=..., log_formatter=..., log_level=..., root_logger=False)```
A blocking call that abstracts away the event loop initialisation from you.

If you want more control over the event loop then this function should not be used. Use [`start()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.start "discord.Client.start") coroutine or [`connect()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.connect "discord.Client.connect") + [`login()`](https://discordpy.readthedocs.io/en/latest/api.html#discord.Client.login "discord.Client.login").

This function also sets up the logging library to make it easier for beginners to know what is going on with the library. For more advanced users, this can be disabled by passing `None` to the `log_handler` parameter.

Warning

This function must be the last function to call due to the fact that it is blocking. That means that registration of events or anything being called after this function call will not execute until it returns.
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

lament mesa
slate swan
#
        File = [
            discord.File("./cogs/create/img/create_img.jpg"),
            discord.File("./cogs/create/img/create_th.png"),
        ]

        embed.set_thumbnail(url = 'attachment://create_th.png')
        embed.set_image(url = "attachment://create_img.png")
        embed.set_footer(text="text", icon_url= ctx.guild.icon.url)

        await ctx.delete()
        await ctx.send(file = File, embed = embed)

Dear tell me please. It is not possible to send 2 images to embed at once. returns the following error

#

pycord

#

okay, guys how do i get arguments from a command?

#

like, an argument insertion?

#

to my cog?

slate swan
#

Oh thanks for helping

ionic garden
#

can only the user who created a view interact with it?